Создаем телеграм-бот с вебхуками на Heroku
Поделюсь своим опытом разработки телеграм-бота для большого количества пользователей: разберу свои ошибки и шаги для их решения.
Одной из моих рабочих задач, как программиста, была автоматизация проведения викторины. Конечно, уже существуют специализированные бесплатные приложения, заточенные под эти задачи, но нужно было такое, в котором не было бы ничего лишнего, оно было всегда под рукой и такое привычное, чтобы не нужно было с ним разбираться. Выбор пал на телеграм-бота и для того чтобы он справлялся с большей нагрузкой было принято решение использовать асинхронную библиотеку aiogram.
Начнём с создания эхо бота на aiogram, тут нет ничего сложного, возьмём пример из документации:
Однако преимущество aiogram над python-telegram-bot и pyTelegramBotAPI в том, что он асинхронный, а значит, может обрабатывать несколько запросов почти единовременно. Стандартная база данных sqlite отлично подходит для несложных проектов и уже входит в стандартную библиотеку питона, поэтому для начала я решил использовать её.
Через несколько часов работы приложение было написано, и мы с коллегами решили протестировать на себе его работоспособность. Бот запускался с использование технологии long polling, и запускался он на локальном компьютере. Для небольшого количества человек этого вполне достаточно: 3-4 человека в секунду бот выдерживает без особых проблем.
Но, к сожалению, или к счастью, во время проведения викторины боту посыпалось бОльшее количество запросов, на которое мы не рассчитывали, в связи с чем посыпались ошибки не обрабатываемые ошибки, связанные с одновременным постоянным запросом новых сообщений у сервера и обработкой уже полученных.
Решением этой проблемы стал переход на вебхуки. И для обеспечения бесперебойной работы разместим его на удалённом сервере. Отличным решением для этого является heroku: здесь можно управлять запуском приложения как с компьютера, так и с мобильного приложения, отслеживать логи и, что является наиболее важным для нас, настраивать вебхуки.
Алгоритм для реализации эхо бота в данном случае занимает больше времени, но он достаточно прост:
Деплоймент бота на Heroku
Рано или поздно в разработке ботов вы столкнетесь с проблемой хостинга бота. Скорее всего, у вас нет своего собственного сервера, а платить за виртуальный не каждый хочет, да и настройка виртуального сервера может казаться чем-то непосильным для начинающих разработчиков. К счастью, есть много сервисов, предоставляющих хостинг приложений бесплатно. Одним из таких есть Heroku. Сегодня я расскажу, как легко и быстро развернуть простенького бота на данной платформе.
Почему именно Heroku? Она была одной из первых платформ, предоставляющих услуги типа PaaS (Platform as a Service) и есть лидером в этой сфере. Используя такие облачные сервисы, разработчик должен предоставить только приложение. Обо всем остальном – серверное железо, операционная система, интерпретатор языка и база данных, позаботится сервис.
По умолчанию, Heroku предлагает до 5 приложений на аккаунт и дает 550 бесплатных дино-часов в месяц. Если же подключить к аккаунту банковскую карту, их к-во расширится до 1000. Подробнее о фри дино-часах можно почитать здесь.
Регистрация и установка клиента Heroku
Прежде всего, для использования Heroku, нужно авторизироваться. Если у вас нет аккаунта, создайте его, перейдя по этой ссылке. Затем нужно установить Heroku Toolbelt. Эта утилита на данный момент поддерживает основные ОС: Windows, macOS и Linux.
Скачать и установить Heroku CLI на Windows или macOS можно прямо отсюда. На Ubuntu/Debian платформах вам понадобится ввести данную комманду:
После установки, чтобы убедиться, что все установилось, откройте консоль и введите heroku :
Если все работает, логинимся, используя данные, введенные при регистрации:
Создание приложения
Сегодня мы будем деплоить бота, написанного во второй части. Для начала создадим наше приложение под названием momentumbots :
Вывод команды показывает, что приложение было успешно создано и доступно на https://momentumbots.herokuapp.com .
Имя momentumbots уже занято мной, так что придумайте свое
Если же не указывать название приложения, то будет сгенерировано рандомное название:
Ставим Вебхуки
В прошлых частях мы писали ботов, использующих Long Polling. Суть его в том, что на сервера Телеграмма периодически приходят запросы на получение обновлений. Это ненадежно, т.к. сервера Telegram могут возвращать ошибку 504, вырубая бота. Используя же вебхуки, мы устанаваливаем URL, на который будут приходить обновления автоматически, таким образом избавляясь от этой проблемы. Вебхуки в тг работают только по HTTPS. Благо, Heroku предоставляет доступ к приложению через HTTPS и SSL-сертификат, освободжая нас от заботы о создании сертификатов.
В качестве веб-сервера будем использовать Flask, однако вам не составит труда разобраться с другими фреймворками. На Github-странице pyTelegramBotAPI, помимо Flask’а, есть примеры для aiohttp, CherryPy, CPython и Tornado.
How to Deploy a Telegram Bot using Heroku for FREE
A Complete Guide Using the python-telegram-bot Library
R unning your telegram bot locally suffices for simple applications. However, if you wanted to scale up your bot and enable others to use your bot even when you are not running the bot locally, you will need to go one step further to deploy the bot.
In this tutorial, I will be going through how to deploy a telegram bot you have created using the python-telegram-bot library with Heroku. What’s even better is that we can do this completely for free! Forget about all the fees you incur from other hosting options, Heroku will mostly likely suffice for your needs, without you having to pay a single cent nor enter your credit card details.
In order to do so, I will use a simple starter script taken from the examples in the python-telegram-bot Github repository where the bot simply echos whatever the user sends. You may have a different script, but I will show you which sections to modify in order to deploy the bot using Heroku.
If you want to go straight to the files needed, head over to this Github repository to download them!
This is our starting point:
Modifying the python-telegram-bot script
Changing from Polling to Webhooks
Firstly, we will modify how the bot fetches new data. The python-telegram-bot script uses polling instead of webhooks to fetch new data. For simple testing purposes, polling is sufficient because it’s simple to implement. However, the disadvantage of polling is that it is inefficient and the data it fetches is always old and never real-time. This is because polling sends a request at a predetermined frequency to detect any changes in the data, meaning it constantly checks if the data is modified, instead of being “notified” when a change is made to the data.
On the other hand, webhooks act like push notifications. Rather than fetching information, webhooks are triggered when the data is modified. This allows for realtime information and also makes it much more efficient because there is no need to continuously send requests to check for data.
We first import os, and then set the port number to listen in for the webhook.
Next, we modify the following line from
What this is doing is that it changes the polling method to webhook, listening in to 0.0.0.0 with the port you specified above with the PORT variable. The token refers to the API token of your telegram bot, which should be defined at the top of the code. The next line is to set the Webhook with the link to your heroku app, which we will get to next.
With all the changes to the python file, it should look similar to this (with your own Telegram bot token):
Creating your Heroku Webapp — Setting up the Directory
We are done with editing the python-telegram-bot script, except for changing the name of your heroku app which we will get into soon. In order for heroku to recognise the following as a python app, you need the following files in the same directory:
The python code should be inside the bot.py file, and I will go through the process to create the Procfile and requirements.txt.
First, change the directory of your terminal / command prompt to the same directory containing your python script. Then, create a requirements.txt file containing the following line:
This is needed to tell heroku which libraries it needs to install in order to execute the code. Assuming you are using the sample code above, the only library you need is python-telegram-bot, and the version we are using is 12.7. If you are importing other libraries to run your python code, be sure to include the other libraries as well in the requirements.txt file.
Next, you need a Procfile. The procfile declares the process type followed by the command, in the format <process type>: <command>. Here, we are using the web process type, which receives external HTTP traffic from Heroku’s routers. The command is python3 bot.py, which tells Heroku to execute the python file as you normally would with a python file locally. So your Procfile should contain the line:
Make sure that the Procfile does not have any file extension like .txt behind it, because it won’t work.
Creating your Heroku Webapp
With the three files in the same directory, we will now create the Heroku Webapp.
- Login / create a Heroku account.
- Install the Heroku CLI. If you do not have Git installed, first install Git before proceeding with the Heroku CLI.
- Once installed, you can use the heroku command in your terminal / command prompt. Go to the same directory as your python files, and type:
A new window will be opened in your browser prompting you to login, so just click on the button.
4. Once you are logged in, go back to the command line. Type in
to create your new webapp. Here, heroku will assign your webapp a name as well as the link to your webapp, which should be of the format https://yourherokuappname.herokuapp.com/. Paste the URL into the bot.py code, for the line
With all the changes to your bot.py file, it should look similar to this (with your own Telegram bot token and heroku app name, of course):
5. Next, in your command line, type in
The first line creates a new Git repository. The second line then tells Git that you want to include updates to a particular file in the next commit. The third line then commits the changes. In the fourth line, change “YourAppName” to the name of your heroku app. Lastly, the fifth line pushes everything to the server.
You should then see the following messages:
In particular, it will say that a Python app is detected and it will install the required libraries in the requirements.txt file using pip. Then, it will read the Procfile which specifies that the bot.py file is to be executed.
So that’s it! Once it finishes executing, you can simply head over to Telegram and message /start to your bot. It should now behave as you expect it to.
Since you are using the free plan on heroku, the bot will sleep after 30 minutes of inactivity. So do expect the bot to take a few seconds to respond to your /start if you are using it more than 30 minutes after it was previously used. Other than that, the bot will respond almost instantaneously
What to do if your Bot stops responding
I’ve noticed that the bot stops responding after about 24 hours of inactivity (because we are using the free version of Heroku), so if you want to “jolt” the bot awake, one way is to make a change to one of the files (eg. changing the python3 in the procfile to python and vice versa) and then committing the changes with the lines below:
You should see again see the messages about a Python app being detected and once it finishes executing, your bot should revive now!
Деплой бота на сервере Heroku
Может кто—нибудь дать инструкцию, как развернуть бота на сервере heroku (написанном на python )? Спасибо заранее.
- Первым делом создайте Git репозиторий в папке с ботом: git init
- Войдите в аккаунт Heroku : heroku login
- Создайте приложение: heroku create appname —region eu
Создайте файл Procfile с содержимым: bot: python main.py
- Если бот на веб-хуках, замените bot на web . Но на бесплатном тарифе, бот будет засыпать каждые 30 минут если не будет подключений, по этому на Heroku free лучше держать ботов на лонг-поллинге. Но проблема с засыпанием веб приложения решается с помощью http://kaffeine.herokuapp.com/.
Теперь нужно упаковать все зависимости проекта: pip freeze > requirements.txt
- Теперь наша папка выглядит приблизительно так: Procfile main.py requirements.txt
Коммитим изменения: git add . затем git commit -m ‘commit’
Пушим на Heroku : git push heroku master
Запускаем бота: heroku ps:scale bot=1
Смотрим логи: heroku logs -t
В папке с проектом должны быть такие 3 файла:
Proc
requirements.txt
+ другие модули (сгенерировать этот файл можно так: pip freeze > requirements.txt )
runtime.txt
или другая версия python
Из папки, где находится проект, запускаете такие команды:
Дополнительно рекомендую установить токен как переменную: heroku config:set TOKEN=7593654323:AAlkjHjhDZiWUD7Th4Dl_uPlkjpdorpoHGhgdsPVjQ (также можно установить переменные и на сайте Хероку) и обращаться к ней из программы