pyTelegramBotAPI
A simple, but extensible Python implementation for the Telegram Bot API.
- Getting started.
- Writing your first bot
- General API Documentation
- Advanced use of the API
- F.A.Q.
- The Telegram Chat Group
- More examples
- Bots using this API
Getting started.
This API is tested with Python 2.6, Python 2.7, Python 3.4, Pypy 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")
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_type
attribute, 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
Same as Message handlers
channel_post_handler
Same as Message handlers
edited_channel_post_handler
Same as Message handlers
Callback Query Handler
In bot2.0 update. You can get callback_query
in update object. In telebot use callback_query_handler
to process callback_querys.
@bot.callback_query_handler(func=lambda call: True)
def test_callback(call):
logger.info(call)
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(chatid, text)
# 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")