CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-telegram-bot-api

Python Telegram bot API library providing a simple, extensible interface for building Telegram bots with complete Bot API support

Pending
Overview
Eval results
Files

index.mddocs/

pyTelegramBotAPI

A comprehensive Python library for building Telegram bots using the official Telegram Bot API. The library provides a simple yet extensible TeleBot class that encapsulates all API calls and offers convenient methods for sending messages, handling updates, and managing bot interactions with users and groups.

Package Information

  • Package Name: pyTelegramBotAPI
  • Language: Python
  • Installation: pip install pyTelegramBotAPI

Core Imports

import telebot

Common patterns:

from telebot import TeleBot
from telebot import types

For advanced usage:

from telebot import util, apihelper
from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend

Basic Usage

import telebot

# Create bot instance with your token
bot = telebot.TeleBot("YOUR_BOT_TOKEN")

# Handle /start and /help commands
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Hello! I'm a bot.")

# Handle all text messages
@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)

# Start polling for updates
bot.polling()

Architecture

The library follows a layered architecture:

  • TeleBot: Main bot class providing high-level API and handler management
  • apihelper: Low-level functions that interface directly with Telegram Bot API
  • types: Complete set of Telegram API type definitions and serialization
  • util: Utility functions for text processing, threading, and image handling
  • handler_backends: Pluggable storage for next-step and reply handlers

This design provides both simplicity for basic bots and extensibility for complex applications requiring custom middleware, handler persistence, and asynchronous processing.

Capabilities

Bot Core Operations

Primary bot functionality including initialization, authentication, basic information retrieval, and command management. Essential operations every bot needs.

class TeleBot:
    def __init__(self, token: str, parse_mode: Optional[str] = None, 
                 threaded: bool = True, skip_pending: bool = False, 
                 num_threads: int = 2, **kwargs): ...
    def get_me(self) -> types.User: ...
    def log_out(self) -> bool: ...
    def close(self) -> bool: ...
    def get_my_commands(self, scope: Optional[types.BotCommandScope] = None, 
                       language_code: Optional[str] = None) -> List[types.BotCommand]: ...
    def set_my_commands(self, commands: List[types.BotCommand], **kwargs) -> bool: ...
    def delete_my_commands(self, scope: Optional[types.BotCommandScope] = None, 
                          language_code: Optional[str] = None) -> bool: ...

Bot Core

Message Operations

Comprehensive message handling including sending, forwarding, copying, deleting, and editing messages with support for all message types and formatting options.

def send_message(self, chat_id: Union[int, str], text: str, 
                parse_mode: Optional[str] = None, 
                reply_markup: Optional[REPLY_MARKUP_TYPES] = None, **kwargs) -> types.Message: ...
def forward_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str], 
                   message_id: int, **kwargs) -> types.Message: ...
def copy_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str], 
                message_id: int, **kwargs) -> int: ...
def delete_message(self, chat_id: Union[int, str], message_id: int, **kwargs) -> bool: ...
def edit_message_text(self, text: str, chat_id: Optional[Union[int, str]] = None, 
                     message_id: Optional[int] = None, **kwargs) -> Union[types.Message, bool]: ...

Message Operations

Media Handling

Sending and managing multimedia content including photos, videos, audio, documents, stickers, animations, media groups, and sticker set management with thumbnail and metadata support.

def send_photo(self, chat_id: Union[int, str], photo: Union[Any, str], 
              caption: Optional[str] = None, **kwargs) -> types.Message: ...
def send_video(self, chat_id: Union[int, str], data: Union[Any, str], 
              duration: Optional[int] = None, **kwargs) -> types.Message: ...
def send_audio(self, chat_id: Union[int, str], audio: Union[Any, str], 
              caption: Optional[str] = None, **kwargs) -> types.Message: ...
def send_document(self, chat_id: Union[int, str], data: Union[Any, str], **kwargs) -> types.Message: ...
def send_media_group(self, chat_id: Union[int, str], 
                    media: List[Union[types.InputMediaAudio, types.InputMediaDocument, 
                                    types.InputMediaPhoto, types.InputMediaVideo]], 
                    **kwargs) -> List[types.Message]: ...
def create_new_sticker_set(self, user_id: int, name: str, title: str, emojis: str, **kwargs) -> bool: ...
def add_sticker_to_set(self, user_id: int, name: str, emojis: str, **kwargs) -> bool: ...
def delete_sticker_from_set(self, sticker: str) -> bool: ...
def set_sticker_set_thumb(self, name: str, user_id: int, **kwargs) -> bool: ...
def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: ...

Media Handling

Handler System

Comprehensive event handling system supporting message handlers, callback query handlers, inline handlers, and various other update types with filtering capabilities.

def message_handler(self, commands: Optional[List[str]] = None, 
                   regexp: Optional[str] = None, func: Optional[Callable] = None, 
                   content_types: Optional[List[str]] = None, **kwargs): ...
def callback_query_handler(self, func: Callable, **kwargs): ...
def inline_handler(self, func: Callable, **kwargs): ...
def register_next_step_handler(self, message: types.Message, callback: Callable, 
                              *args, **kwargs) -> None: ...
def register_for_reply(self, message: types.Message, callback: Callable, 
                      *args, **kwargs) -> None: ...

Handler System

Update Processing

Update retrieval and processing including polling modes, webhook support, and update filtering with middleware support.

def polling(self, non_stop: bool = False, skip_pending: bool = False, 
           interval: int = 0, timeout: int = 20, 
           long_polling_timeout: int = 20, 
           allowed_updates: Optional[List[str]] = None): ...
def infinity_polling(self, timeout: int = 20, skip_pending: bool = False, 
                    long_polling_timeout: int = 20, **kwargs): ...
def set_webhook(self, url: Optional[str] = None, certificate = None, 
               max_connections: Optional[int] = None, **kwargs) -> bool: ...
def process_new_updates(self, updates: List[types.Update]): ...

Update Processing

Chat Management

Chat administration capabilities including member management, permissions, invite links, and chat settings modification.

def get_chat(self, chat_id: Union[int, str]) -> types.Chat: ...
def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: ...
def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: ...
def ban_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
def unban_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
def restrict_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
def promote_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...

Chat Management

Interactive Elements

Interactive features including inline keyboards, custom keyboards, polls, games, payments, invoices, and callback query handling.

def send_poll(self, chat_id: Union[int, str], question: str, options: List[str], 
             **kwargs) -> types.Message: ...
def stop_poll(self, chat_id: Union[int, str], message_id: int, **kwargs) -> types.Poll: ...
def send_game(self, chat_id: Union[int, str], game_short_name: str, **kwargs) -> types.Message: ...
def answer_callback_query(self, callback_query_id: int, text: Optional[str] = None, 
                         **kwargs) -> bool: ...
def answer_inline_query(self, inline_query_id: str, results: List[Any], **kwargs) -> bool: ...
def send_invoice(self, chat_id: Union[int, str], title: str, description: str, 
                invoice_payload: str, provider_token: str, currency: str, 
                prices: List[types.LabeledPrice], **kwargs) -> types.Message: ...
def answer_shipping_query(self, shipping_query_id: str, ok: bool, **kwargs) -> bool: ...
def answer_pre_checkout_query(self, pre_checkout_query_id: str, ok: bool, **kwargs) -> bool: ...

Interactive Elements

Utility Functions

Text processing, HTML formatting, and convenience functions for common bot development tasks.

def is_command(text: str) -> bool:
    """
    Check if text is a Telegram command (starts with '/').
    
    Parameters:
    - text (str): Text to check
    
    Returns:
    bool: True if text is a command
    """

def extract_command(text: str) -> Optional[str]:
    """
    Extract command name from command text (without '/').
    
    Parameters:
    - text (str): Command text
    
    Returns:
    Optional[str]: Command name or None if not a command
    """

def extract_arguments(text: str) -> str:
    """
    Extract arguments from command text.
    
    Parameters:
    - text (str): Command text
    
    Returns:
    str: Arguments following the command
    """

def split_string(text: str, chars_per_string: int) -> List[str]:
    """
    Split long text into chunks for message length limits.
    
    Parameters:
    - text (str): Text to split
    - chars_per_string (int): Maximum characters per chunk
    
    Returns:
    List[str]: List of text chunks
    """

def smart_split(text: str, chars_per_string: int = 4096) -> List[str]:
    """
    Intelligently split text at natural boundaries (newlines, sentences, words).
    
    Parameters:
    - text (str): Text to split
    - chars_per_string (int): Maximum characters per chunk (default 4096)
    
    Returns:
    List[str]: List of text chunks split at natural boundaries
    """

def escape(text: str) -> str:
    """
    Escape HTML special characters (&, <, >) for HTML parse mode.
    
    Parameters:
    - text (str): Text to escape
    
    Returns:
    str: HTML-escaped text
    """

def user_link(user: types.User, include_id: bool = False) -> str:
    """
    Generate HTML link for user mentions.
    
    Parameters:
    - user (User): User object
    - include_id (bool): Include user ID in link text
    
    Returns:
    str: HTML user link
    """

def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int = 2) -> types.InlineKeyboardMarkup:
    """
    Create inline keyboard markup from dictionary format.
    
    Parameters:
    - values (Dict[str, Dict[str, Any]]): Button text to kwargs mapping
    - row_width (int): Buttons per row
    
    Returns:
    InlineKeyboardMarkup: Generated keyboard markup
    """

Types

Core type definitions used throughout the API:

REPLY_MARKUP_TYPES = Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, 
                          types.ReplyKeyboardRemove, types.ForceReply]

class Update:
    update_id: int
    message: Optional[Message]
    edited_message: Optional[Message]
    channel_post: Optional[Message]
    edited_channel_post: Optional[Message]
    inline_query: Optional[InlineQuery]
    chosen_inline_result: Optional[ChosenInlineResult]
    callback_query: Optional[CallbackQuery]
    # ... additional fields

class Message:
    message_id: int
    from_user: Optional[User]
    date: int
    chat: Chat
    content_type: str
    text: Optional[str]
    # ... additional fields based on content type

class User:
    id: int
    is_bot: bool
    first_name: str
    last_name: Optional[str]
    username: Optional[str]
    language_code: Optional[str]

class Chat:
    id: int
    type: str  # 'private', 'group', 'supergroup', 'channel'
    title: Optional[str]
    username: Optional[str]
    first_name: Optional[str]
    last_name: Optional[str]

Install with Tessl CLI

npx tessl i tessl/pypi-py-telegram-bot-api

docs

bot-core.md

chat-management.md

handler-system.md

index.md

interactive-elements.md

media-handling.md

message-operations.md

update-processing.md

tile.json