Python Telegram bot api.

Overview

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API.

PyPi Package Version Supported Python versions Build Status PyPi downloads

Getting started.

This API is tested with Python Python 3.6-3.9 and Pypy 3. There are two ways to install the library:

  • Installation using pip (a Python package manager)*:
$ pip install pyTelegramBotAPI
  • Installation from source (requires git):
$ git clone https://github.com/eternnoir/pyTelegramBotAPI.git
$ cd pyTelegramBotAPI
$ python setup.py install

It is generally recommended to use the first option.

*While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling pip install pytelegrambotapi --upgrade

Writing your first bot

Prerequisites

It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN. Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.

A simple echo bot

The TeleBot class (defined in _init_.py) encapsulates all API calls in a single class. It provides functions such as send_xyz (send_message, send_document etc.) and several ways to listen for incoming messages.

Create a file called echo_bot.py. Then, open the file and create an instance of the TeleBot class.

import telebot

bot = telebot.TeleBot("TOKEN", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN

Note: Make sure to actually replace TOKEN with your own API token.

After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.

Let's define a message handler which handles incoming /start and /help commands.

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
	bot.reply_to(message, "Howdy, how are you doing?")

A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).

Let's add another handler:

@bot.message_handler(func=lambda m: True)
def echo_all(message):
	bot.reply_to(message, message.text)

This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.

Note: all handlers are tested in the order in which they were declared

We now have a basic bot which replies a static message to "/start" and "/help" commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:

bot.polling()

Alright, that's it! Our source file now looks like this:

import telebot

bot = telebot.TeleBot("TOKEN")

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
	bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda message: True)
def echo_all(message):
	bot.reply_to(message, message.text)

bot.polling()

To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands ('/start' and '/help') and arbitrary text messages.

General API Documentation

Types

All types are defined in types.py. They are all completely in line with the Telegram API's definition of the types, except for the Message's from field, which is renamed to from_user (because from is a Python reserved token). Thus, attributes such as message_id can be accessed directly with message.message_id. Note that message.chat can be either an instance of User or GroupChat (see How can I distinguish a User and a GroupChat in message.chat?).

The Message object also has a content_typeattribute, which defines the type of the Message. content_type can be one of the following strings: text, audio, document, photo, sticker, video, video_note, voice, location, contact, new_chat_members, left_chat_member, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created, supergroup_chat_created, channel_chat_created, migrate_to_chat_id, migrate_from_chat_id, pinned_message.

You can use some types in one function. Example:

content_types=["text", "sticker", "pinned_message", "photo", "audio"]

Methods

All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. getMe is renamed to get_me and sendMessage to send_message.

General use of the API

Outlined below are some general use cases of the API.

Message handlers

A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter much return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):

@bot.message_handler(filters)
def function_name(message):
	bot.reply_to(message, "This is a message handler")

function_name is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle. filters is a list of keyword arguments. A filter is declared in the following manner: name=argument. One handler may have multiple filters. TeleBot supports the following filters:

name argument(s) Condition
content_types list of strings (default ['text']) True if message.content_type is in the list of strings.
regexp a regular expression as a string True if re.search(regexp_arg) returns True and message.content_type == 'text' (See Python Regular Expressions)
commands list of strings True if message.content_type == 'text' and message.text starts with a command that is in the list of strings.
func a function (lambda or function reference) True if the lambda or function reference returns True

Here are some examples of using the filters and message handlers:

import telebot
bot = telebot.TeleBot("TOKEN")

# Handles all text messages that contains the commands '/start' or '/help'.
@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
	pass

# Handles all sent documents and audio files
@bot.message_handler(content_types=['document', 'audio'])
def handle_docs_audio(message):
	pass

# Handles all text messages that match the regular expression
@bot.message_handler(regexp="SOME_REGEXP")
def handle_message(message):
	pass

# Handles all messages for which the lambda returns True
@bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document'])
def handle_text_doc(message):
	pass

# Which could also be defined as:
def test_message(message):
	return message.document.mime_type == 'text/plain'

@bot.message_handler(func=test_message, content_types=['document'])
def handle_text_doc(message):
	pass

# Handlers can be stacked to create a function which will be called if either message_handler is eligible
# This handler will be called if the message starts with '/hello' OR is some emoji
@bot.message_handler(commands=['hello'])
@bot.message_handler(func=lambda msg: msg.text.encode("utf-8") == SOME_FANCY_EMOJI)
def send_something(message):
    pass

Important: all handlers are tested in the order in which they were declared

Edited Message handlers

@bot.edited_message_handler(filters)

channel_post_handler

@bot.channel_post_handler(filters)

edited_channel_post_handler

@bot.edited_channel_post_handler(filters)

Callback Query Handler

In bot2.0 update. You can get callback_query in update object. In telebot use callback_query_handler to process callback queries.

@bot.callback_query_handler(func=lambda call: True)
def  test_callback(call):
    logger.info(call)

Middleware Handler

A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are executed. Middleware processing is disabled by default, enable it by setting apihelper.ENABLE_MIDDLEWARE = True.

apihelper.ENABLE_MIDDLEWARE = True

@bot.middleware_handler(update_types=['message'])
def modify_message(bot_instance, message):
    # modifying the message before it reaches any other handler 
    message.another_text = message.text + ':changed'

@bot.message_handler(commands=['start'])
def start(message):
    # the message is already modified when it reaches message handler
    assert message.another_text == message.text + ':changed'

There are other examples using middleware handler in the examples/middleware directory.

TeleBot

import telebot

TOKEN = '<token_string>'
tb = telebot.TeleBot(TOKEN)	#create a new Telegram Bot object

# Upon calling this function, TeleBot starts polling the Telegram servers for new messages.
# - none_stop: True/False (default False) - Don't stop polling when receiving an error from the Telegram servers
# - interval: True/False (default False) - The interval between polling requests
#           Note: Editing this parameter harms the bot's response time
# - timeout: integer (default 20) - Timeout in seconds for long polling.
tb.polling(none_stop=False, interval=0, timeout=20)

# getMe
user = tb.get_me()

# setWebhook
tb.set_webhook(url="http://example.com", certificate=open('mycert.pem'))
# unset webhook
tb.remove_webhook()

# getUpdates
updates = tb.get_updates()
updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout):

# sendMessage
tb.send_message(chat_id, text)

# editMessageText
tb.edit_message_text(new_text, chat_id, message_id)

# forwardMessage
tb.forward_message(to_chat_id, from_chat_id, message_id)

# All send_xyz functions which can take a file as an argument, can also take a file_id instead of a file.
# sendPhoto
photo = open('/tmp/photo.png', 'rb')
tb.send_photo(chat_id, photo)
tb.send_photo(chat_id, "FILEID")

# sendAudio
audio = open('/tmp/audio.mp3', 'rb')
tb.send_audio(chat_id, audio)
tb.send_audio(chat_id, "FILEID")

## sendAudio with duration, performer and title.
tb.send_audio(CHAT_ID, file_data, 1, 'eternnoir', 'pyTelegram')

# sendVoice
voice = open('/tmp/voice.ogg', 'rb')
tb.send_voice(chat_id, voice)
tb.send_voice(chat_id, "FILEID")

# sendDocument
doc = open('/tmp/file.txt', 'rb')
tb.send_document(chat_id, doc)
tb.send_document(chat_id, "FILEID")

# sendSticker
sti = open('/tmp/sti.webp', 'rb')
tb.send_sticker(chat_id, sti)
tb.send_sticker(chat_id, "FILEID")

# sendVideo
video = open('/tmp/video.mp4', 'rb')
tb.send_video(chat_id, video)
tb.send_video(chat_id, "FILEID")

# sendVideoNote
videonote = open('/tmp/videonote.mp4', 'rb')
tb.send_video_note(chat_id, videonote)
tb.send_video_note(chat_id, "FILEID")

# sendLocation
tb.send_location(chat_id, lat, lon)

# sendChatAction
# action_string can be one of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video',
# 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.
tb.send_chat_action(chat_id, action_string)

# getFile
# Downloading a file is straightforward
# Returns a File object
import requests
file_info = tb.get_file(file_id)

file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))

Reply markup

All send_xyz functions of TeleBot take an optional reply_markup argument. This argument must be an instance of ReplyKeyboardMarkup, ReplyKeyboardRemove or ForceReply, which are defined in types.py.

from telebot import types

# Using the ReplyKeyboardMarkup class
# It's constructor can take the following optional arguments:
# - resize_keyboard: True/False (default False)
# - one_time_keyboard: True/False (default False)
# - selective: True/False (default False)
# - row_width: integer (default 3)
# row_width is used in combination with the add() function.
# It defines how many buttons are fit on each row before continuing on the next row.
markup = types.ReplyKeyboardMarkup(row_width=2)
itembtn1 = types.KeyboardButton('a')
itembtn2 = types.KeyboardButton('v')
itembtn3 = types.KeyboardButton('d')
markup.add(itembtn1, itembtn2, itembtn3)
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)

# or add KeyboardButton one row at a time:
markup = types.ReplyKeyboardMarkup()
itembtna = types.KeyboardButton('a')
itembtnv = types.KeyboardButton('v')
itembtnc = types.KeyboardButton('c')
itembtnd = types.KeyboardButton('d')
itembtne = types.KeyboardButton('e')
markup.row(itembtna, itembtnv)
markup.row(itembtnc, itembtnd, itembtne)
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)

The last example yields this result:

ReplyKeyboardMarkup

# ReplyKeyboardRemove: hides a previously sent ReplyKeyboardMarkup
# Takes an optional selective argument (True/False, default False)
markup = types.ReplyKeyboardRemove(selective=False)
tb.send_message(chat_id, message, reply_markup=markup)
# ForceReply: forces a user to reply to a message
# Takes an optional selective argument (True/False, default False)
markup = types.ForceReply(selective=False)
tb.send_message(chat_id, "Send me another word:", reply_markup=markup)

ForceReply:

ForceReply

Inline Mode

More information about Inline mode.

inline_handler

Now, you can use inline_handler to get inline queries in telebot.

@bot.inline_handler(lambda query: query.query == 'text')
def query_text(inline_query):
    # Query message is text

chosen_inline_handler

Use chosen_inline_handler to get chosen_inline_result in telebot. Don't forgot add the /setinlinefeedback command for @Botfather.

More information : collecting-feedback

@bot.chosen_inline_handler(func=lambda chosen_inline_result: True)
def test_chosen(chosen_inline_result):
    # Process all chosen_inline_result.

answer_inline_query

@bot.inline_handler(lambda query: query.query == 'text')
def query_text(inline_query):
    try:
        r = types.InlineQueryResultArticle('1', 'Result', types.InputTextMessageContent('Result message.'))
        r2 = types.InlineQueryResultArticle('2', 'Result2', types.InputTextMessageContent('Result message2.'))
        bot.answer_inline_query(inline_query.id, [r, r2])
    except Exception as e:
        print(e)

Working with entities:

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:

  • type
  • url
  • offset
  • length
  • user

Here's an Example:message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase there are multiple entities in the reply/message.
message.entities returns a list of entities object.
message.entities[0].type would give the type of the first entity
Refer Bot Api for extra details

Advanced use of the API

Asynchronous delivery of messages

There exists an implementation of TeleBot which executes all send_xyz and the get_me functions asynchronously. This can speed up you bot significantly, but it has unwanted side effects if used without caution. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.

tb = telebot.AsyncTeleBot("TOKEN")

Now, every function that calls the Telegram API is executed in a separate Thread. The functions are modified to return an AsyncTask instance (defined in util.py). Using AsyncTeleBot allows you to do the following:

import telebot

tb = telebot.AsyncTeleBot("TOKEN")
task = tb.get_me() # Execute an API call
# Do some other operations...
a = 0
for a in range(100):
	a += 10

result = task.wait() # Get the result of the execution

Note: if you execute send_xyz functions after eachother without calling wait(), the order in which messages are delivered might be wrong.

Sending large text messages

Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:

from telebot import util
large_text = open("large_text.txt", "rb").read()

# Split the text each 3000 characters.
# split_string returns a list with the splitted text.
splitted_text = util.split_string(large_text, 3000)
for text in splitted_text:
	tb.send_message(chat_id, text)

Controlling the amount of Threads used by TeleBot

The TeleBot constructor takes the following optional arguments:

  • threaded: True/False (default True). A flag to indicate whether TeleBot should execute message handlers on it's polling Thread.

The listener mechanism

As an alternative to the message handlers, one can also register a function as a listener to TeleBot.

NOTICE: handlers won't disappear! Your message will be processed both by handlers and listeners. Also, it's impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:

def handle_messages(messages):
	for message in messages:
		# Do something with the message
		bot.reply_to(message, 'Hi')

bot.set_update_listener(handle_messages)
bot.polling()

Using web hooks

When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.

There are some examples using webhooks in the examples/webhook_examples directory.

Logging

You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.

import logging

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.

Proxy

You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.

from telebot import apihelper

apihelper.proxy = {'http':'http://10.10.1.10:3128'}

If you want to use socket5 proxy you need install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn, PySocks, pyTelegramBotAPI, requests and urllib3.

apihelper.proxy = {'https':'socks5://userproxy:[email protected]_address:port'}

API conformance

Checking is in progress...

Bot API 4.5 - To be checked...

Change log

27.04.2020 - Poll and Dice are up to date. Python2 conformance is not checked any more due to EOL.

11.04.2020 - Refactoring. new_chat_member is out of support. Bugfix in html_text. Started Bot API conformance checking.

06.06.2019 - Added polls support (Poll). Added functions send_poll, stop_poll

F.A.Q.

Bot 2.0

April 9,2016 Telegram release new bot 2.0 API, which has a drastic revision especially for the change of method's interface.If you want to update to the latest version, please make sure you've switched bot's code to bot 2.0 method interface.

More information about pyTelegramBotAPI support bot2.0

How can I distinguish a User and a GroupChat in message.chat?

Telegram Bot API support new type Chat for message.chat.

  • Check the type attribute in Chat object:
if message.chat.type == "private":
	# private chat message

if message.chat.type == "group":
	# group chat message

if message.chat.type == "supergroup":
	# supergroup chat message

if message.chat.type == "channel":
	# channel message

How can I handle reocurring ConnectionResetErrors?

Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.

The Telegram Chat Group

Get help. Discuss. Chat.

More examples

Bots using this API

Want to have your bot listed here? Just make a pull requet.

Issues
  • ERROR - TeleBot:

    ERROR - TeleBot: "ConnectionError occurred, args=(ProtocolError('Connection aborted.', TimeoutError(110, 'Connection timed out')),)

    2018-01-29 08:32:07,077 (util.py:64 WorkerThread1) ERROR - TeleBot: "ConnectionError occurred, args=(ProtocolError('Connection aborted.', TimeoutError(110, 'Connection timed out')),) Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen body=body, headers=headers) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 354, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.5/http/client.py", line 1106, in request self._send_request(method, url, body, headers) File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request self.endheaders(body) File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders self._send_output(message_body) File "/usr/lib/python3.5/http/client.py", line 936, in _send_output self.send(message_body) File "/usr/lib/python3.5/http/client.py", line 908, in send self.sock.sendall(data) File "/usr/lib/python3.5/ssl.py", line 891, in sendall v = self.send(data[count:]) File "/usr/lib/python3.5/ssl.py", line 861, in send return self._sslobj.write(data) File "/usr/lib/python3.5/ssl.py", line 586, in write return self._sslobj.write(data) TimeoutError: [Errno 110] Connection timed out

    1. What version of pyTelegramBotAPI are you using? Name: pyTelegramBotAPI Version: 3.5.2

    2. What OS are you using? Linux Mint 18.2

    3. What version of python are you using? Python 3.5.2

    opened by toxidxd 34
  • Bot does not recover properly when using infinity_polling

    Bot does not recover properly when using infinity_polling

    1. What version of pyTelegramBotAPI are you using? 3.7.4

    2. What OS are you using? Raspbian

    3. What version of python are you using? 3.6.9


    Testing out bot.infinity_polling() as recommended in #1057 I noticed a bug in the recovery from exceptions:

    It seems like the bot does not recover completely from a collision from another bot instance. It crashes and restarts successfully, which is nice, but it seems to get stuck in a restart loop every 3s (sleep time on recovery). I would guess there is an implicit state that carries over the restart that still contains the cancel instruction, but I haven't found anything obvious.

    This bug can be bypassed by not starting another instance with the same token, but I assume that the same bug will also strike with other exceptions, unrelated to this cause.

    Reproduction:

    1. Start instance 1 with bot.infinity_polling() and logging.INFO
    2. Start another instance to provoke a collision
    3. stop second bot to allow instance 1 to run
    4. -> instance 1 has crashed and is stuck in restart loop afterwards

    log instance 1:

    2020-12-31 16:03:07,705 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:19:07,961 (__init__.py:489 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"
    2020-12-31 16:19:07,961 (__init__.py:496 MainThread) INFO - TeleBot: "Waiting for 0.25 seconds until retry"
    2020-12-31 16:19:11,546 (__init__.py:489 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"
    2020-12-31 16:19:11,546 (__init__.py:496 MainThread) INFO - TeleBot: "Waiting for 0.5 seconds until retry"
    2020-12-31 16:42:57,901 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:43:00,905 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:43:03,908 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:43:06,914 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:43:09,920 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    

    log instance 2:

    2020-12-31 16:19:07,872 (__init__.py:460 MainThread) INFO - TeleBot: "Started polling."
    2020-12-31 16:19:11,256 (__init__.py:489 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"
    2020-12-31 16:19:11,256 (__init__.py:496 MainThread) INFO - TeleBot: "Waiting for 0.25 seconds until retry"
    
    Process finished with exit code -1
    

    PS: Happy new year and thanks for the fast responses!

    bug 
    opened by ModischFabrications 30
  • HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot

    HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot

    Packages: pyTelegramBotAPI==3.6.3 requests==2.19.1 PySocks==1.6.8 urllib3==1.23

    OS: MacOS or Ubuntu 16 (via docker)

    Python: Python 3.5.3 or PyPy3 (also 3.5.3)

    Problem: I successfully ran a bot some hours ago but after some time it starts to throw an error. I have to use a proxy (and it worked with a proxy at the beginning). I tried HTTPS, SOCKS5 proxies and I'm sure that they are working ones but I still get this error and I suppose that Telegram servers are fine right now. There are many posts in the internet with the same error but they have no information and solutions to the problem (beside the fact that people switch to some other packages).

    Don't know if this is a bug or not, but as there are no answers in other places I decided to put it here.

    Code:

    import os
    import time
    import logging
    
    import telebot
    from telebot import apihelper
    
    # Logger
    logger = telebot.logger
    telebot.logger.setLevel(logging.DEBUG)
    
    # Configuration
    TG_PROXY = 'https://103.241.156.250:8080'
    TG_BOT_TOKEN = 'xxxxxxxx'
    
    # Set proxy
    apihelper.proxy = {'http': TG_PROXY}
    
    # Init bot
    bot = telebot.TeleBot(TG_BOT_TOKEN)
    
    # /start
    @bot.message_handler(commands=['start'])
    def send_welcome(message):
        bot.reply_to(message, "Howdy, how are you doing?")
    
    # Plain message
    @bot.message_handler(func=lambda m: True)
    def echo_all(message):
        bot.reply_to(message, message.text)
    
    # Polling
    while True:
        try:
            bot.polling(none_stop=True)
        except Exception as e:
            logger.error(e)
            time.sleep(15)
    

    Traceback:

    2018-07-05 14:33:26,589 (__init__.py:276 MainThread) INFO - TeleBot: "Started polling."
    2018-07-05 14:33:26,590 (util.py:56 PollingThread) DEBUG - TeleBot: "Received task"
    2018-07-05 14:33:26,590 (apihelper.py:45 PollingThread) DEBUG - TeleBot: "Request: method=get url=https://api.telegram.org/bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates params={'offset': 1, 'timeout': 20} files=None"
    2018-07-05 14:33:26,962 (util.py:65 PollingThread) ERROR - TeleBot: "SSLError occurred, args=(MaxRetryError("HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))",),)
    Traceback (most recent call last):
      File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 600, in urlopen
        chunked=chunked)
      File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 343, in _make_request
        self._validate_conn(conn)
      File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn
        conn.connect()
      File "/Users/max/Documents/env/site-packages/urllib3/connection.py", line 356, in connect
        ssl_context=context)
      File "/Users/max/Documents/env/site-packages/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket
        return context.wrap_socket(sock, server_hostname=server_hostname)
      File "/Users/max/pypy3/lib-python/3/ssl.py", line 385, in wrap_socket
        _context=self)
      File "/Users/max/pypy3/lib-python/3/ssl.py", line 760, in __init__
        self.do_handshake()
      File "/Users/max/pypy3/lib-python/3/ssl.py", line 996, in do_handshake
        self._sslobj.do_handshake()
      File "/Users/max/pypy3/lib-python/3/ssl.py", line 641, in do_handshake
        self._sslobj.do_handshake()
      File "/Users/max/pypy3/lib_pypy/_cffi_ssl/_stdssl/__init__.py", line 354, in do_handshake
        raise pyssl_error(self, ret)
    _cffi_ssl._stdssl.error.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/max/Documents/env/site-packages/requests/adapters.py", line 445, in send
        timeout=timeout
      File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 638, in urlopen
        _stacktrace=sys.exc_info()[2])
      File "/Users/max/Documents/env/site-packages/urllib3/util/retry.py", line 398, in increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/max/Documents/env/site-packages/telebot/util.py", line 59, in run
        task(*args, **kwargs)
      File "/Users/max/Documents/env/site-packages/telebot/__init__.py", line 158, in __retrieve_updates
        updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
      File "/Users/max/Documents/env/site-packages/telebot/__init__.py", line 128, in get_updates
        json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
      File "/Users/max/Documents/env/site-packages/telebot/apihelper.py", line 180, in get_updates
        return _make_request(token, method_url, params=payload)
      File "/Users/max/Documents/env/site-packages/telebot/apihelper.py", line 54, in _make_request
        timeout=(connect_timeout, read_timeout), proxies=proxy)
      File "/Users/max/Documents/env/site-packages/requests/sessions.py", line 512, in request
        resp = self.send(prep, **send_kwargs)
      File "/Users/max/Documents/env/site-packages/requests/sessions.py", line 622, in send
        r = adapter.send(request, **kwargs)
      File "/Users/max/Documents/env/site-packages/requests/adapters.py", line 511, in send
        raise SSLError(e, request=request)
    requests.exceptions.SSLError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))
    

    UPD:

    Tried my former code that uses python-telegram-bot with the same TG_PROXY and TG_BOT_TOKEN and everything works ok. So it's not a proxy / telegram servers or "ban" problem.

    opened by vashchukmaksim 29
  • My bot is suddenly stoping

    My bot is suddenly stoping

    I'm getting this several times a day:

    TeleBot: Exception occurred. Stopping.
    getUpdates failed. Returned result: <Response [502]>
    TeleBot: Stopped polling.
    

    Knowing that 'The 502 Bad Gateway error is an HTTP status code that means that one server received an invalid response from another server', I believe it is an error on Telegram's server, not on the API.

    So I would be happy if someone could give me an suggestion on how to treat this and make my bot automatically begin to work again.

    opened by GabrielRF 25
  • Explicitly create Threads instead of implicitly?

    Explicitly create Threads instead of implicitly?

    Threading is a complicated subject and it can lead to difficult to track bugs. By default TeleBot creates a new Thread for each registered listener and each registered message handler. Now, if two message handlers or two listeners try to access the same (not thread-safe) resource, the programmer has got a problem. So unless the programmer is aware that this library creates Threads (and knows how to handle them (locks, semaphores, queues)), Threads can be a threat ( :) ) to the stability of bots. My proposal: Create an optional create_threads parameter for the TeleBot constructor, which defaults to False. Check for this parameter when calling listeners or message handlers:

    if self.create_threads:
        t = threading.Thread(target=message_handler, args=message)
        t.start()
    else:
        message_handler(message)
    

    The drawback of this is of course program speed. The bot will block until a listener or message handler has returned. Until then the bot cannot receive new messages. But my estimation is that this drawback is less important than the overhead (for the, especially novice, programmer) of creating Threads. With an optional argument, the programmer can decide for himself whether he wants to go down the dangerous road of multithreading. Is my reasoning correct?

    opened by pevdh 22
  • Python3

    Python3 "module 'telebot' has no attribute 'TeleBot'"

    1. version of pyTelegramBotAPI is 2.3.2
    2. OS is Ubuntu 16.04 LTS 64
    3. Python version 3.5.2 Hi, i got the problem, trying to launch the first example. My code is:

    import telebot TOKEN="3156... etc" bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Howdy, how are you doing?") @bot.message_handler(func=lambda message: True) def echo_all(message): bot.reply_to(message, message.text) bot.polling()

    the terminal :

    bot = telebot.TeleBot(TOKEN) AttributeError: module 'telebot' has no attribute 'TeleBot'

    opened by Honotoo 20
  • Read timed out. (read timeout=30) Error

    Read timed out. (read timeout=30) Error

    Please answer these questions before submitting your issue. Thanks!

    1. What version of pyTelegramBotAPI are you using? six-1.11.0
    2. What OS are you using? Ubuntu 14.04.4 LTS
    3. What version of python are you using? Python 3.4.3

    Hello! I have had this error several times in the past few days and I can not fix it. I use this solution in my code (#251) but I have the same error. Can you help me? Thanks a lot!

    while True:

    try:
    
        bot.polling(none_stop=True)
    
    # ConnectionError and ReadTimeout because of possible timout of the requests library
    
    # TypeError for moviepy errors
    
    # maybe there are others, therefore Exception
    
    except Exception as e:
    
        logger.error(e)
    
        time.sleep(15)
    

    File "/usr/local/lib/python3.4/dist-packages/telebot/apihelper.py", line 54, in _make_request timeout=(connect_timeout, read_timeout), proxies=proxy) File "/usr/local/lib/python3.4/dist-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.4/dist-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.4/dist-packages/requests/adapters.py", line 521, in send raise ReadTimeout(e, request=request) requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=30)

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "bot.py", line 537, in logger.error(e)

    opened by natijauskas 19
  • pyTelegramBotAPI Bot2.0 Implementation status.

    pyTelegramBotAPI Bot2.0 Implementation status.

    Install pyTelegramBotAPI bot 2.0 branch

    $ git clone -b bot20 --single-branch https://github.com/eternnoir/pyTelegramBotAPI.git
    $ cd pyTelegramBotAPI
    $ python setup.py install
    
    • This branch has not been well tested. Still under beta.

    Bot 2.0 Implementation Status

    New Types

    • [x] InlineKeyboardMarkup
    • [x] InlineKeyboardButton
    • [x] CallbackQuery
    • [x] MessageEntity
    • [x] Venue

    New Methods

    • [x] answerCallbackQuery
    • [x] editMessageText
    • [x] editMessageCaption
    • [x] editMessageReplyMarkup
    • [x] sendVenue
    • [x] sendContact
    • [x] kickChatMember
    • [x] unbanChatMember

    Inline bots

    • [x] InlineQueryResultCachedAudio
    • [x] InlineQueryResultCachedDocument
    • [x] InlineQueryResultCachedGif
    • [x] InlineQueryResultCachedMpeg4Gif
    • [x] InlineQueryResultCachedPhoto
    • [x] InlineQueryResultCachedSticker
    • [x] InlineQueryResultCachedVideo
    • [x] InlineQueryResultCachedVoice
    • [x] InlineQueryResultArticle
    • [x] InlineQueryResultAudio
    • [x] InlineQueryResultContact
    • [x] InlineQueryResultDocument
    • [x] InlineQueryResultGif
    • [x] InlineQueryResultLocation
    • [x] InlineQueryResultMpeg4Gif
    • [x] InlineQueryResultPhoto
    • [x] InlineQueryResultVenue
    • [x] InlineQueryResultVideo
    • [x] InlineQueryResultVoice

    Bug repor.

    Feel free to report bugs about this branch. https://github.com/eternnoir/pyTelegramBotAPI/issues/130

    opened by eternnoir 18
  • How to Use SOCKS5 proxy?

    How to Use SOCKS5 proxy?

    1. What version of pyTelegramBotAPI are you using? 3.5.2

    2. What OS are you using? Linux Mint

    3. What version of python are you using? 3.5.2 ==========

    Hi. I did everything that described in Readme, but it seems that

    proxies = {
    'http': 'socks5://telegram.vpn99.net:55655',
    'https': 'socks5://telegram.vpn99.net:55655'
    }
    

    , pasted at the beggining of the script, has no effect. Bot does not use them. What am I doing wrong?

    Thank you for response.

    opened by LeoNeeDpk1 17
  • base_url added

    base_url added

    I've added a little change in base_url. It can be set in TeleBot class. Base_url helps to make a request to another API, local API. Check tests in the tests folder. Also, added an example in the example folder.

    opened by coder2020official 16
  • `InputPhotoMessageContent`

    `InputPhotoMessageContent`

    Hi. I would like a new feature to be implemented regarding the InputMessageContent of the Inline Mode.

    It says over here that Telegram only supports these 5 types:

    image

    I was wondering if we can get a new type called the InputPhotoMessageContent which would represent the content of the photo to be sent as the result of an Inline query.

    opened by TECH-SAVVY-GUY 3
  • Method to stop a poll.

    Method to stop a poll.

    How to stop the poll? What should I do? Telegram docs says that I should edit the message flags, but there is no option for edit the message excluding edit_message_text

    Is it possible using this library?

    opened by karambaq 6
Releases(4.2.0)
Owner
FrankWang
FrankWang
Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live strams, YouTube videos and telegram media.

Telegram VCVideoPlayBot An Telegram Bot By @ZauteKm To Stream Videos in Telegram Voice Chat. NOTE: Make sure you have started a VoiceChat in your Grou

Zaute 12 Dec 1, 2021
Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live strams, YouTube videos and telegram media.

Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live strams, YouTube videos and telegram media.

SUBIN 235 Nov 26, 2021
Telegram bot implementing Lex Arcana using python-telegram-bot library.

Lex Arcana Telegram Bot ?? Telegram bot implementing Lex Arcana using python-telegram-bot library. This bot was evaluated for the course "Computer Eng

Nicolò Sonnino 5 Sep 17, 2021
Receive GitHub webhook events and send to Telegram chats with AIOHTTP through Telegram Bot API

GitHub Webhook to Telegram Receive GitHub webhook events and send to Telegram chats with AIOHTTP through Telegram Bot API What this project do is very

Dash Eclipse 24 Nov 8, 2021
This is telegram bot to generate string session for using user bots. You can see live bot in https://telegram.dog/string_session_Nsbot

TG String Session Generate Pyrogram String Session Using this bot. Demo Bot: Configs: API_HASH Get from Here. API_ID Get from Here. BOT_TOKEN Telegram

Anonymous 16 Nov 29, 2021
A telegram bot which can show you the status of telegram bot

BotStatus-Ts-Bot An open source telegram Bot Status bot For demo you can check here The status is updated in every 1 hour About Bot This is a Bot stat

Ts_Bots 6 Oct 19, 2021
veez music bot is a telegram music bot project, allow you to play music on voice chat group telegram.

?? Veez Music Bot Music bot for playing music on telegram voice chat group. Requirements ?? FFmpeg NodeJS nodesource.com Python 3.7+ PyTgCalls ?? Get

levina 106 Dec 4, 2021
An Telegram Bot By @AsmSafone To Stream Videos in Telegram Voice Chat. This is Also The Source Code of The Bot Which is Being Used In @SafoTheBot Group! ❤️

Telegram Video Player Bot (Beta) An Telegram Bot By @AsmSafone To Stream Videos in Telegram Voice Chat. Special Features Supports Live Streaming From

SAF ONE 157 Nov 23, 2021
A Telegram Filter Bot, Support Unlimited Filter. Also, The Bot can auto-filter telegram File | video

A Telegram Filter Bot, Support Unlimited Filter. Also, The Bot can auto-filter telegram File | video

Hash Minner 3 Nov 27, 2021
Bagas Mirror&Leech Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Internet to our beloved Google Drive. Based on python-aria-mirror-bot

- [ MAYBE UPDATE & ADD MORE MODULE ] Bagas Mirror&Leech Bot Bagas Mirror&Leech Bot is a multipurpose Telegram Bot written in Python for mirroring file

null 4 Nov 23, 2021
A new coin listing alert bot using Python, Flask, MongoDB, Telegram API and Binance API

Bzzmans New Coin Listing Detection Bot Architecture About Project Work in progress. This bot basically gets new coin listings from Binance using Binan

Eyüp Barlas 12 Nov 28, 2021
Easy & powerful bot to check if your all Telegram bots are working or not. This bot status bot updates every 45 minutes & runs for 24x7 hours.

PowerfulBotStatus-IDN-C-X Easy & powerful bot to check if your all Telegram bots are working or not. This bot status bot updates every 45 minutes & ru

IDNCoderX 4 Oct 23, 2021
A telegram bot that can upload telegram media files to anonfiles.com and give you direct download link

✯ AnonFilesBot ✯ Telegram Files to AnonFiles Upload Bot It will Also Give Direct Download Link Process : Fork This Repositry And Simply Cick On Heroku

Avishkar Patil 12 Oct 17, 2021
Telegram Radio - A User-bot who continuously play random audio files (from the famous telegram music channel @mveargasm) in the intended voice chat.

MvEargasmDJ: This is my submission for the Telegram Radio Project of Baivaru. Which required a userbot to continiously play random audio files from th

eyaadh 22 Nov 23, 2021
A Simple Telegram Bot By @AsmSafone to Download Files From Mega.nz and Upload It to Telegram

MegaDL-Bot A Simple Telegram Bot By @AsmSafone to Download Files From Mega.nz and Upload It to Telegram Features No Login Required All Mega.nz File Li

SAF ONE 42 Nov 29, 2021
A Telegram Bot for adding Footer caption beside main caption of Telegram Channel Messages.

Footer-Bot A Telegram Bot for adding Footer caption beside main caption of Telegram Channel Messages. Best for Telegram Movie Channels. Made by @AbirH

Abir Hasan 31 Sep 24, 2021
Poll-Bot Repo For Telegram #telegram

Intro This Is A Simple Bot To Create Poll In Channel and Groups And Also This Is our First Project Too.. Enter you tokens at these are very important

BotsUniverse 6 Oct 25, 2021
veez music is a telegram music bot project, allow you to play music on voice chat group telegram.

?? VEEZ MUSIC BOT Veez Music is a telegram bot project that's allow you to play music on telegram voice chat group. Requirements ?? FFmpeg NodeJS node

levina 23 Aug 29, 2021
Based Telegram Bot and Userbot To Play Music in Your Telegram Groups With Some Cool Extra Features! 🥰

CallMusicPlus69 This Repo base on! ??️ A CallsMusic Based Telegram Bot and Userbot To Play Music in Your Telegram Groups With Some Cool Extra Features

brut✘⁶⁹ // ユスフ 4 Oct 28, 2021