Build a Telegram Bot using Python

Anant Verma
IEEE Manipal
Published in
6 min readAug 17, 2020

A bot is a piece of interactive software that performs repetitive automated tasks over the internet. A lot of items can be automated and delivered to the user through a bot. There are a range of platforms we can create bots on like Twitter, Discord, Slack, and Telegram. In this article, we’ll be creating a Telegram bot.

The Telegram bot API allows third-parties to create bots that use the Telegram app as the main interface. They run inside the Telegram environment and do not require any further installation. We will access the Telegram API using one of its python wrapper: python-telegram-bot (link). The use of a wrapper will simplify our development process.

By the end of this tutorial, you will have a telegram bot that on command will message you with a summary of new and total positive covid19 cases.

Before Starting

  • We are going to need python so make sure to have it installed.
  • Have a phone with the Telegram App installed.

Let’s Start

Step 1: Get a telegram bot TOKEN

Register a new bot using BotFather (Use the steps specified in this link). After creating the bot, copy the token string and keep it safe.

The token is a unique identifier used to authenticate the developer. Thus, anyone with access to the token has full access to your bot.

Step 2: Install the required libraries

Open up terminal or cmd and navigate to your project folder. Then copy-paste these two commands. (Don’t include the dollar sign)

$ python3 -m venv venv
$ source venv/bin/activate

We create a virtual environment to keep dependencies required by different projects separate. This is good practice. The environment gets activated using the second command. Every new python module installed after activating it gets saved within this venv folder instead of being installed globally.

Now, return to your cmd (terminal) and enter this command. Press y if prompted.

$ pip3 install python-telegram-bot

Step 3: Test the setup

Now we should have everything to start. Just in case, let’s test our setup.

Create a new file with the name ‘main.py’ and enter the code below.

import telegram
bot = telegram.bot(token='TOKEN') #Replace TOKEN with your token string
print(bot.get_me())

Close, save and run the file (python3 main.py) and provided everything was installed successfully, you’ll get a message in terminal similar to this:

$ {'id': ..., 'first_name': '...', 'is_bot': True, 'username': '...', 'can_join_groups': True, 'can_read_all_group_messages': False, 'supports_inline_queries': False}

Tip: Using the python3 command, one can run a script once. When you edit your code and want to run the updated file, you will have to stop the process (Ctrl + C) and type the command again. This is slow. You can use the command ‘nodemon main.py’ instead which needs to be invoked just the once. After that, it waits till you save the file again and then runs the new script automatically!

Step 4: Your first bot

Now that everything works, let’s follow tradition and make a Hello World program. We will create a command (/hello) on which the bot will respond with the message, ‘Hello, World’. Comment out the code already present in main.py and then add the following three lines.

Here, we import the telegram module and perform some necessary things. Don’t stress with the details, just copy for now.

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
updater = Updater(token='TOKEN', use_context=True) #Replace TOKEN with your token string
dispatcher = updater.dispatcher

Now let’s make a hello function that sends the desired text message through the bot. Notice that, to send a message, ‘context.bot.send_message()’ is used. You can use this line of code whenever you need to send a message; just change the text inside the string to your needs.

def hello(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text='Hello, World')

Now we use a CommandHandler and register it in the dispatcher. Basically, we link the /hello command with the function hello().

hello_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hello_handler)

Again, don’t worry yourself with all the new terms here. Just follow this procedure for every command. Make a function that performs the task required, then use a CommandHandler and register it in the dispatcher.

And that’s it. To start our bot, add this code at the end of the file.

updater.start_polling()

Run the file and enter /hello in your telegram bot. Your bot will respond with “Hello, World”.

Say hello

Congratulations!

Tip: A word prefixed by a forward slash is considered a command in Telegram and is highlighted in the app.

What if the user enters an incorrect command. Let’s add code that replies to all the commands not recognized by the previous handlers. Add this code at the end, after all the other commands.

def unknown(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.")

unknown_handler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(unknown_handler)

Now, try entering an incorrect command like /start, /Hello. Our bot will now politely notify the mistake instead of giving you the cold shoulder.

A small task:

Add a command (/date) that responds with the current date. Use the DateTime module to get the date. For assistance, check out this link.

Note: Remember to put the code above the unknown command snippet!

Step 5: Code the Corona-Bot

The https://api.covid19api.com/ API will be used to bring real-time details about COVID 19. We shall provide a summary of the cases that occurred worldwide till now using this endpoint to get our data.

First, install the requests module. This is an HTTP library module for python which we will use to communicate with the API and handle all the possible responses.

Note: This article doesn’t give you a comprehensive overview of the requests module. This is a good tutorial for those interested in learning more about it. Go through the rest of the article in any case, for now.

Enter this command in cmd (terminal).

$ pip3 install requests

Then add these two lines at the top of main.py.

import requests
import json

Now we create the summary command.

def summary(update, context):
response = requests.get('https://api.covid19api.com/summary')
if(response.status_code==200): #Everything went okay, we have the data
data = response.json()
print(data['Global'])
context.bot.send_message(chat_id=update.effective_chat.id, text=data['Global'])
else: #something went wrong
context.bot.send_message(chat_id=update.effective_chat.id, text="Error, something went wrong.")

corona_summary_handler = CommandHandler('summary', summary)
dispatcher.add_handler(corona_summary_handler)
The bot’s response is not in a very readable format.

The message received is in JSON. It has too many properties and it isn’t in a readable format for the user. Let’s remove newly confirmed, new deaths and new recovered keys from it and present the rest in a readable format.

Replace the summary function with the one below:

def summary(update, context):
response = requests.get('https://api.covid19api.com/summary')
if(response.status_code==200):
data = response.json()
date = data['Date'][:10]
ans = f"Covid 19 Summary (as of {date}): \n";

for attribute, value in data['Global'].items():
if attribute not in ['NewConfirmed', 'NewDeaths', 'NewRecovered']:
ans += 'Total ' + attribute[5::].lower() + " : " + str(value) + "\n"

print(ans)
context.bot.send_message(chat_id=update.effective_chat.id, text=ans)
else:
context.bot.send_message(chat_id=update.effective_chat.id, text="Error, something went wrong.")
A more readable response

The new /summary command sends a much better-formatted response. Nicely done, CoronaBot!

Congratulations, you built your first telegram bot!

Resources:

--

--