python-telegram-bot

Language: Python

Web

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.

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.

Installation

pip: pip install python-telegram-bot --upgrade
conda: conda install -c conda-forge python-telegram-bot

Usage

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.

Simple bot that replies to /start

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()

Creates a Telegram bot that replies 'Hello! I am your bot.' when a user sends the /start command.

Sending a message to a chat

from telegram import Bot
BOT_TOKEN = 'YOUR_BOT_TOKEN'
bot = Bot(BOT_TOKEN)
bot.send_message(chat_id=123456789, text='Hello from bot!')

Sends a message to a specific chat using the bot token.

Using inline keyboards

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()

Creates a bot with an inline keyboard, and edits the message based on the user selection.

Echo bot for text messages

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))

Replies with the same message text sent by the user, ignoring commands.

Handling multiple commands

def help_command(update, context):
    update.message.reply_text('This is a help message.')

updater.dispatcher.add_handler(CommandHandler('help', help_command))

Adds another command handler to respond to /help with a custom message.

Asynchronous bot with asyncio

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())

Demonstrates creating an asynchronous bot using the latest ApplicationBuilder and asyncio support.

Error Handling

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.