Table of contents
No headings in the article.
Bots are cool, yes, super cool, and they make our life super easy. Imagine having a robot do everything you ever wanted. In contrast, you have to rest, take a vacation, or go for that dinner, and you are sure all your activities are covered because of that bot.
Today, I will walk you through some easy steps in creating a Telegram bot in less than 10 minutes. Get your favorite cappuccino, and let's get it on!!!
First thing first, you need to have basic knowledge of python but do not worry; if you do not have any knowledge, I will work you through the process, and you will be fine.
Go to your telegram app and search for BotFather.
Click on it and click on the start at the top right hand corner to begin your journey.
We will have to type in /newbot
to create a new bot, after creating a new bot we will give our bot a name.
Once we are done giving it a name we will be asked to give our bot a username
, remember our username must be dynamic or you will get an error message like it was showed above.
Now you have a working bot!!!
But before you celebrate, we still have a few more things to do.
Copy your APi_Key which will be very important when we start building the logics.
After copying the key, lets open our code editor and for this tutorial i will be using VScode, you can use any other editor.
We will create three files and i will explain what each one is used for
constant.py
reponses.py
main.py
This is where we will keep the API Key we copied from telegram bot
API_KEY = '5372521272:AAEsLdFjg22NI2hwDKr_yhVP8R6Eyawdvg0'
The key is what links our code to telegram and our bot, APIs are like direct access to the particular service of a program or software.
This is where we will store the responses
our bot will give when a user sends a message, we can connect and train our bot but that is taking us too deep, lets just build the bot with simple commands first.
gist.github.com/Scofield-Idehen/1ce87fedf2c..
gist.github.com/Scofield-Idehen/1ce87fedf2c..
first from datetime
we import datetime which will allow us show our users the correct time and updated time and date when they request.
def sample_responses(input_text):
user_message = str(input_text).lower()
Next we define our sample_response
and which we will give an argument of input_text
we create a variable of user_message = string(str)(input_text).lowar()
, this allows our bot to capture what ever the user inputs and match it against our if statement.
.lower
means the text it will capture are lower characters.
if user_message in ("hello", "hi", "sup"):
return "Hey! Who goes you!!!"
if user_message in ("who are you", "can you help me", "who are you"):
return "I am a bot, how can i help you!!!"
if user_message in ("time", "time?", "date?"):
now = datetime.now()
date_time = now.strtime("%d/%m/%y, %H:%M:%S")
return str(date_time)
Our first if statement takes an argument that if the user_message
is “hello”, “hi”, sup”, our bot should return the following, “Who goes you!!!”
Next if statement says if the user ask “who are you” or any of the listed in the second line our bot should return “I am a bot, how can i help you”
The last if
statement answers the time question and give an updated time of the user.
But what if the user inputs something that is not in our if statement, we then call the return of “please type something the human mind can comprehend"
gist.github.com/Scofield-Idehen/d8faead0ced..
gist.github.com/Scofield-Idehen/d8faead0ced..
Do not fret with the code blocks, its repetition of the same steps but lets break it apart.
Before we go on, we have download a library that we will be using, so open your terminal and type in the following.
pip install python- telegram-bot
This install the library that enable us to build our build and control it.
After installing this, if you get error with pip please make sure you have python installed in your system, if not use this link.
from telegram.ext import *
This *
imports everything from the telegram lib to our program.
import responses as R
We import the responses into the main.py
import constant as keys
Here we install the constant where we have our API into the main,py
We create a print statement print (“ Bot Started…”)
that shows the program is running.
def start_command(update, context):
update.message.reply_text('Start now, or forver remain silent.' )
we will define our first command and call it start_command
which will take the argument of (update, context)
it will update the following message of (‘Start now, or forever remain silent.’), so whenever a user opens our bot this message pops up as a welcome message.
def help_command(update, context):
update.message.reply_text('If you need help, please ask your father' )
We create another one but this time we ask our user if they need any help.
def handle_message(update, context):
text = str(update.message.text).lower()
response = R.sample_responses(text)
update.message.reply_text(response)
def error(update, context):
print(f"update {update} caused error {context.error}")
First we create a new def that handles the response of the user.
We also create another def that handles error and we print out the error and list the cause below for easy debugging.
def main():
updater = Updater(keys.API_KEY, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start_command))
dp.add_handler(CommandHandler("help", start_command))
dp.add_handler(MessageHandler(Filters.text, handle_message))
dp.add_error_handler(error)
updater.start_polling(3)
updater.idle()
Here we update the API keys and create a dispatcher
to fetch information between our codes and telegram.
At 8, we add an error handler where we call the def error and print the error message, 9, we set the time our bot will be waiting for user input, and we set that to 3.
We do not want our bot to stop updater.idle()
, so we keep it running even if we do not have any command.
Finally, we set the main()
to run.
Wooooow…..
Our bot is ready and we can test it to see if its working.
Look for the name of your bot and click on start, and you will notice that our start command pops up.
Our bot is replying, and it is working perfectly.
Let me know if you can get yours to work as well.
Best regards
You can follow me on Linkedin and Twitter and give my article a clap if you find it interesting. If I get 1k+ clap, I will write about how to train your bot and make it do more than reply.