How I Created & Deployed Telegram Bot 🤖 in Just 10 Minutes in Python

Shahzaib Chadhar
8 min readJun 1, 2022

In this article, I will show you the whole process of how to create a Telegram bot in Python and deploy it on Heroku for FREE! If you’re interested then keep reading the article 😀.

Really it will take only 10 minutes!

Follow these easy and simple steps with me!

STEP 1: Set up your Bot’s profile

To set up a new bot, start the conversation with BotFather (@BotFather).
BotFather will help us in creating the new bot.

  • Search for @botfather in Telegram.
  • Start your conversation by pressing the Start button.
  • Create the bot by running /newbotcommand
  • Enter the Display Name and User Name for the bot.
  • BotFather will send you a message with the token

DISCLAIMER — Keep the access token of the bot securely. Anyone with your token can manipulate this bot.

STEP 2: Coding the bot in Python

Open up the terminal and start by creating a new directory first.

mkdir echo-bot/
cd echo-bot/

We will be using python-telegram-bot package for interacting with Telegram API. Install the package using the following command.

pip install python-telegram-bot

Create a new file echobot.py and paste the following code into it.

#!/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 loggingfrom 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__)
# 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_polling()
# 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” on line 56 with the token that you got from the BotFather earlier.

This code uses a polling approach to check for messages and will reply to every message it receives with the same message. You can read more about how python-telegram-bot works here — Coding your first bot

Run the bot using

python echobot.py

WOW! We’re done 😄

I bet this would have taken you less than 10 minutes to get started with your first bot.

See the 🤖 in action:

Play with the bot here — EchoBot on Telegram.

STEP 3: Deploy on Heroku

There I will guide you to deploy your first created bot on Heroku.

Setting up Heroku

  • First things first, you will need to create an account on Heroku.
  • Install heroku-cli for your specific operating system.
  • Login into your account by running the following command in terminal
heroku login

See more documentation on Heroku Login.

Make Changes in Previous Code

As mentioned in the above step 2, 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 the “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. Run the following command to change your bot’s directory.

cd echo-bot/

Now, we will first need to make this directory 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 them 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. 🥳

I hope these steps were easy for you and I are able to teach you how you can make the telegram bot in python.

If you have enjoyed and learned from this article, make sure to FOLLOW me and clap! 👏👏

THANK YOU! 😊

--

--

Shahzaib Chadhar

I am Shahzaib Chadhar, a hard-working, reliable freelance Full Stack Developer and Data Extraction Specialist.