A guide to hosting a telegram bot created using the python-telegram-bot library with heroku. See the full article explaining the steps here.
Before you begin, you will need a Telegram bot API token from BotFather.
- Download the three files in this repo: bot.py (containing your python code for the Telegram bot), requirements.txt (containing the python libraries to be installed), and Procfile (containing the command to execute the python file).
- Login / create a Heroku account.
- Install Git.
- Install the Heroku CLI.
- Once installed, you can use the heroku command in your terminal / command prompt. Go to the same directory as the files in this repository, and type:
heroku login
A new window will be opened in your browser prompting you to login, so just click on the button.
- Once you are logged in, go back to the command line. Type in
heroku create
to create your new webapp. 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/.
- To the bot.py file, change the TOKEN variable to the API token of your telegram bot, and change the yourherokuappname to the name of your heroku app in the line
updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN)
- Next, in your command line, type the following commands in the following order:
git init
git add .
git commit -m "first commit"
heroku git:remote -a YourAppName
git push heroku master
(Make sure to replace YourAppName with the name of your Heroku webapp)
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.
- Go to your conversation with your Telegram bot on Telegram and type /start. The bot should be working now!
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 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!