This page is generated from the following source files:
Before starting with pyTelegramBotAPI, ensure the following requirements are met:
Python Version Compatibility: The library is tested with Python 3.9-3.13 and Pypy 3 (README.md:72-72). Earlier Python versions are not supported.
Telegram Bot Token: Obtain an API token from @BotFather on Telegram. This token is required for authenticating bot requests with the Telegram Bot API (README.md:97-97). The token should be stored securely and never committed to version control.
Knowledge Requirements: Basic understanding of Python programming and familiarity with the Telegram Bot API concepts are presumed (README.md:98-98).
Token Configuration Example: In example code, the token is typically stored in a variable before initializing the bot instance:
python1API_TOKEN = '<api_token>' 2bot = telebot.TeleBot(API_TOKEN)
pyTelegramBotAPI offers multiple installation methods to suit different development environments.
The simplest and recommended method uses pip, the Python package manager:
bash1pip install pyTelegramBotAPI
For development or accessing the latest unreleased features, install directly from the GitHub repository:
bash1pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git
The library receives regular updates. To ensure access to the latest features and bug fixes, update periodically:
bash1pip install pytelegrambotapi --upgrade
The library relies on the following core dependencies for network operations:
requests==2.32.4 - HTTP library for synchronous API callsaiohttp==3.13.3 - Async HTTP client for AsyncTeleBot functionalitypytest - Testing frameworkwheel==0.46.2 - Package distribution formatThe TeleBot class serves as the primary interface for interacting with the Telegram Bot API, encapsulating all API calls within a single class instance.
Create a TeleBot instance by passing the API token obtained from BotFather:
python1import telebot 2 3bot = telebot.TeleBot("TOKEN")
The TeleBot constructor accepts additional parameters for customization. The parse_mode parameter allows setting a default parsing mode for message formatting:
python1bot = telebot.TeleBot("TOKEN", parse_mode=None) # Options: HTML, MARKDOWN, or None
The TeleBot class provides methods such as send_xyz (including send_message, send_document, etc.) and multiple ways to listen for incoming messages (README.md:102-102).
Message handlers define the logic for processing incoming messages. They use Python decorators to associate filter conditions with handler functions.
A message handler is a function decorated with @bot.message_handler() that processes messages matching specified filters. Each filter must return True for a message to be handled by that function (README.md:177-178).
Handle specific commands using the commands filter:
python1@bot.message_handler(commands=['help', 'start']) 2def send_welcome(message): 3 bot.reply_to(message, """\ 4Hi there, I am EchoBot. 5I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\ 6""")
This handler responds to both /start and /help commands with a welcome message.
Use lambda functions for custom filtering logic. The following handler catches all text messages by returning True for every message:
python1@bot.message_handler(func=lambda message: True) 2def echo_message(message): 3 bot.reply_to(message, message.text)
Handlers are tested in the order they were declared (README.md:131-131). The first handler whose filters all return True will process the message.
| Filter | Argument Type | Condition |
|---|---|---|
content_types | List of strings (default: ['text']) | Matches if message.content_type is in the list |
regexp | Regular expression string | Matches if pattern found in text content |
commands | List of strings | Matches if message starts with specified command |
chat_types | List of chat types | Matches if message.chat.type matches |
func | Lambda or function reference | Matches if function returns True |
After registering handlers, start the bot to begin processing incoming messages.
The infinity_polling() method starts a long-polling loop that continuously checks for new updates:
python1bot.infinity_polling()
This method blocks execution and handles reconnection automatically, making it suitable for production deployments (README.md:135-136).
A minimal working echo bot combines all elements:
python1import telebot 2 3bot = telebot.TeleBot("YOUR_BOT_TOKEN") 4 5@bot.message_handler(commands=['start', 'help']) 6def send_welcome(message): 7 bot.reply_to(message, "Howdy, how are you doing?") 8 9@bot.message_handler(func=lambda message: True) 10def echo_all(message): 11 bot.reply_to(message, message.text) 12 13bot.infinity_polling()
Execute the bot script from a terminal:
bash1python echo_bot.py
Test the bot by sending /start, /help commands, and arbitrary text messages to verify the echo functionality.
For applications requiring asynchronous operations, pyTelegramBotAPI provides AsyncTeleBot with native async/await support.
Import and initialize the async bot using the AsyncTeleBot class:
python1import asyncio 2from telebot.async_telebot import AsyncTeleBot 3 4bot = AsyncTeleBot('TOKEN')
(examples/asynchronous_telebot/echo_bot.py:5-9)
Handler functions must be defined as async and use await when calling bot methods:
python1@bot.message_handler(commands=['help', 'start']) 2async def send_welcome(message): 3 text = 'Hi, I am EchoBot.\nJust write me something and I will repeat it!' 4 await bot.reply_to(message, text)
(examples/asynchronous_telebot/echo_bot.py:12-16)
The echo handler follows the same pattern with async/await syntax:
python1@bot.message_handler(func=lambda message: True) 2async def echo_message(message): 3 await bot.reply_to(message, message.text)
(examples/asynchronous_telebot/echo_bot.py:20-22)
Use asyncio.run() to start the async polling loop:
python1asyncio.run(bot.polling())
(examples/asynchronous_telebot/echo_bot.py:25-25)
After starting a bot with python echo_bot.py, verify successful operation by observing the following indicators:
/start or /help should trigger the welcome messageFor AsyncTeleBot instances, ensure:
asyncio.run() call executes without errorsasync/await syntax(examples/asynchronous_telebot/echo_bot.py:25-25)
| Issue | Possible Cause | Solution |
|---|---|---|
| No response to commands | Invalid token | Verify token from BotFather |
| Connection errors | Network/firewall | Check internet connectivity |
| Handler not triggered | Filter mismatch | Review handler filter conditions |
| Import errors | Library not installed | Run pip install pyTelegramBotAPI |
Symptoms: Authentication errors, 401 Unauthorized responses, bot fails to start.
Cause: The API token is incorrect, expired, or not properly configured in the code.
Solution:
Symptoms: Bot starts successfully but does not respond to messages or commands.
Cause: Handler filters may not match incoming messages, or handlers are registered after infinity_polling() is called.
Solution:
infinity_polling()Symptoms: Recurring ConnectionResetError exceptions during long-running bot operations.
Cause: Network instability or Telegram API server connection issues.
Solution: The infinity_polling() method handles reconnection automatically. For custom implementations, implement retry logic with exponential backoff (common practice, not explicitly documented in provided sources).
Symptoms: TypeError or coroutine warnings when using AsyncTeleBot.
Cause: Missing async keyword on handler functions or missing await on bot method calls.
Solution:
async defawait before all bot method callsasyncio.run(bot.polling())(examples/asynchronous_telebot/echo_bot.py:12-22)
Symptoms: Import errors or syntax errors related to type hints or async features.
Cause: Using an unsupported Python version.
Solution: Ensure Python 3.9 or higher is installed. Check version with python --version.
After completing the quick start guide, explore these advanced topics: