Build a telegram bot using python in 10 min!
A quick and extremely simple python project I did after a long break.
Here we go.
We will be creating a bot in telegram. So if you aren’t on telegram, the first step is to sign up. In order to create a bot, we need an API key from telegram. For this we use BotFather. BotFather is telegrams official bot for handing out API keys. Search for BotFather, click on START. To create a new bot type the command /newbot in the chat. Give any name for the chat bot. Next, give a user name for the chat bot, but this name has to be unique. Once that’s done your bot will be created and you’ll get the API key for your bot.
For the coding part, you can use any code editor of your preference. Before we start off, we have to install the package pyTelegramBotAPI, using the command pip install pyTelegramBotAPI.
Lets get into the coding part. Open a file in your text editor. The code will be as follows
import os
import telebot
On the next line give your API key as
API_KEY = “your api key”. This will include your API key in the program.
bot = telebot.TeleBot(API_KEY) #creating the bot using the API
@bot.message_handler (commands=[‘Greet’]) #setup the handler which will look out for commands that the bot receives
def greet(message): #function to pass in the message received by the bot
bot.reply_to(message, “Hey, how are you doin”) #reply to the message
bot.polling() #this command keeps the bot checking for messages
Run the script. Go back to telegram. Open the chat with your bot. All the chat commands start with your bot start with a “/”. Keep that in mind. Now type
/Greet to test your bot.
Again keep the capitalization in mind! Make sure the message you type in is same as that in line number 5 of the code. If you get the response that you’re looking for, hurray! Else there’s a bug probably:)
That was it! The above code could be extended to fetch useful information from the web.