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

interactive-elements.mddocs/

Interactive Elements

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

Capabilities

Polls and Voting

Create, send, and manage polls with various question types and voting options.

def send_poll(self, chat_id: Union[int, str], question: str, options: List[str],
             is_anonymous: Optional[bool] = None, type: Optional[str] = None,
             allows_multiple_answers: Optional[bool] = None,
             correct_option_id: Optional[int] = None,
             explanation: Optional[str] = None,
             explanation_parse_mode: Optional[str] = None,
             open_period: Optional[int] = None,
             close_date: Optional[Union[int, datetime]] = None,
             is_closed: Optional[bool] = None,
             disable_notification: Optional[bool] = False,
             reply_to_message_id: Optional[int] = None,
             reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
             allow_sending_without_reply: Optional[bool] = None,
             timeout: Optional[int] = None,
             explanation_entities: Optional[List[types.MessageEntity]] = None) -> types.Message:
    """
    Send polls with customizable voting options and behavior.

    Parameters:
    - chat_id (Union[int, str]): Target chat
    - question (str): Poll question (1-300 characters)
    - options (List[str]): List of answer options (2-10 options, 1-100 characters each)
    - is_anonymous (bool, optional): True for anonymous polls
    - type (str, optional): Poll type ('quiz' or 'regular')
    - allows_multiple_answers (bool, optional): Allow multiple answers (regular polls only)
    - correct_option_id (int, optional): Correct answer ID (quiz polls only)
    - explanation (str, optional): Explanation for quiz answer (0-200 characters)
    - explanation_parse_mode (str, optional): Explanation parsing mode
    - open_period (int, optional): Auto-close period in seconds (5-600)
    - close_date (Union[int, datetime], optional): Point when poll closes
    - is_closed (bool, optional): Send closed poll
    - disable_notification (bool, optional): Send silently
    - reply_to_message_id (int, optional): Message to reply to
    - reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
    - allow_sending_without_reply (bool, optional): Send if reply target missing
    - timeout (int, optional): Request timeout
    - explanation_entities (List[MessageEntity], optional): Explanation entities

    Returns:
    Message: Sent poll message
    """

def stop_poll(self, chat_id: Union[int, str], message_id: int,
             reply_markup: Optional[REPLY_MARKUP_TYPES] = None) -> types.Poll:
    """
    Stop a poll which was sent by the bot.

    Parameters:
    - chat_id (Union[int, str]): Chat where poll was sent
    - message_id (int): Poll message ID
    - reply_markup (REPLY_MARKUP_TYPES, optional): New inline keyboard

    Returns:
    Poll: Stopped poll with final results
    """

Games

Send and manage games with score tracking and leaderboards.

def send_game(self, chat_id: Union[int, str], game_short_name: str,
             disable_notification: Optional[bool] = None,
             reply_to_message_id: Optional[int] = None,
             reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
             timeout: Optional[int] = None,
             allow_sending_without_reply: Optional[bool] = None) -> types.Message:
    """
    Send a game message.

    Parameters:
    - chat_id (Union[int, str]): Target chat
    - game_short_name (str): Short name of the game
    - disable_notification (bool, optional): Send silently
    - reply_to_message_id (int, optional): Message to reply to
    - reply_markup (REPLY_MARKUP_TYPES, optional): Inline keyboard
    - timeout (int, optional): Request timeout
    - allow_sending_without_reply (bool, optional): Send if reply target missing

    Returns:
    Message: Sent game message
    """

def set_game_score(self, user_id: Union[int, str], score: int,
                  force: Optional[bool] = None,
                  chat_id: Optional[Union[int, str]] = None,
                  message_id: Optional[int] = None,
                  inline_message_id: Optional[str] = None,
                  disable_edit_message: Optional[bool] = None) -> Union[types.Message, bool]:
    """
    Set the score of the specified user in a game.

    Parameters:
    - user_id (Union[int, str]): User identifier
    - score (int): New score (must be non-negative)
    - force (bool, optional): Pass True to set score even if it's lower
    - chat_id (Union[int, str], optional): Chat where game was sent
    - message_id (int, optional): Game message ID
    - inline_message_id (str, optional): Inline message ID
    - disable_edit_message (bool, optional): Don't edit the game message

    Returns:
    Union[Message, bool]: Edited message or True for inline messages
    """

def get_game_high_scores(self, user_id: int, chat_id: Optional[Union[int, str]] = None,
                        message_id: Optional[int] = None,
                        inline_message_id: Optional[str] = None) -> List[types.GameHighScore]:
    """
    Get data for high score tables of a game.

    Parameters:
    - user_id (int): Target user ID
    - chat_id (Union[int, str], optional): Chat where game was sent
    - message_id (int, optional): Game message ID
    - inline_message_id (str, optional): Inline message ID

    Returns:
    List[GameHighScore]: Game high scores
    """

Dice and Random Elements

Send animated dice and other random elements.

def send_dice(self, chat_id: Union[int, str], emoji: Optional[str] = None,
             disable_notification: Optional[bool] = None,
             reply_to_message_id: Optional[int] = None,
             reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
             timeout: Optional[int] = None,
             allow_sending_without_reply: Optional[bool] = None) -> types.Message:
    """
    Send animated dice or other random value generators.

    Parameters:
    - chat_id (Union[int, str]): Target chat
    - emoji (str, optional): Emoji type ('🎲', '🎯', '🏀', '⚽', '🎳', '🎰')
    - disable_notification (bool, optional): Send silently
    - reply_to_message_id (int, optional): Message to reply to
    - reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
    - timeout (int, optional): Request timeout
    - allow_sending_without_reply (bool, optional): Send if reply target missing

    Returns:
    Message: Sent dice message with animation
    """

Inline Query Handling

Handle and respond to inline queries for inline bot functionality.

def answer_inline_query(self, inline_query_id: str, results: List[Any],
                       cache_time: Optional[int] = None,
                       is_personal: Optional[bool] = None,
                       next_offset: Optional[str] = None,
                       switch_pm_text: Optional[str] = None,
                       switch_pm_parameter: Optional[str] = None) -> bool:
    """
    Send answers to an inline query.

    Parameters:
    - inline_query_id (str): Unique identifier for the query
    - results (List[Any]): Array of results for the inline query (max 50)
    - cache_time (int, optional): Cache time for results on server (default 300)
    - is_personal (bool, optional): Cache results on server for user only
    - next_offset (str, optional): Offset for next query with same text
    - switch_pm_text (str, optional): Button text to switch to private chat
    - switch_pm_parameter (str, optional): Parameter for the start message

    Returns:
    bool: True on success
    """

Venue and Location Sharing

Send venue information and location data.

def send_venue(self, chat_id: Union[int, str], latitude: float, longitude: float,
              title: str, address: str, foursquare_id: Optional[str] = None,
              foursquare_type: Optional[str] = None,
              disable_notification: Optional[bool] = None,
              reply_to_message_id: Optional[int] = None,
              reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
              timeout: Optional[int] = None,
              allow_sending_without_reply: Optional[bool] = None,
              google_place_id: Optional[str] = None,
              google_place_type: Optional[str] = None) -> types.Message:
    """
    Send information about a venue.

    Parameters:
    - chat_id (Union[int, str]): Target chat
    - latitude (float): Venue latitude
    - longitude (float): Venue longitude
    - title (str): Venue name
    - address (str): Venue address
    - foursquare_id (str, optional): Foursquare identifier
    - foursquare_type (str, optional): Foursquare type
    - disable_notification (bool, optional): Send silently
    - reply_to_message_id (int, optional): Message to reply to
    - reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
    - timeout (int, optional): Request timeout
    - allow_sending_without_reply (bool, optional): Send if reply target missing
    - google_place_id (str, optional): Google Places identifier
    - google_place_type (str, optional): Google Places type

    Returns:
    Message: Sent venue message
    """

Payments and Invoices

Send invoices, process payments, and handle shipping queries for e-commerce functionality.

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], 
                start_parameter: Optional[str] = None, 
                photo_url: Optional[str] = None, 
                photo_size: Optional[int] = None, 
                photo_width: Optional[int] = None, 
                photo_height: Optional[int] = None,
                need_name: Optional[bool] = None, 
                need_phone_number: Optional[bool] = None, 
                need_email: Optional[bool] = None, 
                need_shipping_address: Optional[bool] = None,
                send_phone_number_to_provider: Optional[bool] = None, 
                send_email_to_provider: Optional[bool] = None, 
                is_flexible: Optional[bool] = None,
                disable_notification: Optional[bool] = None, 
                reply_to_message_id: Optional[int] = None, 
                reply_markup: Optional[REPLY_MARKUP_TYPES] = None, 
                provider_data: Optional[str] = None, 
                timeout: Optional[int] = None,
                allow_sending_without_reply: Optional[bool] = None,
                max_tip_amount: Optional[int] = None,
                suggested_tip_amounts: Optional[List[int]] = None) -> types.Message:
    """
    Send invoices for payment processing.

    Parameters:
    - chat_id (Union[int, str]): Target chat (must be private)
    - title (str): Product name (1-32 characters)
    - description (str): Product description (1-255 characters)
    - invoice_payload (str): Bot-defined invoice payload (1-128 bytes)
    - provider_token (str): Payment provider token from @BotFather
    - currency (str): Three-letter ISO 4217 currency code
    - prices (List[LabeledPrice]): Breakdown of prices
    - start_parameter (str, optional): Deep-linking parameter
    - photo_url (str, optional): Product photo URL
    - photo_size (int, optional): Photo size in bytes
    - photo_width (int, optional): Photo width
    - photo_height (int, optional): Photo height
    - need_name (bool, optional): Require user's full name
    - need_phone_number (bool, optional): Require user's phone number
    - need_email (bool, optional): Require user's email address
    - need_shipping_address (bool, optional): Require user's shipping address
    - send_phone_number_to_provider (bool, optional): Pass phone to provider
    - send_email_to_provider (bool, optional): Pass email to provider
    - is_flexible (bool, optional): Price depends on shipping method
    - disable_notification (bool, optional): Send silently
    - reply_to_message_id (int, optional): Message to reply to
    - reply_markup (REPLY_MARKUP_TYPES, optional): Inline keyboard markup
    - provider_data (str, optional): JSON data for payment provider
    - timeout (int, optional): Request timeout
    - allow_sending_without_reply (bool, optional): Send if reply target missing
    - max_tip_amount (int, optional): Maximum accepted tip amount
    - suggested_tip_amounts (List[int], optional): Suggested tip amounts

    Returns:
    Message: Sent invoice message
    """

def answer_shipping_query(self, shipping_query_id: str, ok: bool, 
                         shipping_options: Optional[List[types.ShippingOption]] = None,
                         error_message: Optional[str] = None) -> bool:
    """
    Reply to shipping queries for flexible invoices.

    Parameters:
    - shipping_query_id (str): Unique identifier for the query
    - ok (bool): True if delivery is possible, False otherwise
    - shipping_options (List[ShippingOption], optional): Available shipping options
    - error_message (str, optional): Error message if ok is False

    Returns:
    bool: True on success
    """

def answer_pre_checkout_query(self, pre_checkout_query_id: str, ok: bool, 
                             error_message: Optional[str] = None) -> bool:
    """
    Respond to pre-checkout queries for final payment confirmation.

    Parameters:
    - pre_checkout_query_id (str): Unique identifier for the query
    - ok (bool): True if ready to proceed, False if problems exist
    - error_message (str, optional): Error message if ok is False

    Returns:
    bool: True on success
    """

Usage Examples

Poll Creation Examples

# Simple poll
bot.send_poll(
    chat_id,
    "What's your favorite color?",
    ["Red", "Blue", "Green", "Yellow"]
)

# Quiz poll with explanation
bot.send_poll(
    chat_id,
    "What is 2+2?",
    ["3", "4", "5"],
    type="quiz",
    correct_option_id=1,
    explanation="Basic arithmetic: 2+2=4"
)

# Anonymous poll with multiple answers
bot.send_poll(
    chat_id,
    "Which programming languages do you know?",
    ["Python", "JavaScript", "Java", "C++", "Go"],
    is_anonymous=True,
    allows_multiple_answers=True
)

Game Integration Example

from telebot import types

@bot.message_handler(commands=['game'])
def send_game(message):
    markup = types.InlineKeyboardMarkup()
    markup.add(types.InlineKeyboardButton("Play Game", callback_game=True))
    
    bot.send_game(
        message.chat.id,
        "my_game_short_name",
        reply_markup=markup
    )

@bot.callback_query_handler(func=lambda call: call.game_short_name)
def handle_game_callback(call):
    # Handle game callback
    bot.answer_callback_query(
        call.id,
        url=f"https://mygame.com/play?user_id={call.from_user.id}"
    )

# Set game score after user plays
def update_game_score(user_id, score):
    bot.set_game_score(user_id, score, force=True)

Dice and Random Elements

@bot.message_handler(commands=['dice'])
def roll_dice(message):
    bot.send_dice(message.chat.id, '🎲')

@bot.message_handler(commands=['darts'])
def throw_darts(message):
    bot.send_dice(message.chat.id, '🎯')

@bot.message_handler(commands=['basketball'])
def shoot_basketball(message):
    bot.send_dice(message.chat.id, '🏀')

Inline Query Example

@bot.inline_handler(lambda query: len(query.query) > 0)
def handle_inline_query(query):
    results = []
    
    # Create inline results based on query
    for i in range(5):
        result = types.InlineQueryResultArticle(
            id=str(i),
            title=f"Result {i}",
            input_message_content=types.InputTextMessageContent(
                f"You searched for: {query.query} - Result {i}"
            )
        )
        results.append(result)
    
    bot.answer_inline_query(query.id, results, cache_time=1)

Venue Sharing Example

@bot.message_handler(commands=['venue'])
def share_venue(message):
    bot.send_venue(
        message.chat.id,
        latitude=40.7589,
        longitude=-73.9851,
        title="Times Square",
        address="Times Square, New York, NY 10036, USA",
        google_place_id="ChIJmQJIxlVYwokRLgeuocVOGVU"
    )

Types

class Poll:
    id: str
    question: str
    options: List[PollOption]
    total_voter_count: int
    is_closed: bool
    is_anonymous: bool
    type: str  # 'quiz' or 'regular'
    allows_multiple_answers: bool
    correct_option_id: Optional[int]
    explanation: Optional[str]
    explanation_entities: Optional[List[MessageEntity]]
    open_period: Optional[int]
    close_date: Optional[int]

class PollOption:
    text: str
    voter_count: int

class Dice:
    emoji: str
    value: int

class Game:
    title: str
    description: str
    photo: List[PhotoSize]
    text: Optional[str]
    text_entities: Optional[List[MessageEntity]]
    animation: Optional[Animation]

class GameHighScore:
    position: int
    user: User
    score: int

class InlineQueryResultArticle:
    type: str = "article"
    id: str
    title: str
    input_message_content: InputMessageContent
    reply_markup: Optional[InlineKeyboardMarkup]
    url: Optional[str]
    hide_url: Optional[bool]
    description: Optional[str]
    thumb_url: Optional[str]
    thumb_width: Optional[int]
    thumb_height: Optional[int]

class Venue:
    location: Location
    title: str
    address: str
    foursquare_id: Optional[str]
    foursquare_type: Optional[str]
    google_place_id: Optional[str]
    google_place_type: Optional[str]

class LabeledPrice:
    label: str  # Portion label
    amount: int  # Price of the product in the smallest units of the currency

class Invoice:
    title: str
    description: str
    start_parameter: str
    currency: str
    total_amount: int

class ShippingAddress:
    country_code: str
    state: str
    city: str
    street_line1: str
    street_line2: str
    post_code: str

class OrderInfo:
    name: Optional[str]
    phone_number: Optional[str]
    email: Optional[str]
    shipping_address: Optional[ShippingAddress]

class ShippingOption:
    id: str
    title: str
    prices: List[LabeledPrice]

class SuccessfulPayment:
    currency: str
    total_amount: int
    invoice_payload: str
    shipping_option_id: Optional[str]
    order_info: Optional[OrderInfo]
    telegram_payment_charge_id: str
    provider_payment_charge_id: str

class ShippingQuery:
    id: str
    from_user: User
    invoice_payload: str
    shipping_address: ShippingAddress

class PreCheckoutQuery:
    id: str
    from_user: User
    currency: str
    total_amount: int
    invoice_payload: str
    shipping_option_id: Optional[str]
    order_info: Optional[OrderInfo]

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