Find out how to build a Telegram Bot using python
Building Telegram Bots Made Easy: Your Step-by-Step Guide
Table of contents
Hello there fellow coder's and web surfer's. Have you ever wondered how a telegram bot gives responses for all the messages you send to it.
Or when you want a movie and you use a telegram bot to get the movie illegally. Lets find out how to build one.
Bot Father
Bot father is a bot that helps you to make your own bot
Select or type /newbot
to create a bot, give it a nice username ending with the word 'bot'. This will create a bot for you as shown below.
Remember to safely store the access token
it is needed to program the bot and must never be shared or leaked as it can be used to control the bot(I have revoked my token shown here, you guys do it too if leaked ;) ).
Next, You can use the /setcommands
message to set commands for your bot. you can set commands in the following way.
command1 - command1 description
command2 - command2 description
This is the most basic setup, you guys can explore more commands given by bot father here. You can now search your bot and see that its live. It shows the commands but no responces as we need a server to respond to it, lets create one now.
Using python-telegram-bot
You need to use python-telegram-bot to communicate with telegram apis easily, it is a wrapper over the rest api's that core telegram provide's for developer's.
It's fun
It's simple
Easy to use
Follow the below steps carefully
Firstly, make a new python file called bot.py
make a
.env
file to store your telegram bot token creds as shown below, it should never be hardcoded directly into the code.TELEGRAM_TOKEN="6950516794:AAHc3n56yLBETu9h-MMhKkRzU2QWKQWyaLI"
Make a python virtual enviroment to isolate the packages and avoid conflicts. Run the following command to do so.
python -m venv .venv
Now activate the venv using the below command.
.venv/Scripts/activate # for windows
.venv/bin/activate # for linux based systems
Next download the needed telegram packages.
python-dotenv
is needed to load telegram token from .env file.pip install python-telegram-bot python-dotenv
Now to the most interesting part lets get our hands dirty( I meant by coding).
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
import os
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env file
telegram_token = os.getenv("TELEGRAM_TOKEN") # same name as in .env file
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(update.message.text)
await update.message.reply_text(f"Hello {update.effective_user.first_name}")
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(update.message.text)
await update.message.reply_text("Help message")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(update.message.text)
await update.message.reply_text("I am a bot")
app = ApplicationBuilder().token(telegram_token).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help))
app.add_handler(MessageHandler(filters.TEXT, handle_message))
print("polling started....")
app.run_polling()
The CommandHandler
is used to handle various commands and respond to them like start and help make sure you add them before message handler or else they will be considered as text by filters.TEXT and not a command.
MessageHandler
is used to intercept texts or any filters given.
We need to pass the function that will run on receiving commands, start function for start.
The update
object contains the message sent by the user, user details, and also can make a call to return a response for it.
Now, run the above code by typing python bot.py
in cmd line.
As we can see our bot has received the messages and replied to them.
And thats it, Congratulations on making your first telegram bot.
More advanced bot can be built as well, using the package. Buttons can be sent as well for the user. You guys can futher explore this, I tired to give you guys a basic overview of how easy it is build your own bot in telegram. Hope you guys enjoyed it.
Note: To keep the bot running always you can run it on your machine 24x7 or host in some cloud hosting platforms.
Do checkout the offical docs at https://python-telegram-bot.org/.
Conclusion
Creating a Telegram bot can be a rewarding experience for coders and tech enthusiasts. In this guide, we explored the basic steps to build a simple Telegram bot using the python-telegram-bot
library, a popular wrapper for interacting with Telegram's API.