Deploy Telegram Bot on Heroku

So you created a mind-blowing Telegram app that can reply automatically to your group members. Is it not brilliant? However, now you are stuck with another problem. Where should you host your code so that it can run 24*7? If this is the situation you are in then continue reading as I am going to show you how you can deploy Telegram Bot on Heroku for free.

Prerequisites to deploy Telegram Bot on Heroku

  1. Create Telegram Bot
  2. Install Python. You can download Python software from here.
  3. Install Git. You can read this article to install Git on Linux or Git on Windows
  4. Install Heroku CLI. You can read this article to download and install Heroku CLI on various platforms.
  5. Create Heroku Account by clicking here.
  6. Set Telegram Webhook

Important Notes: I am using Centos 7 OS in this example, some steps in your case may vary depending on the OS.

Create Telegram Bot

Follow the steps mentioned in this video to create Telegram Bot.

Setup Python Virtual Environment and Download Required Packages

  • Create a folder with the name “telegram”.
  • Move inside the telegram directory.
mkdir telegram
cd telegram
  • Create a Python Virtual Environment by running the below commands and activating the virtual environment.
python3 -m venv telegram-web-app python=3.6
source telegram-web-app/bin/activate
  • Install Requests, Flask and Gunicorn modules.
pip install requests flask gunicorn

Create Flask Application

We now need to create a Flask application that will contain the Telegram code. Follow the below steps in sequence.

Please ensure you are still in the “telegram” folder which you created in the above steps. You can cross-verify that by running “pwd” command and verifying the directory.

Create an App Folder

mkdir app
cd app

Create Python program

You now need to create a main.py file and write your program there.

touch main.py

Below is a sample program that you can use. Please make sure you have already created the Telegram Bot.

from flask import Flask, jsonify, request
import datetime
import requests

app = Flask(__name__)

token = '2007294251:AAGF-7kT89lNpTx-Hta3qYHsFy1RSI4oAdU'

def welcome_msg(item):
    global token
    if item["text"].lower() == "hi":
        msg = 'hello'
        chat_id = item["chat"]["id"]
        user_id = item["from"]["id"]
        user_name = item["from"].get("username",user_id)
        welcome_msg = '''{}'''.format(msg)
        to_url = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=HTML'.format(token, chat_id, welcome_msg)
        resp = requests.get(to_url)


@app.route("/", methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        data = request.get_json()
        data = data["message"]
        welcome_msg(data)
        return { 'statusCode' : 200, 'body' : 'Success' , 'data' : data }
    else:
        return { 'statusCode' : 200, 'body' : 'Success'}

Create a Script to run the app

Move to the parent directory by running the below command.
Create a file named “run.py”

cd ../
touch run.py

Add below sample code in the run.py file.

from app.main import app
 
if __name__ == "__main__":
  app.run()

Validate the app

It is a good practice to verify the application now and see if it works. You can use the below code to verify the app now.

python run.py

You should be able to see something as shown below. If there is no error here then please move to the next step.

(telegram-web-app) [root@localhost telegram-web-app]# python run.py
 * Serving Flask app 'app.main' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Prepare to Deploy the Telegram Bot to Heroku

We need to perform two important steps before we can deploy our application on Heroku. The steps are:

  1. Create requirements.txt file
  2. Create Procfile

run below commands to perform these two steps.

pip freeze > requirements.txt
echo web: gunicorn run:app >> Procfile

Deploy Telegram Bot to Heroku

Create a Heroku app by running the below command.

heroku create <app-name>

Add Heroku application to Remote by running the below commands:

$ git init
$ heroku git:remote -a <heroku-app-name>
$ git remote -v

Deploy the App to Heroku

git add .
git commit -m "Init deploy"
git push heroku master

Great ! Your Telegram Bot should be live now. You can test it by writing some messages in your Telegram groups and checking if the Bot replies automatically now.

Set Telegram Webhook

The last step of this tutorial is going to be to add a telegram webhook so that whenever your bot receives a new message, Telegram is going to send the request to your application along with the data.

Syntax: https://api.telegram.org/bot<token>/setWebhook?url=<your-heroku-app-url>

https://api.telegram.org/bot2007294251:AAGF-7kT89lNpTx-Hta3qYHsFy1RSI4oAdU/setWebhook?url=https://telegram-web-app.herokuapp.com

To learn about Automating Tweets on Twitter, Read here. 😀

Scroll to Top