How to Deploy a Telegram Bot using Heroku for FREE | by Haohui | Towards Data Science

Running 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:
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.
import osPORT = int(os.environ.get('PORT', 5000))
Next, we modify the following line from
updater.start_polling()
to
updater.start_webhook(listen="0.0.0.0",                          port=int(PORT),                          url_path=TOKEN)updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN)
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):
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:
bot.pyProcfilerequirements.txt
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:
python-telegram-bot==12.7
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:
web: python3 bot.py
Make sure that the Procfile does not have any file extension like .txt behind it, because it won’t work.
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:
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:
heroku login
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
heroku create
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
updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN)
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
git initgit add .git commit -m "first commit"heroku git:remote -a YourAppNamegit push heroku master
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~
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:
git add .git commit -m "changing python3 to python in Procfile"git push heroku master
You should see again see the messages about a Python app being detected and once it finishes executing, your bot should revive now!