Python Telegram bot API library providing a simple, extensible interface for building Telegram bots with complete Bot API support
—
Primary bot functionality including initialization, authentication, and basic information retrieval. These are the essential operations every bot needs to function.
Create and configure a bot instance with authentication token and optional settings for threading, parsing, and handler management.
class TeleBot:
def __init__(self, token: str, parse_mode: Optional[str] = None,
threaded: bool = True, skip_pending: bool = False,
num_threads: int = 2, next_step_backend=None,
reply_backend=None, exception_handler=None,
last_update_id: int = 0,
suppress_middleware_excepions: bool = False):
"""
Initialize bot instance with API token and configuration.
Parameters:
- token (str): Bot API token from @BotFather
- parse_mode (str, optional): Default parse mode ('HTML', 'Markdown', 'MarkdownV2')
- threaded (bool): Enable threaded message handling (default: True)
- skip_pending (bool): Skip pending updates on startup
- num_threads (int): Number of worker threads for message processing
- next_step_backend: Backend for storing next step handlers
- reply_backend: Backend for storing reply handlers
- exception_handler: Custom exception handler instance
- last_update_id (int): Last processed update ID
- suppress_middleware_excepions (bool): Continue processing if middleware fails
"""Retrieve basic information about the bot, authenticate with Telegram servers, and manage bot session lifecycle.
def get_me(self) -> types.User:
"""
Get basic information about the bot.
Returns:
User: Bot information including ID, username, and capabilities
"""
def log_out(self) -> bool:
"""
Log out from the cloud Bot API server before running locally.
Must be called before switching to local Bot API server.
Returns:
bool: True on success
"""
def close(self) -> bool:
"""
Close the bot instance before moving to another server.
Should delete webhook before calling this method.
Returns:
bool: True on success
"""Handle file downloads, uploads, and URL generation for media content shared through the bot.
def get_file(self, file_id: str) -> types.File:
"""
Get basic info about a file and prepare it for downloading.
Files up to 20MB can be downloaded.
Parameters:
- file_id (str): File identifier to get info about
Returns:
File: File object with download path and metadata
"""
def get_file_url(self, file_id: str) -> str:
"""
Get download URL for a file.
Parameters:
- file_id (str): File identifier
Returns:
str: Direct download URL (valid for at least 1 hour)
"""
def download_file(self, file_path: str) -> bytes:
"""
Download file content from Telegram servers.
Parameters:
- file_path (str): File path from File object
Returns:
bytes: File content as bytes
"""Retrieve user profile photos and related user information.
def get_user_profile_photos(self, user_id: int, offset: Optional[int] = None,
limit: Optional[int] = None) -> types.UserProfilePhotos:
"""
Get user profile photos.
Parameters:
- user_id (int): Target user ID
- offset (int, optional): Sequential number of first photo to return
- limit (int, optional): Number of photos to return (1-100, default 100)
Returns:
UserProfilePhotos: User's profile photos
"""Manage the list of bot commands shown in the Telegram interface.
def get_my_commands(self, scope: Optional[types.BotCommandScope] = None,
language_code: Optional[str] = None) -> List[types.BotCommand]:
"""
Get the current list of bot commands for the given scope and user language.
Parameters:
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
- language_code (str, optional): Two-letter ISO 639-1 language code
Returns:
List[BotCommand]: List of bot commands
"""
def set_my_commands(self, commands: List[types.BotCommand],
scope: Optional[types.BotCommandScope] = None,
language_code: Optional[str] = None) -> bool:
"""
Change the list of bot commands shown in Telegram interface.
Parameters:
- commands (List[BotCommand]): List of bot commands (maximum 100)
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
- language_code (str, optional): Two-letter ISO 639-1 language code
Returns:
bool: True on success
"""
def delete_my_commands(self, scope: Optional[types.BotCommandScope] = None,
language_code: Optional[str] = None) -> bool:
"""
Delete the list of bot commands for the given scope and user language.
After deletion, higher level commands will be shown to affected users.
Parameters:
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
- language_code (str, optional): Two-letter ISO 639-1 language code
Returns:
bool: True on success
"""Control bot execution state and resource cleanup.
def stop_polling(self):
"""
Stop the polling process.
Sets internal flag to stop polling loop.
"""
def stop_bot(self):
"""
Stop bot and clean up resources.
Stops polling and closes thread pool if threaded mode is enabled.
"""import telebot
# Initialize bot with token
bot = telebot.TeleBot("YOUR_BOT_TOKEN")
# Get bot information
bot_info = bot.get_me()
print(f"Bot name: {bot_info.first_name}")
print(f"Bot username: @{bot_info.username}")import telebot
from telebot.handler_backends import FileHandlerBackend
# Create bot with custom configuration
bot = telebot.TeleBot(
token="YOUR_BOT_TOKEN",
parse_mode='HTML',
threaded=True,
num_threads=4,
skip_pending=True
)
# Enable persistent handler storage
bot.next_step_backend = FileHandlerBackend()
bot.reply_backend = FileHandlerBackend()@bot.message_handler(content_types=['document', 'photo'])
def handle_files(message):
if message.document:
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
# Save file locally
with open(message.document.file_name, 'wb') as f:
f.write(downloaded_file)
bot.reply_to(message, "File downloaded successfully!")class User:
id: int
is_bot: bool
first_name: str
last_name: Optional[str]
username: Optional[str]
language_code: Optional[str]
can_join_groups: Optional[bool]
can_read_all_group_messages: Optional[bool]
supports_inline_queries: Optional[bool]
class File:
file_id: str
file_unique_id: str
file_size: Optional[int]
file_path: Optional[str]
class UserProfilePhotos:
total_count: int
photos: List[List[PhotoSize]]
class PhotoSize:
file_id: str
file_unique_id: str
width: int
height: int
file_size: Optional[int]
class BotCommand:
command: str # Text of the command; 1-32 characters, lowercase letters, digits, underscores only
description: str # Description of the command; 1-256 characters
class BotCommandScope:
type: str # Scope type
class BotCommandScopeDefault(BotCommandScope):
type: str = "default" # Represents the default scope of bot commands
class BotCommandScopeAllPrivateChats(BotCommandScope):
type: str = "all_private_chats" # Represents scope of bot commands covering all private chats
class BotCommandScopeAllGroupChats(BotCommandScope):
type: str = "all_group_chats" # Represents scope of bot commands covering all group chats
class BotCommandScopeAllChatAdministrators(BotCommandScope):
type: str = "all_chat_administrators" # Represents scope of bot commands covering all chat administrators
class BotCommandScopeChat(BotCommandScope):
type: str = "chat"
chat_id: Union[int, str] # Unique identifier for the target chat
class BotCommandScopeChatAdministrators(BotCommandScope):
type: str = "chat_administrators"
chat_id: Union[int, str] # Unique identifier for the target chat
class BotCommandScopeChatMember(BotCommandScope):
type: str = "chat_member"
chat_id: Union[int, str] # Unique identifier for the target chat
user_id: int # Unique identifier of the target userInstall with Tessl CLI
npx tessl i tessl/pypi-py-telegram-bot-api