Codementor Events

Part 2: Deploying Telegram Bot for FREE on Heroku

Published Sep 03, 2020
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

2.png

Create the Heroku application using the following command, you can use whatever “app_name” you like.

heroku create "app_name"	

3.png

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

4.png

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

5.png

Add the following contents to Procfile. Make sure that your file name is bot.py

web: python3 bot.py

6.png

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

7.png

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.

8.png

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

9.png

Now your application will start its build, you can check the logs by running the following command.

heroku logs -t

10.png

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.

Discover and read more posts from Karan Batra
get started
post commentsBe the first to share your opinion
Thobisa Ndlovu
2 years ago

We appreciate and thank you sir, such a wonderful and thorough tutorial!

joshi toshi
3 years ago

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

Roberto
3 years ago

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.

Karan Batra
3 years ago

Hey, reach out to me on codementor and we can discuss what error you are facing!

Jayant
3 years ago

having same error please help

MsgtGreer
3 years ago

I have the same issue, were you able to resolve this by chance? Appart from that a really nice tutorial

MsgtGreer
3 years ago
Show more replies