First telegram bot in python.

Prakhar Agarwal
5 min readMay 21, 2021

Hola Amigos !

In this short blog , I will walk you guys through the steps for creating your own Telegram bot in python. I would like to show you how you can create a simple telegram bot.

Let me give a background on how i landed up on this thought.

In this pandemic when we all are locked out and fighting with this vicious virus. I thought of creating a bot that will give the nearest vaccination centers as per the pincode and district name provided by the user.

So what my bot does ? It throws 5 questions and based on the answers it will respond back with the nearest available vaccination centers along with available capacity. These answers will act as filters to take off unnecessary and not required data. I am using Co-WIN Public APIs provided by Indian Government to get all these data.

It also has subscribing feature where on subscribing user gets automatic notification if there is any update. I am hitting the API on every 2 mins and comparing the current response with the previous one. If the current and previous responses are same there will be no message.

Check it out on Telegram . Bot name : Vaccine_ki_Khoj
Note : Useful for Indian Users only.

I never worked with python before and being a complete novice it took 4 days to complete this bot.

This was my use case of creating one such bot. Similarly there could be many use cases like you can use it to send automatic notifications on cryptocurrency price , stock values , send daily quotes to user , create surveys or quizzes and many more. Think about your objective and let me know in comment section if you need any help.

In this blog i am not covering my use case. We will be creating a simple echo bot where our bot echoes the messages that we send to it. Trust me it would take hardly 15 mins to create and run this bot.

As a prerequisite make sure you have python installed in your system. So lets get started with this fun activity.

1. Register a new bot in BotFather

In order to create a bot in Telegram, first you have to “register” it with telegram. To achieve this you need to contact the BotFather, which is essentially a bot used to create other bots. When we “register” our bot, we will get the token to access the Telegram API.

  • Search for @botfather in Telegram. You can use telegram app on phone/desktop or web app as well.
  • Press Start button to start the conversation.
  • Create the bot by running /newbot command
  • Enter the Display Name and User Name for the bot.
  • BotFather will send you a message with the token.

NOTE— Keep it secure. Anyone with its access can manipulate your bot.

By the way, BotFather is also able to perform following actions for you:

  • Put description to your bot
  • Upload avatar
  • Change access token
  • Delete your bot etc.

2. Lets Code

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

Lets start coding our bot.

Create a file bot.py . First lets have our imports in place.

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

Now lets define our functions . These functions are basically command/message handlers. They usually take the two arguments update of type Update and context of type CallbackContext . Error handlers also receive the raised TelegramError object in error.

In our bot we will define three function , one to handle our /start command

def start_bot(update,context):
# Your bot will send this message when users first talk to bot
#using /start command
update.message.reply_text('Hi! Welcome. Please give me any text
and i will echo it for you')

this handler will take of care of /help command.

def need_help(update, context):     
# on /help command
update.message.reply_text('Help!')

and this messagehandler function will be called for remaining text other than /start and /help.

def echo(update, context):     
update.message.reply_text(update.message.text)

Lastly, lets have our main to run our program. Change YOUR_TOKEN with the token that we generated earlier in this tutorial.

def main():
updater = Updater('YOUR_TOKEN')

#get dispatcher from updater to register handlers
dp = updater.dispatcher

# adding start command handler to dispatcher.
#handles /start command
dp.add_handler(CommandHandler('start',start_bot))
# calls help method on /help command
dp.add_handler(CommandHandler('help',need_help))
#on noncommand i.e for text other than start and help , echo
#the message on Telegram

dp.add_handler(MessageHandler(Filters.text, echo))

# 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
updater.idle()

if __name__ == '__main__':
main()

This code uses polling approach to check for messages and will reply to every message it receives with the same message. Here our server is checking hitting our bot continuously and checking for any message. Another way is webhook.

Webhook provides us a way of letting the bot call our server whenever a message is called, so that we don’t need to make our server suffer in a while loop waiting for a message to come.

Run the script

python bot.py

Goto your telegram , search for bot with the name give during registering with BotFather . Type /start to start the conversion and enjoy.

Voilà ! We’re done with our first bot.

Lets check our Echo 🤖 in action

TIP :

In order to make you bot active 24*7 , you need to have the script up and running all the time. You can have it deployed on any of the cloud service. For my use case i used AWS EC2 instance. I chose Ubuntu 18.04 , installed python on it and run below

nohop python3 bot.py &

this will run the script in background.

--

--

Prakhar Agarwal

An enthusiastic coder ,learner and a mountain lover.