What it is
python-telegram-bot is a Python library that provides a pure Python interface for the Telegram Bot API. It allows developers to build bots to interact with Telegram users, send messages, handle commands, and integrate with other services.
The library allows you to create bots that respond to messages, commands, and callbacks. It supports inline keyboards, custom keyboards, message formatting, handling updates, and asynchronous execution.
Installation
pip install python-telegram-bot --upgradeGetting started
The smallest useful thing you can do with it, and what each part means.
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
TOKEN = 'YOUR_BOT_TOKEN'
def start(update: Update, context: CallbackContext):
update.message.reply_text('Hello! I am your bot.')
updater = Updater(TOKEN)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()from telegram import Bot
BOT_TOKEN = 'YOUR_BOT_TOKEN'
bot = Bot(BOT_TOKEN)
bot.send_message(chat_id=123456789, text='Hello from bot!')Advanced usage
Where the library earns its place over a simpler alternative.
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
TOKEN = 'YOUR_BOT_TOKEN'
def start(update, context):
keyboard = [[InlineKeyboardButton('Option 1', callback_data='1'),
InlineKeyboardButton('Option 2', callback_data='2')]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Choose:', reply_markup=reply_markup)
def button(update, context):
query = update.callback_query
query.answer()
query.edit_message_text(text=f'Selected option: {query.data}')
updater = Updater(TOKEN)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.start_polling()
updater.idle()from telegram.ext import MessageHandler, Filters
def echo(update, context):
update.message.reply_text(update.message.text)
updater.dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))def help_command(update, context):
update.message.reply_text('This is a help message.')
updater.dispatcher.add_handler(CommandHandler('help', help_command))import asyncio
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler
async def start(update: Update, context):
await update.message.reply_text('Hello async bot!')
app = ApplicationBuilder().token('YOUR_BOT_TOKEN').build()
app.add_handler(CommandHandler('start', start))
asyncio.run(app.run_polling())Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- telegram.error.TelegramError
- Catch general exceptions for API requests and handle network or HTTP errors.
- telegram.error.Unauthorized
- Check your bot token and make sure the bot has permissions to interact with the chat.
- telegram.error.NetworkError
- Retry requests or handle transient network issues gracefully.
Best practices
- Store your bot token securely using environment variables.
- Use CommandHandlers for specific commands and MessageHandlers for general text.
- Keep your bot responsive by using async features for I/O-heavy tasks.
- Handle exceptions in handlers to prevent the bot from crashing.
- Use logging to monitor bot activity and errors.
Background
Why it exists, and what it was reacting to.
python-telegram-bot was created to simplify Telegram bot development using Python. It abstracts HTTP requests to Telegram servers, provides a convenient object-oriented interface, and supports asynchronous programming, making it one of the most popular libraries for Telegram bot development.
