Build your first Telegram bot using Python and Heroku

Mattia Righetti
5 min readMay 29, 2019

One of the most powerful tools in Telegram is the ability create bots which can do whatever you’ll tell them to do with your code.

In this tutorial I’m going to teach you how to code a Telegram bot and deploy it on Heroku, a free platform on which you can deploy a lot of different apps.
To have a better understanding you’ll need some basic requirements:

  • Basic knowledge of Git
  • Basic Python programming
  • Basic terminal/shell commands

The first thing you’re going to do is to “register” your bot using the father of them all, the BotFather

Head to your Telegram app and search for the BotFather and create your first bot.

Why do we need to do this, you might ask?
As you can see, in the last message the BotFather sent us, there’s an HTTP API token which grants us the ability to comunicate with our bot. Save it and store it somewhere safe.

Now begins the fun part, get your shell and your favourite Python IDE ready and let’s get our hands dirty.

In this tutorial I’m going to use the pyTelegramBotAPI which will save us a lot of headaches later with the code and will make things a lot easier to understand. I’m also going to use Flask which is a Python web framework which will make your bot work on the web when we’re going to deploy it on Heroku.
Let’s start by downloading those two libraries with this command (note that I’m currently using Python 3.7):

pip install pyTelegramBotAPI && pip install flask

Now we have everything we’ll need to code our first bot.

Initial setup

Go ahead and create a folder with a file named Bot.py in it, open up that file in your IDE and start by importing the libraries we’ve just installed

import os
import telebot
from flask import Flask, request
TOKEN = '<YOUR TOKEN>'
bot = telebot.TeleBot(token=TOKEN)
server = Flask(__name__)

Paste your token you got previously from BotFather and you’re set!

Functionalities

Now’s time to program some functionalities our bot will feature. In this tutorial our bot will display some nice infos when it’s going to be started with the /start command and will reply something whenever it receives a message containing the “Hello” word.
(Please make sure to correctly indent the Python code provided below)

# Bot's Functionalitiesdef sendMessage(message, text):
bot.send_message(message.chat.id, text)
# This method will send a message formatted in HTML to the user whenever it starts the bot with the /start command, feel free to add as many commands' handlers as you want@bot.message_handler(commands=['start'])
def send_info(message):
text = (
"<b>Welcome to the Medium 🤖!</b>\n"
"Say Hello to the bot to get a reply from it!"
)
bot.send_message(message.chat.id, text, parse_mode='HTML')
# This method will fire whenever the bot receives a message from a user, it will check that there is actually a not empty string in it and, in this case, it will check if there is the 'hello' word in it, if so it will reply with the message we defined@bot.message_handler(func=lambda msg: msg.text is not None)
def reply_to_message(message):
if 'hello'in message.text.lower():
sendMessage(message, 'Hello! How are you doing today?')

That’s it for the functionalities part!

Server side

Now we’re going to look at the server side part which will host our bot, making it reachable by anyone that simply has its username.
Let’s create an account on Heroku first and after that we’re going to install the heroku CLI tools on our Mac with this command (Windows users have to download the tool from the official link)

brew tap heroku/brew && brew install heroku

Navigate to the folder you’ve created earlier and execute this command which will log you into Heroku.

heroku login

After that you’ll need to execute

heroku create

this command will create a project into your Heroku dashboard.
Last but not least you need the Heroku App URL, execute

heroku info

and you should get something like this

Copy the Web URL field of the returned message and save it for later.

Open up the Bot.py file we were working on before and add some more code for the server side part of the bot.

# SERVER SIDE @server.route('/' + TOKEN, methods=['POST'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200
@server.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url='<HEROKU Web URL>' + TOKEN)
return "!", 200
if __name__ == "__main__":
server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))

You do not need to fully understand this code, just know that this bot will use a webhook to make your bot respond immediately after it receives a message.

You’re done with the coding part! It’s that easy!
Let’s deploy the bot on our Heroku app.

Deployment

Navigate to your folder and create a file called Procfile with no extention and paste in it this line of code

web: python Bot.py

This is a file needed to let Heroku know that program needs to be started.
You will need to create another file with this command:

pip freeze > requirements.txt

As the name says, this command will generate a file that specifies what requirements are needed for our program to execute correctly.

Finally we can push our code to Heroku, from your folder execute this commands:

git add * && git commit -m "First deploy"

and after that we’re ready to deploy our bot.
Run this command

git push heroku master

and as soon as it finishes head to your Heroku dashboard, click on your freshly created app and click on the Open App button.
You should be ready to communicate with your bot now!

That’s it for this tutorial!

You can take a look at Telegram’s API to get a lot more from this powerful tool and get creative with it!

Happy coding to everyone!

--

--

Mattia Righetti

Software Engineer, enthusiast iOS and macOS application developer. Find me at https://mattrighetti.com