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

handler-system.mddocs/

Handler System

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

Capabilities

Message Handlers

Register handlers for different types of messages with filtering by commands, content types, and custom functions.

def message_handler(self, commands: Optional[List[str]] = None,
                   regexp: Optional[str] = None,
                   func: Optional[Callable] = None,
                   content_types: Optional[List[str]] = None, **kwargs):
    """
    Decorator for message handling with various filters.

    Parameters:
    - commands (List[str], optional): Bot commands to handle (['start', 'help'])
    - regexp (str, optional): Regular expression pattern for text matching
    - func (Callable, optional): Custom filter function receiving message
    - content_types (List[str], optional): Content types to handle (default: ['text'])
    - **kwargs: Additional filter parameters

    Usage:
    @bot.message_handler(commands=['start'])
    @bot.message_handler(content_types=['photo', 'video'])
    @bot.message_handler(func=lambda msg: msg.text and 'hello' in msg.text.lower())
    """

def add_message_handler(self, handler_dict):
    """
    Programmatically add message handler.

    Parameters:
    - handler_dict (dict): Handler configuration dictionary
    """

def register_message_handler(self, callback: Callable, content_types: Optional[List[str]] = None,
                            commands: Optional[List[str]] = None, regexp: Optional[str] = None,
                            func: Optional[Callable] = None, **kwargs):
    """
    Register message handler without decorator.

    Parameters:
    - callback (Callable): Handler function
    - content_types (List[str], optional): Content types to handle
    - commands (List[str], optional): Commands to handle
    - regexp (str, optional): Regular expression pattern
    - func (Callable, optional): Custom filter function
    """

Callback Query Handlers

Handle button clicks from inline keyboards.

def callback_query_handler(self, func: Callable, **kwargs):
    """
    Decorator for callback query handling.

    Parameters:
    - func (Callable): Filter function for callback queries
    - **kwargs: Additional filter parameters

    Usage:
    @bot.callback_query_handler(func=lambda call: call.data.startswith('btn_'))
    """

def answer_callback_query(self, callback_query_id: int, text: Optional[str] = None,
                         show_alert: Optional[bool] = None, url: Optional[str] = None,
                         cache_time: Optional[int] = None) -> bool:
    """
    Answer callback queries from inline keyboards.

    Parameters:
    - callback_query_id (int): Unique identifier for the query
    - text (str, optional): Text notification to show (0-200 characters)
    - show_alert (bool, optional): Show alert instead of notification
    - url (str, optional): URL to open by the client
    - cache_time (int, optional): Cache time for the answer

    Returns:
    bool: True on success
    """

Next Step and Reply Handlers

Handle conversational flow and replies to specific messages.

def register_next_step_handler(self, message: types.Message, callback: Callable,
                              *args, **kwargs) -> None:
    """
    Register handler for next message from user in same chat.

    Parameters:
    - message (Message): Message that triggers next step handling
    - callback (Callable): Function to call on next message
    - *args: Arguments to pass to callback
    - **kwargs: Keyword arguments to pass to callback
    """

def register_next_step_handler_by_chat_id(self, chat_id: Union[int, str], callback: Callable,
                                         *args, **kwargs) -> None:
    """
    Register next step handler by chat ID.

    Parameters:
    - chat_id (Union[int, str]): Chat ID to monitor
    - callback (Callable): Handler function
    - *args: Arguments to pass to callback
    - **kwargs: Keyword arguments to pass to callback
    """

def register_for_reply(self, message: types.Message, callback: Callable,
                      *args, **kwargs) -> None:
    """
    Register handler for replies to specific message.

    Parameters:
    - message (Message): Message to wait for replies to
    - callback (Callable): Function to call when reply received
    - *args: Arguments to pass to callback
    - **kwargs: Keyword arguments to pass to callback
    """

def clear_step_handler(self, message: types.Message) -> None:
    """Clear next step handlers for a chat."""

def clear_reply_handlers(self, message: types.Message) -> None:
    """Clear reply handlers for a message."""

Specialized Handlers

Handle various other update types including inline queries, polls, and chat member changes.

def inline_handler(self, func: Callable, **kwargs):
    """
    Decorator for inline query handling.

    Parameters:
    - func (Callable): Filter function for inline queries
    """

def poll_handler(self, func: Callable, **kwargs):
    """
    Decorator for poll update handling.

    Parameters:
    - func (Callable): Filter function for polls
    """

def poll_answer_handler(self, func: Optional[Callable] = None, **kwargs):
    """
    Decorator for poll answer handling.

    Parameters:
    - func (Callable, optional): Filter function for poll answers
    """

def my_chat_member_handler(self, func: Optional[Callable] = None, **kwargs):
    """
    Decorator for bot's chat membership changes.

    Parameters:
    - func (Callable, optional): Filter function for membership changes
    """

def chat_member_handler(self, func: Optional[Callable] = None, **kwargs):
    """
    Decorator for chat member status changes.

    Parameters:
    - func (Callable, optional): Filter function for member changes
    """

Middleware System

Add middleware for preprocessing updates before handlers.

def middleware_handler(self, update_types: Optional[List[str]] = None):
    """
    Decorator for middleware handlers.

    Parameters:
    - update_types (List[str], optional): Update types to process
                   (['message', 'callback_query', 'inline_query', etc.])

    Usage:
    @bot.middleware_handler(['message'])
    def log_messages(bot_instance, message):
        print(f"Received: {message.text}")
    """

def add_middleware_handler(self, handler: Callable, update_types: Optional[List[str]] = None):
    """
    Add middleware handler programmatically.

    Parameters:
    - handler (Callable): Middleware function
    - update_types (List[str], optional): Update types to process
    """

Usage Examples

Basic Message Handler

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Hello! How can I help you?")

@bot.message_handler(content_types=['photo'])
def handle_photo(message):
    bot.reply_to(message, "Nice photo!")

@bot.message_handler(func=lambda msg: msg.text and 'hello' in msg.text.lower())
def handle_hello(message):
    bot.reply_to(message, "Hello there!")

Conversational Flow Example

@bot.message_handler(commands=['name'])
def ask_name(message):
    msg = bot.reply_to(message, "What's your name?")
    bot.register_next_step_handler(msg, process_name)

def process_name(message):
    name = message.text
    msg = bot.reply_to(message, f"Nice to meet you, {name}! How old are you?")
    bot.register_next_step_handler(msg, process_age, name)

def process_age(message, name):
    try:
        age = int(message.text)
        bot.reply_to(message, f"Great! {name}, you are {age} years old.")
    except ValueError:
        msg = bot.reply_to(message, "Please enter a valid number:")
        bot.register_next_step_handler(msg, process_age, name)

Inline Keyboard and Callback Example

from telebot import types

@bot.message_handler(commands=['menu'])
def show_menu(message):
    markup = types.InlineKeyboardMarkup()
    markup.row(
        types.InlineKeyboardButton("Option 1", callback_data="opt1"),
        types.InlineKeyboardButton("Option 2", callback_data="opt2")
    )
    bot.send_message(message.chat.id, "Choose an option:", reply_markup=markup)

@bot.callback_query_handler(func=lambda call: call.data.startswith('opt'))
def handle_menu_callback(call):
    bot.answer_callback_query(call.id)
    
    if call.data == "opt1":
        bot.send_message(call.message.chat.id, "You chose Option 1!")
    elif call.data == "opt2":
        bot.send_message(call.message.chat.id, "You chose Option 2!")

Middleware Example

# Enable middleware
import telebot.apihelper
telebot.apihelper.ENABLE_MIDDLEWARE = True

@bot.middleware_handler(['message'])
def log_messages(bot_instance, message):
    print(f"User {message.from_user.id} sent: {message.text}")

@bot.middleware_handler()  # All update types
def security_check(bot_instance, update):
    # Add security checks, rate limiting, etc.
    pass

Types

class CallbackQuery:
    id: str
    from_user: User
    message: Optional[Message]
    inline_message_id: Optional[str]
    chat_instance: str
    data: Optional[str]
    game_short_name: Optional[str]

class InlineQuery:
    id: str
    from_user: User
    query: str
    offset: str
    chat_type: Optional[str]
    location: Optional[Location]

class Poll:
    id: str
    question: str
    options: List[PollOption]
    total_voter_count: int
    is_closed: bool
    is_anonymous: bool
    type: str
    allows_multiple_answers: bool

class PollAnswer:
    poll_id: str
    user: User
    option_ids: List[int]

class ChatMemberUpdated:
    chat: Chat
    from_user: User
    date: int
    old_chat_member: ChatMember
    new_chat_member: ChatMember
    invite_link: Optional[ChatInviteLink]

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