or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdapplication-framework.mdbot-api.mdfiles.mdfilters.mdhandlers.mdindex.mdkeyboards.mdtelegram-types.md
tile.json

tessl/pypi-python-telegram-bot

A pure Python, asynchronous interface for the Telegram Bot API with comprehensive wrapper and high-level framework for building sophisticated Telegram bots

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-telegram-bot@21.11.x

To install, run

npx @tessl/cli install tessl/pypi-python-telegram-bot@21.11.0

index.mddocs/

Python Telegram Bot

A comprehensive, asynchronous Python library providing a complete interface to the Telegram Bot API. This library offers both a pure API wrapper and a high-level framework for building sophisticated Telegram bots with minimal complexity.

Package Information

  • Package Name: python-telegram-bot
  • Language: Python
  • Installation: pip install python-telegram-bot
  • Python Version: 3.9+
  • API Version: Telegram Bot API 8.3

Core Imports

from telegram import Bot, Update
from telegram.ext import Application, ApplicationBuilder

For basic bot functionality:

from telegram import Bot
from telegram.ext import Application, CommandHandler, MessageHandler, filters

Basic Usage

import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /start is issued."""
    await update.message.reply_text('Hi! I am your bot.')

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Echo the user message."""
    await update.message.reply_text(update.message.text)

def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your bot's token
    application = Application.builder().token("YOUR_BOT_TOKEN").build()

    # Register handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Run the bot until you press Ctrl-C
    application.run_polling()

if __name__ == '__main__':
    main()

Architecture

The library is structured around two main layers:

  • Core API Layer (telegram.*): Direct wrapper around Telegram Bot API providing all types and methods
  • Extension Framework (telegram.ext.*): High-level framework with application management, handlers, persistence, and utilities

Key components:

  • Application: Central coordinator managing bot lifecycle, handlers, and updates
  • Handlers: Process specific types of updates (commands, messages, callbacks, etc.)
  • Bot: Provides all Telegram Bot API methods for sending messages and managing bot
  • Update: Represents incoming data from Telegram
  • Filters: Filter incoming updates based on criteria

Capabilities

Bot Core API

Core Bot class providing all Telegram Bot API methods for sending messages, managing files, handling chats and users, and bot administration.

class Bot:
    def __init__(self, token: str, **kwargs): ...
    async def send_message(self, chat_id: int | str, text: str, **kwargs) -> Message: ...
    async def send_photo(self, chat_id: int | str, photo: InputFile | str, **kwargs) -> Message: ...
    async def get_updates(self, **kwargs) -> list[Update]: ...
    async def get_me() -> User: ...

Bot API

Application Framework

High-level framework for building and managing Telegram bots with handlers, job queues, persistence, and lifecycle management.

class Application:
    def add_handler(self, handler: BaseHandler) -> None: ...
    def run_polling(self, **kwargs) -> None: ...
    def run_webhook(self, **kwargs) -> None: ...
    
class ApplicationBuilder:
    def token(self, token: str) -> 'ApplicationBuilder': ...
    def build() -> Application: ...

Application Framework

Message Handlers

Comprehensive handler system for processing different types of updates including commands, messages, callbacks, inline queries, and other Telegram events.

class CommandHandler(BaseHandler):
    def __init__(self, command: str, callback: callable, **kwargs): ...

class MessageHandler(BaseHandler):
    def __init__(self, filters: BaseFilter, callback: callable, **kwargs): ...

class CallbackQueryHandler(BaseHandler):
    def __init__(self, callback: callable, **kwargs): ...

Handlers

Telegram Types

Complete type system covering all Telegram Bot API objects including messages, users, chats, files, keyboards, payments, games, and passport data.

class Update:
    message: Message | None
    callback_query: CallbackQuery | None
    inline_query: InlineQuery | None

class Message:
    message_id: int
    from_user: User | None
    chat: Chat
    text: str | None
    
class User:
    id: int
    is_bot: bool
    first_name: str
    username: str | None

Telegram Types

Keyboards and Markup

Inline and reply keyboards with comprehensive button types including web apps, contact/location requests, and callback data.

class ReplyKeyboardMarkup:
    def __init__(self, keyboard: list[list[KeyboardButton]], **kwargs): ...

class InlineKeyboardMarkup:
    def __init__(self, inline_keyboard: list[list[InlineKeyboardButton]]): ...

class KeyboardButton:
    def __init__(self, text: str, **kwargs): ...

class InlineKeyboardButton:
    def __init__(self, text: str, **kwargs): ...

Keyboards

File Operations

Complete file handling including uploads, downloads, and media processing with support for all Telegram file types.

class InputFile:
    def __init__(self, obj: BinaryIO | bytes | str): ...

class File:
    file_id: str
    file_unique_id: str
    file_path: str | None
    async def download_to_drive(self, custom_path: str = None) -> str: ...

Files

Filters System

Powerful filtering system for precisely targeting which updates handlers should process, with built-in filters and custom filter creation.

class filters:
    TEXT: MessageFilter
    COMMAND: MessageFilter
    PHOTO: MessageFilter
    VIDEO: MessageFilter
    ALL: UpdateFilter

Filters

Advanced Features

Additional capabilities including job queues, persistence, rate limiting, conversation handling, and webhook management.

class JobQueue:
    def run_once(self, callback: callable, when: float, **kwargs) -> Job: ...
    def run_repeating(self, callback: callable, interval: float, **kwargs) -> Job: ...

class PicklePersistence(BasePersistence):
    def __init__(self, filepath: str, **kwargs): ...

Advanced Features

Error Handling

The library provides comprehensive error handling through the telegram.error module:

class TelegramError(Exception):
    """Base class for all Telegram errors."""
    def __init__(self, message: str): ...

class NetworkError(TelegramError):
    """Base class for exceptions due to networking errors."""

class BadRequest(NetworkError):
    """Raised when Telegram could not process the request correctly."""

class Forbidden(TelegramError):
    """Raised when the bot has not enough rights to perform the requested action."""

class TimedOut(NetworkError):
    """Raised when a request took too long to finish."""

class InvalidToken(TelegramError):
    """Raised when the token is invalid."""

class ChatMigrated(TelegramError):
    """Raised when group chat migrated to supergroup."""
    def __init__(self, new_chat_id: int): ...
    new_chat_id: int

class RetryAfter(TelegramError):
    """Raised when flood limits were exceeded."""
    def __init__(self, retry_after: int): ...
    retry_after: int

class Conflict(TelegramError):
    """Raised when a long poll or webhook conflicts with another one."""

class EndPointNotFound(TelegramError):
    """Raised when the requested endpoint is not found."""

class PassportDecryptionError(TelegramError):
    """Something went wrong with decryption."""

Common error handling patterns:

from telegram.error import (
    TelegramError, BadRequest, Forbidden, TimedOut, 
    NetworkError, ChatMigrated, RetryAfter
)

# Basic error handling
try:
    await bot.send_message(chat_id, "Hello!")
except BadRequest as e:
    print(f"Bad request: {e}")
except Forbidden as e:
    print(f"Bot blocked or insufficient permissions: {e}")
except TimedOut as e:
    print(f"Request timed out: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except TelegramError as e:
    print(f"Other Telegram error: {e}")

# Handling specific scenarios
try:
    await bot.send_message(chat_id, "Hello!")
except ChatMigrated as e:
    # Update chat_id and retry
    new_chat_id = e.new_chat_id
    await bot.send_message(new_chat_id, "Hello!")
except RetryAfter as e:
    # Wait and retry
    import asyncio
    await asyncio.sleep(e.retry_after)
    await bot.send_message(chat_id, "Hello!")

Constants and Utilities

Access to all Telegram Bot API constants, limits, and utility functions:

from telegram import constants
from telegram.helpers import escape_markdown, mention_html

# Constants
max_message_length = constants.MessageLimit.MAX_TEXT_LENGTH
parse_mode = constants.ParseMode.MARKDOWN_V2

# Helpers
escaped_text = escape_markdown("Text with *special* characters")
user_mention = mention_html(user.id, user.first_name)