Part 2: Deploying Telegram Bot for FREE on Heroku
Following my previous article on how to create a telegram bot, in this article we will learn how to deploy the bot for free on Heroku.
First of all, what is Heroku? đ€
Quoting from the website.
Heroku is a cloud platform that lets companies build, deliver, monitor and scale apps â weâre the fastest way to go from idea to URL, bypassing all those infrastructure headaches.
In simpler terms, Heroku provides you the platform to host your applications, so you donât have to run your machine 24 X 7. đ
Setting up Heroku
- First things first, you will need to create an account on Heroku.
- Install heroku-cli for your specific operating system.
- Login in to your account by running the following command in terminal
heroku login
More about this here - Logging In
Code Changes
As mentioned in the previous article, we were using polling for running the bot. For deploying the bot online, we will be using webhooks so we need to make some code changes to our bot.
Polling vs. Webhook
The general difference between polling and a webhook is:
Polling (via get_updates) periodically connects to Telegram's servers to check for new updates
A Webhook is a URL you transmit to Telegram once. Whenever a new update for your bot arrives, Telegram sends that update to the specified URL.
You can learn more about the difference between polling and webhooks here.
We will be adding the set_webhook method in our code. Learn more about it here.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
import os
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
PORT = int(os.environ.get('PORT', '8443'))
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(
TOKEN, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
# updater.bot.set_webhook(url=settings.WEBHOOK_URL)
updater.bot.set_webhook(APP_NAME + TOKEN)
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Replace TOKEN with the value you got from BotFather as in the previous article. Replace APP_NAME with the application name you will be creating in the next step. (For some reason I am not able to link within the page, please see âCreate the Heroku applicationâ part).
Deploying the application
If you have followed the steps till now, you would be able to create a new application on Heroku. Letâs go back to our directory which contains the bot code if youâre following from the previous article, we had made a directory named echo-bot. Run the following command to change to your botâs directory.
cd echo-bot/
Now, we will first need to make this directory as a git repository before pushing the code to Heroku. Use the following command to instantiate your current directory as a git repository.
Note: If your repository is already a git repo, you donât need to run the next command.
git init
Create the Heroku application using the following command, you can use whatever âapp_nameâ you like.
heroku create "app_name"
Now you can use this Heroku application link in the APP_NAME in the code above. (In my case APP_NAME is âhttps://echotelegrambot.herokuapp.com/â)
Once the app is created, you can check the Remote URL of the application. Run the following command to check the emote information.
git remote -v
Now we need to tell our application what command to run on startup, for that Heroku uses a file called Procfile. You can read more about Procfile here.
Create a file named âProcfileâ using the following command.
vim Procfile
Add the following contents to Procfile. Make sure that your file name is bot.py
web: python3 bot.py
Note: This Procfile will only work if your bot is written in python if youâre using any other language check Herokuâs official documentation on how to write the Procfile for that corresponding language.
Now, you need to tell the dependencies to install on the Heroku server. Enter the pipenv shell first.
pipenv shell
pip freeze > requirements.txt
Running this command will create a file named ârequirements.txtâ which will contain all the dependencies required for running this application.
Now weâre almost done with the Heroku part, you just need to add the files, commit it and push those changes to Heroku. For our changes, we can add all the files in the git repo. So run the following command.
git add .
You can check the status using the following command.
git status
If you were following the tutorial till now the output of git status should like exactly like this.
Once added to git, we need to commit it and push it. Run these commands.
git commit -m <add_your_message>
git push heroku master
Now your application will start its build, you can check the logs by running the following command.
heroku logs -t
And weâve finally hosted our telegram bot on Heroku. đ„ł
Interested in learning about Heroku commands. Check this awesome cheatsheet - Herkou CheatSheet
I hope you learned something new from reading this article!
Checkout my other bots in action:
BookQuoteBot đ: Read the best quotes from famous books.
SplitwizeBot: Uses Splitwise API to list, create and settle the expenses all within Telegram.
We appreciate and thank you sir, such a wonderful and thorough tutorial!
Thanks for the detailed guide, it really helped me being a noob.
BTW i want to know how can i add rclone feature in my bot to access/read/write files from my td. Actually i want to create a bot which will convert flac files to mp3 using python script, and i will give it path to my flac files in my td
Hi, thanks for this tutorial. I only have one error in the logs.
telegram.error.BadRequest: Bad webhook: ip address 0.0.0.0 is reserved
How can I get the ip that must be specified to the app? The one used by the domain created by Heroku always changes.
Hey, reach out to me on codementor and we can discuss what error you are facing!
having same error please help
I have the same issue, were you able to resolve this by chance? Appart from that a really nice tutorial
Found the solution, which is an error in your tutorial, see my answer here: https://stackoverflow.com/questions/66920177/heroku-telegram-bot-badrequest-bad-webhook-ip-address-0-0-0-0-is-reserved