How to Create a Python Bot with Telegram Bot API? Complete Guide
Introduction to Telegram Bots
In today's world, messengers have become an essential part of life, and bots are a convenient tool for automating tasks, communicating with users, and even running a business. If you want to quickly and easily create your own Telegram bot, Python and the python-telegram-bot library are the perfect choice.
Step 1. Get Your Access Token from BotFather
Before writing any code, you need to register your bot with Telegram. Here's how:
- Open Telegram and find the user @BotFather.
- Type the command /start and then /newbot.
- Provide a name and a unique username for your bot (e.g., MyFirstPythonBot).
- After registration, BotFather will give you an API token. Copy it — you'll need it in your code.
Step 2. Install the Required Libraries
To interact with the Telegram API, we'll use the python-telegram-bot library. Install it via pip:
pip install python-telegram-bot --upgrade
Step 3. Basic Bot Skeleton
Now let's create a simple bot that responds to the /start command:
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello! I'm your first Python bot!")
if __name__ == '__main__':
app = ApplicationBuilder().token("YOUR_TOKEN_HERE").build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
Here's what's happening:
ApplicationBuilderandCommandHandlerare the core tools for handling commands.- The
startfunction responds to the /start command and sends a text message to the user. - The
run_polling()method launches the bot and starts checking for new messages.
Step 4. Handle User Messages
Let's add handling for regular text messages:
from telegram.ext import MessageHandler, filters
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
received_text = update.message.text
await update.message.reply_text(f"You wrote: {received_text}")
if __name__ == '__main__':
app = ApplicationBuilder().token("YOUR_TOKEN_HERE").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_polling()
Now the bot will reply to any text message by echoing your text back.
Step 5. Add Buttons and Interactive Menus
Bots become much more user-friendly when you add buttons:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[InlineKeyboardButton("Button 1", callback_data='button1')],
[InlineKeyboardButton("Button 2", callback_data='button2')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text('Choose an option:', reply_markup=reply_markup)
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
await query.edit_message_text(text=f"You clicked: {query.data}")
if __name__ == '__main__':
from telegram.ext import CallbackQueryHandler
app = ApplicationBuilder().token("YOUR_TOKEN_HERE").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("menu", menu))
app.add_handler(CallbackQueryHandler(button_handler))
app.add_handler