Как создать Telegram-бота с помощью библиотеки python-telegram-bot
Делимся инструкцией, как написать бота с помощью библиотеки python-telegram-bot за считанные минуты. На примере гайда от программиста Давида Мастроматтео.
«Купи мне истребитель». Сбор средств для Воздушных Сил ВСУ
Установка python-telegram-bot
Для создания бота понадобится пакет python-telegram-bot — оболочка для API от Telegram. Написать бота с помощью этой библиотеки очень просто, так как она полностью совместима с Python 3.6+.
Первое, что нужно сделать — установить python-telegram-bot. Вот ссылка на официальную документацию библиотеки .
$ pip install python-telegram-bot –upgrade
Создание бота
Теперь можно взяться за создание бота. Для этого даже не нужно писать код. Перейдите в Telegram и найдите канал @BotFather, который отвечает за регистрацию новых ботов. Начните общаться с ботом и введите команду /newbot . Затем BotFather спросит у вас имя и юзернейм.
У BotFather можно запросить много других интересных вещей. Например, изменить изображение профиля бота.
Теперь нужно принять важное решение: определиться с главной задачей бота. В этой инструкции мы сделаем бота, который предоставляет информацию о биоритмах пользователей . Будьте осторожны: речь идет о псевдонаучных теориях, так что б от будет такой же полезный, как и гороскопы. Но если дойдете до конца — сможете создавать любых ботов.
Программирование бота
Пакет python-telegram-bot состоит из оболочки API Telegram. Этот инструмент доступен через telegram.Bot- классы. Помимо них, есть еще модуль telegram.ext , который значительно упростит работу.
Модуль telegram.ext содержит много классов, но самые важные — telegram.ext.Updater и telegram.ext.Dispatcher . Updater отвечает за выборку новых обновлений от Telegram. Также он передает их в Dispatcher , после чего они обрабатываются с помощью Handler .
Приступим к программированию:
В функции main создан класс Updater , который автоматически сгенерировал объект Dispatcher , доступный через .dispatcher- свойства класса Updater .
Добавьте несколько обработчиков:
- команда /start вызывает функцию start() , которая отвечает пользователю информативным сообщением;
- команда /help вызывает функцию help() , которая отвечает пользователю информативным сообщением;
Сейчас в коде прописаны функции обратного вызова, которые используют полученные данные для отправки сообщений пользователю.
Тестирование
Теперь можно протестировать бота. Запустите его.
Пошлите ему команду /start .
Ура, бот работает!
Но это не конец. Надо создать бота, который сообщает пользователю его ежедневный биоритм. Для этого следует применить команду /start . С ее помощью при запуске чата можно получить данные о дне рождения пользователя. Затем надо создать функцию для обработки новой команды /biorhythm , чтобы отправить ответ пользователю с его личным биоритмом.
Чтобы узнать день рождения пользователя, для начала нужно изменить функцию, обрабатывающую команду /start . Чтобы упростить задачу, попросите пользователя указать год, месяц и день рождения.
В параметре update можно найти полезную информацию о пользователе, например, его имя.
В самом начале скрипта определите новую переменную STATE , которая нужна, чтобы понять, на какой вопрос отвечает пользователь.
Теперь необходимо реализовать функцию start_getting:_birthday_info() , она вызывается с помощью команды start() . После запуска вы получите информацию о дне рождения от пользователя.
Для переменной STATE устанавливается значение BIRTH_YEAR , чтобы после ответа пользователя было понятно, что вопрос касался года рождения. Затем отправляется сообщение, чтобы узнать год рождения.
Теперь пользователь ответит обычным текстом, поэтому нужно изменить функцию text() .
В функции text() необходимо понять, на какой вопрос отвечает пользователь, используя переменную STATE . После чего остается вызвать функцию для обработки каждого ответа.
Эти функции можно записать так:
Когда получен год рождения пользователя, остается проверить, допустимое ли это значение. Если да, то оно сохраняется в словаре context.user_data[] . Продолжайте устанавливать значения для переменной STATE и задавать следующие вопросы.
Когда зададите последний вопрос и будете знать день рождения, создайте переменную даты и сохраните ее в context.user_data[] словаре.
Если пользователь вводит недопустимое значение, то получает ответ, что оно неверно. Значение переменной STATE не меняется, поэтому пользователь застревает на этом вопросе, пока не ответит правильно.
Создание команды
Теперь нужно обработать команду /biorhythm .
Добавьте новый обработчик команд в функцию main() .
Напишите функцию расчета биоритма:
В примере представлены две разные функции: одна для обработки команды, а другая для расчета биоритма. Таким образом удается разделить ответственность этих функций.
Полный код бота
Пришло время проверить его:
Поздравляем! Telegram-бот на Python полностью готов.
Бот, созданный для примера, был сохранен. Его можно протестировать по имени пользователя @mastro35_mastrobot.
python-telegram-bot/python-telegram-bot
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.rst
We have made you a wrapper you can’t refuse
We have a vibrant community of developers helping each other in our Telegram group. Join us!
Stay tuned for library updates and new releases on our Telegram Channel.
This library provides a pure Python, asynchronous interface for the Telegram Bot API. It’s compatible with Python versions 3.7+.
In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the telegram.ext submodule.
A pure API implementation without telegram.ext is available as the standalone package python-telegram-bot-raw . See here for details.
Installing both python-telegram-bot and python-telegram-bot-raw in conjunction will result in undesired side-effects, so only install one of both.
Telegram API support
All types and methods of the Telegram Bot API 6.2 are supported.
You can install or upgrade python-telegram-bot via
To install a pre-release, use the —pre flag in addition.
You can also install python-telegram-bot from source, though this is usually not necessary.
Dependencies & Their Versions
python-telegram-bot tries to use as few 3rd party dependencies as possible. However, for some features using a 3rd party library is more sane than implementing the functionality again. The dependencies are:
-
for telegram.request.HTTPXRequest , the default networking backend for telegram.ext.Updater.start_webhook for telegram.ext.CallbackDataCache for telegram.ext.JobQueue
python-telegram-bot is most useful when used along with additional libraries. To minimize dependency conflicts, we try to be liberal in terms of version requirements on the dependencies. On the other hand, we have to ensure stability of python-telegram-bot , which is why we do apply version bounds. If you encounter dependency conflicts due to these bounds, feel free to reach out.
PTB can be installed with optional dependencies:
- pip install python-telegram-bot[passport] installs the cryptography>=3.0 library. Use this, if you want to use Telegram Passport related functionality.
- pip install python-telegram-bot[socks] installs httpx[socks] . Use this, if you want to work behind a Socks5 server.
- pip install python-telegram-bot[rate-limiter] installs aiolimiter
Our Wiki contains an Introduction to the API explaining how the pure Bot API can be accessed via python-telegram-bot . Moreover, the Tutorial: Your first Bot gives an introduction on how chatbots can be easily programmed with the help of the telegram.ext module.
- The package documentation is the technical reference for python-telegram-bot . It contains descriptions of all available classes, modules, methods and arguments as well as the changelog.
- The wiki is home to number of more elaborate introductions of the different features of python-telegram-bot and other useful resources that go beyond the technical documentation.
- Our examples section contains several examples that showcase the different features of both the Bot API and python-telegram-bot . Even if it is not your approach for learning, please take a look at echobot.py . It is the de facto base for most of the bots out there. The code for these examples is released to the public domain, so you can start by grabbing the code and building on top of it.
- The official Telegram Bot API documentation is of course always worth a read.
If the resources mentioned above don’t answer your questions or simply overwhelm you, there are several ways of getting help.
- We have a vibrant community of developers helping each other in our Telegram group. Join us! Asking a question here is often the quickest way to get a pointer in the right direction.
- Ask questions by opening a discussion.
- You can even ask for help on Stack Overflow using the python-telegram-bot tag.
Since v20.0, python-telegram-bot is built on top of Pythons asyncio module. Because asyncio is in general single-threaded, python-telegram-bot does currently not aim to be thread-safe. Noteworthy parts of python-telegram-bots API that are likely to cause issues (e.g. race conditions) when used in a multi-threaded setting include:
- telegram.ext.Application/Updater.update_queue
- telegram.ext.ConversationHandler.check/handle_update
- telegram.ext.CallbackDataCache
- telegram.ext.BasePersistence
- all classes in the telegram.ext.filters module that allow to add/remove allowed users/chats at runtime
Contributions of all sizes are welcome. Please review our contribution guidelines to get started. You can also help by reporting bugs or feature requests.
Occasionally we are asked if we accept donations to support the development. While we appreciate the thought, maintaining PTB is our hobby, and we have almost no running costs for it. We therefore have nothing set up to accept donations. If you still want to donate, we kindly ask you to donate to another open source project/initiative of your choice instead.
You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don’t have to be.
python-telegram-bot 13.13
We have a vibrant community of developers helping each other in our Telegram group. Join us!
Stay tuned for library updates and new releases on our Telegram Channel.
Table of contents
Introduction
This library provides a pure Python interface for the Telegram Bot API. It’s compatible with Python versions 3.7+. PTB might also work on PyPy, though there have been a lot of issues before. Hence, PyPy is not officially supported.
In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the telegram.ext submodule.
A pure API implementation without telegram.ext is available as the standalone package python-telegram-bot-raw . See here for details.
Installing both python-telegram-bot and python-telegram-bot-raw in conjunction will result in undesired side-effects, so only install one of both.
Telegram API support
All types and methods of the Telegram Bot API 6.1 are supported.
Installing
You can install or upgrade python-telegram-bot with:
Or you can install from source with:
In case you have a previously cloned local repository already, you should initialize the added urllib3 submodule before installing with:
Optional Dependencies
PTB can be installed with optional dependencies:
- pip install python-telegram-bot[passport] installs the cryptography library. Use this, if you want to use Telegram Passport related functionality.
- pip install python-telegram-bot[ujson] installs the ujson library. It will then be used for JSON de- & encoding, which can bring speed up compared to the standard json library.
- pip install python-telegram-bot[socks] installs the PySocks library. Use this, if you want to work behind a Socks5 server.
Getting started
Our Wiki contains a lot of resources to get you started with python-telegram-bot :
Learning by example
We believe that the best way to learn this package is by example. Here are some examples for you to review. Even if it is not your approach for learning, please take a look at echobot.py, it is the de facto base for most of the bots out there. Best of all, the code for these examples are released to the public domain, so you can start by grabbing the code and building on top of it.
Visit this page to discover the official examples or look at the examples on the wiki to see other bots the community has built.
Logging
This library uses the logging module. To set up logging to standard output, put:
at the beginning of your script.
You can also use logs in your application by calling logging.getLogger() and setting the log level you want:
If you want DEBUG logs instead:
Documentation
python-telegram-bot ’s documentation lives at readthedocs.io.
Getting help
You can get help in several ways:
- We have a vibrant community of developers helping each other in our Telegram group. Join us!
- Report bugs, request new features or ask questions by creating an issue or a discussion.
- Our Wiki pages offer a growing amount of resources.
- You can even ask for help on Stack Overflow using the python-telegram-bot tag.
Contributing
Contributions of all sizes are welcome. Please review our contribution guidelines to get started. You can also help by reporting bugs.
Donating
Occasionally we are asked if we accept donations to support the development. While we appreciate the thought, maintaining PTB is our hobby and we have almost no running costs for it. We therefore have nothing set up to accept donations. If you still want to donate, we kindly ask you to donate to another open source project/initiative of your choice instead.
License
You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don’t have to be.
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python.
In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filter the spam messages sent by users.
Requirements
- A Telegram Account: If you don’t have the Telegram app installed just download it from the play store. After downloading create an account using your mobile number just like WhatsApp.
- .python-telegram-bot module: Here we will need a module called python-telegram-bot, This library provides a pure Python interface for the Telegram Bot API. It’s compatible with Python versions 3.6.8+. In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the “telegram.ext” submodule. For more information, you can check their official GitHub repo.
Installation of the module
We can install this module via pip and conda with the below command.
Steps to create your first bot
Step 1: After opening an account on Telegram, in the search bar at the top search for “BotFather”
Step 2: Click on the ‘BotFather’ (first result) and type /newbot
Step 3: Give a unique name to your bot. After naming it, Botfather will ask for its username. Then also give a unique name BUT remember the username of your bot must end with the bot, like my_bot, hellobot etc.
Step 4: After giving a unique name and if it gets accepted you will get a message something like this –
Here the token value will be different for you, we will use this token in our python code to make changes in our bot and make it just like we want, and add some commands in it.