Введение, простой echo-бот
Приветствую тебя, читатель! Telegram Bot API – это мощный инструмент для вообще чего угодно. Автоматизация действий, работа с пользователями, онлайн-магазины, игры и много чего ещё. В этом учебнике мы научимся писать ботов для Telegram на языке Python.
Сразу оговорюсь: тот бот, который получится в итоге — это лишь прототип, цель всех этих постов — рассказать об основах ботостроения, показать, как можно за короткое время написать простого бота для своих нужд.
Язык программирования будет Python 3, но это не означает, что любители PHP, Ruby и т.д. в пролёте; все основные принципы совпадают. Я не буду особо останавливаться на описании самого языка, желающие могут ознакомиться с документацией по Python здесь.
Подготовка к запуску
Взаимодействие ботов с людьми основано на HTTP-запросах. Чтобы не мучаться с обработкой «сырых» данных, воспользуемся библиотекой pyTelegramBotAPI, которая берет на себя все нюансы отправки и получения запросов, позволяя сконцентрироваться непосредственно на логике. Установка библиотеки предельно простая:
Теперь можно выйти из режима Python-консоли (Ctrl+Z или Ctrl+D, или exit() )
Пишем простого echo-бота
Ну, довольно слов, перейдем к делу. В качестве практики к первому уроку, напишем бота, повторяющего присланное текстовое сообщение. Создадим каталог, а внутри него 2 файла: bot.py и config.py . Я рекомендую выносить различные константы и настройки в файл config.py , дабы не загромождать другие. В файл config.py впишем:
Теперь надо научить бота реагировать на сообщения. Напишем обработчик, который будет реагировать на все текстовые сообщения.
У читателя возникнет вопрос: зачем там символ “@”? Что это вообще за message_handler ? Дело в том, что после приёма сообщения от Telegram его надо обработать по-разному в зависимости от того, что это за сообщение: текст “привет” или текст “пока”, может быть, вообще стикер или музыка. Первое, что придёт в голову – написать множество конструкций if-then-else , но такой подход некрасивый и позволяет быстро запутаться.
Для решения этой проблемы автор библиотеки pyTelegramBotAPI реализовал механизм хэндлеров, которые используют питоновские декораторы (пока просто запомним это слово). В хэндлере описывается, в каком случае необходимо выполнять ту или иную функцию. Например, хэндлер @bot.message_handler(content_types=[«text»]) выполнит нижестоящую функцию, если от Telegram придёт текстовое сообщение, а хэндлер @bot.message_handler(commands=[«start»]) сработает при получении команды /start.
Теперь запустим бесконечный цикл получения новых записей со стороны Telegram:
Функция infinity_polling запускает т.н. Long Polling, бот должен стараться не прекращать работу при возникновении каких-либо ошибок. При этом, само собой, за ботом нужно следить, ибо сервера Telegram периодически перестают отвечать на запросы или делают это с большой задержкой приводя к ошибкам 5xx)
How to Create a Telegram Bot using Python

Ashutosh Krishna

Automated chatbots are quite useful for stimulating interactions. We can create chatbots for Slack, Discord, and other platforms.
In this article, I’ll teach you how to build a Telegram chatbot that will tell you your horoscope. So, let’s get started!
How to Get Your Bot Token
To set up a new bot, you will need to talk to BotFather. No, he’s not a person – he’s also a bot, and he’s the boss of all the Telegram bots.
- Search for @botfather in Telegram.
2. Start a conversation with BotFather by clicking on the Start button.

Click on Start Button
3. Type /newbot , and follow the prompts to set up a new bot. The BotFather will give you a token that you will use to authenticate your bot and grant it access to the Telegram API.

Getting access token
Note: Make sure you store the token securely. Anyone with your token access can easily manipulate your bot.
How to Set Up Your Coding Environment
Let’s set up the coding environment. While there are various libraries available to create a Telegram bot, we’ll use the pyTelegramBotAPI library. It is a simple but extensible Python implementation for the Telegram Bot API with both synchronous and asynchronous capabilities.
Install the pyTelegramBotAPI library using pip:
Next, open your favorite code editor and create a .env file to store your token as below:
After that, run the source .env command to read the environment variables from the .env file.
How to Create Your First Bot
All the API implementations are stored in a single class called TeleBot . It offers many ways to listen for incoming messages as well as functions like send_message() , send_document() , and others to send messages.
Create a new bot.py file and paste the following code there:
In the above code, we use the os library in order to read the environment variables stored in our system.
If you remember, we exported an environment variable called BOT_TOKEN in the previous step. The value of BOT_TOKEN is read in a variable called BOT_TOKEN . Further, we use the TeleBot class to create a bot instance and passed the BOT_TOKEN to it.
We then need to register message handlers. These message handlers contain filters that a message must pass. If a message passes the filter, the decorated function is called and the incoming message is supplied as an argument.
Let’s define a message handler that handles incoming /start and /hello commands.
Any name is acceptable for a function that is decorated by a message handler, but it can only have one parameter (the message).
Let’s add another handler that echoes all incoming text messages back to the sender.
The above code uses a lambda expression to test a message. Since we need to echo all the messages, we always return True from the lambda function.
You now have a simple bot that responds to the /start and /hello commands with a static message and echoes all the other sent messages. Add the following to the end of your file to launch the bot:
That’s it! We have a Telegram bot ready. Let’s run the Python file and go to Telegram to test the bot.
Search for the bot using its username if you’re unable to find it. You can test it by sending the commands like /hello and /start and other random texts.

Testing the bot
Note: All the message handlers are tested in the order in which they were declared in the source file.
For more information on using the pyTelegramBotAPI library, you can refer to their documentation.
How to Code the Horoscope Bot
Let’s shift our attention to building our Horoscope Bot now. We will use message chaining in the bot. The bot will first ask for your zodiac sign, and then the day, and then it will respond with the horoscope for that particular day.
Under the hood, the bot interacts with an API to get the horoscope data.
We are going to use the Horoscope API that I built in another tutorial. If you wish to learn how to build one, you can go through this tutorial. Make sure you explore the APIs here before getting started.
How to fetch the horoscope data
Let’s create a utility function to fetch the horoscope data for a particular day.
In the above Python code, we created a function that accepts two string arguments – sign and day – and returns JSON data. We send a GET request on the API URL and pass sign and day as the query parameters.
If you test the function, you will get an output similar to below:
Note: You can explore more about the requests library in Python in this tutorial.
How to add a message handler
Now that we have a function that returns the horoscope data, let’s create a message handler in our bot that asks for the zodiac sign of the user.
The above function is a bit different from the other functions we defined earlier. The bot’s horoscope functionality will be invoked by the /horoscope command. We are sending a text message to the user, but notice that we have set the parse_mode to Markdown while sending the message.
Since we’ll use message chaining, we used the register_next_step_handler() method. This method accepts two parameters: the message sent by the user and the callback function which should be called after the message. Thus, we pass the sent_msg variable and a new day_handler function that we’ll define next.
Let’s define the day_handler() function that accepts the message.
We fetch the zodiac sign from the message.text attribute. Similar to the previous function, it also asks the day for which you want to know the horoscope.
In the end, we use the same register_next_step_handler() method and pass the sent_msg , the fetch_horoscope callback function, and the sign .
Let’s now define the fetch_horoscope() function that accepts the message and the sign.
This is the final function where we get the sign from the function parameter and the day from the message.text attribute.
Next, we fetch the horoscope using the get_daily_horoscope() function and construct our message. In the end, we send the message with the horoscope data.
Bot Demo
Once you run the Python file, you can test this functionality. Here’s the demo:
Horoscope Bot Demo
Recommended Next Steps
As of now, the bot stops working as soon as we stop our Python application. In order to make it run always, you can deploy the bot on platforms like Heroku, Render, and so on.
Here’s a link to the GitHub repo for this project — feel free to check it out.
You can also add more functionalities to the bot by exploring the Telegram APIs.
pyTelegramBotAPI 4.10.0
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.5!
Official documentation
Official ru documentation
Contents
Getting started
This API is tested with Python 3.7-3.11 and Pypy 3. There are two ways to install the library:
- Installation using pip (a Python package manager):
- Installation from source (requires git):
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
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.
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.
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:
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:
Alright, that’s it! Our source file now looks like this:
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 , web_app_data .
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 must 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):
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. |
| chat_types | list of chat types | True if message.chat.type in your filter |
| 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:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) # <- passes a Message type object to your function
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function
Poll Handler
Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function
Inline Mode
More information about Inline mode.
Inline handler
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
Middleware Handlers
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 .
There are other examples using middleware handler in the examples/middleware directory.
Class-based middlewares
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Custom filters
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
TeleBot
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.
The last example yields this result:
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
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
Asynchronous TeleBot
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
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:
Or you can use the new smart_split function to get more meaningful substrings:
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:
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.
Proxy
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
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 .
Testing
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
API conformance limitations
- ➕ Bot API 4.5 — No nested MessageEntities and Markdown2 support
- ➕ Bot API 4.1 — No Passport support
- ➕ Bot API 4.0 — No Passport support
AsyncTeleBot
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
EchoBot
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
Examples
See more examples in our examples folder
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:
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.
- Join the pyTelegramBotAPI Telegram Chat Group
Telegram Channel
Join the News channel. Here we will post releases and updates.
More examples
Code Template
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
-
(source) by ilteoood — Monitors websites and sends a notification on changes by aRandomStranger by GabrielRF — Let me Google that for you. by mrgigabyte by Tronikart — Multifunctional Telegram Bot RadRetroRobot. (source) by i32ropie by @NeoRanger (source) — Share code snippets as beautifully syntax-highlighted HTML and/or images. (source) by alejandrocq — Telegram bot to check the menu of Universidad de Granada dining hall. — Simple Proxy Bot for Telegram. by p-hash — DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. — by vfranch by Dmytryi Striletskyi — Timetable for one university in Kiev. by rmed — Send and receive messages to/from WhatsApp through Telegram (source) by jcolladosp — Telegram bot using the Python API that gets films rating from IMDb and metacritic (source) by GabrielRF — Send to Kindle service. (source) by GabrielRF — Bot used to track packages on the Brazilian Mail Service. (link) by EeOneDown — Bot with timetables for SPbU students. (link) by 0xVK — Telegram timetable bot, for Zhytomyr Ivan Franko State University students. (link) — A Telegram Bot created to help people to memorize other languages’ vocabulary. by rubenleon (GitHub) — Bot that provides buses coming to a certain stop and their remaining time for the city of Vigo (Galicia — Spain) (source) by airatk — bot which shows all the necessary information to KNTRU-KAI students. (source) by @FacuM — Support Telegram bot for developers and maintainers. (source) by @DesExcile — Сatalog of poems by Eduard Asadov. (source) by @LeoSvalov — words and synonyms from dictionary.com and thesaurus.com in the telegram. (source) by @irevenko — An all-round bot that displays some statistics (weather, time, crypto etc. ) (source) by @Fliego — a simple bot for food ordering (source) by @0xnu — Telegram bot for displaying the latest news, sports schedules and injury updates. (source) by @zeph1997 — A Telegram Bot to remove «join group» and «removed from group» notifications. (source) by @Pablo-Davila — A (tasks) lists manager bot for Telegram. (source) by @Pablo-Davila — An implementation of the famous Eliza psychologist chatbot. (source) by Mrsqd. A Telegram bot that will always be happy to show you the weather forecast. by ModischFabrications. This bot can start, stop and monitor a minecraft server. by dexpiper. This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. by Anvaari. This Bot make «Add to google calendar» link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. Source code by Areeg Fahad. This bot can be used to translate texts. by Areeg Fahad. With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. by Leon Heess (source). Send any link, and the bot tries its best to remove all tracking from the link you sent. by Vishal Singh(source code) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) by Aadithya & Amol Soans This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) (source) by TrevorWinstral — Gets live COVID Country data, plots it, and briefs the user (source) by TrevorWinstral — Notifies ETH students when their lectures have been uploaded by Resinprotein2333. This bot can help you to find The information of CVE vulnerabilities. (Source by DevAdvik — Get Live Ethereum Gas Fees in GWEI by JoachimStanislaus. This bot can help you to track your expenses by uploading your bot entries to your google sheet. by Carlosma7. This bot is a trivia game that allows you to play with people from different ages. This project addresses the use of a system through chatbots to carry out a social and intergenerational game as an alternative to traditional game development. (source) This bot lets you find difinitions of words in Spanish using RAE’s dictionary. It features direct message and inline search. by EnriqueMoran. Control your LinuxOS computer through Telegram. . Make purchases of items in a store with an Admin panel for data control and notifications. Query wolframalpha.com and make use of its API through Telegram. This Bot can understand spoken text in videos and translate it to English (source) Zyprexa can solve, help you solve any mathematical problem you encounter and convert your regular mathematical expressions into beautiful imagery using LaTeX. by tusharhero — Makes bincodes from text provides and also converts them back to text. Toolset for Hydrophilia tabletop game (game cards, rules, structure. ). (source) by 咕谷酱 GuXiaoJiang is a multi-functional robot, such as OSU game information query, IP test, animation screenshot search and other functions. A feedback bot for user-admin communication. Made on AsyncTeleBot, using template. by ablakely This is a Telegram to IRC bridge which links as an IRC server and makes Telegram users appear as native IRC users. by Anton Glyzin This is a simple telegram-store with an admin panel. Designed according to a template. (source)by CommanderCRM. This bot aggregates media (movies, TV series, etc.) ratings from IMDb, Rotten Tomatoes, Metacritic, TheMovieDB, FilmAffinity and also provides number of votes of said media on IMDb.
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.
pyTelegramBotAPI Wiki
A simple, but extensible Python implementation for the Telegram Bot API.
PyPi Package Version Supported Python versions Build Status
Getting started.
Writing your first bot
Prerequisites
A simple echo bot
General API Documentation
Types
Methods
General use of the API
Message handlers
Callback Query handlers
Middleware handlers
TeleBot
Reply markup
Inline Mode
Advanced use of the API
Asynchronous delivery of messages
Sending large text messages
Controlling the amount of Threads used by TeleBot
The listener mechanism
Using web hooks
Logging
Proxy
API conformance
Change log
F.A.Q.
Bot 2.0
How can I distinguish a User and a GroupChat in message.chat?
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.
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:
@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:
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)
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.
@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</token_string>
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
setWebhook
unset webhook
getUpdates
updates = tb.get_updates()
updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout):
sendMessage
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’.
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:
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:
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</attribute>
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:
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.
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.
✅ Bot API 3.5 — To be checked.
✔ Bot API 3.4
✔ Bot API 3.3
✔ Bot API 3.2
✔ Bot API 3.1
✔ Bot API 3.0
✔ Bot API 2.3.1
✔ Bot API 2.3
✔ Bot API 2.2
✔ Bot API 2.1
✔ Bot API 2.0
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