pyTelegramBotAPI
pyTelegramBotAPI is a straightforward yet comprehensive Python library providing both synchronous and asynchronous implementations of the Telegram Bot API. It enables developers to easily create Telegram bots with features like message handling, inline queries, and custom keyboards. The library is actively maintained, with frequent updates (often monthly or bi-monthly) to support the latest Telegram Bot API versions, and the current version is 4.33.0.
Warnings
- breaking Major changes in the official Telegram Bot API, while often accommodated by library updates, can sometimes introduce breaking changes requiring code migration. Always review the `pyTelegramBotAPI` changelog and Telegram Bot API release notes when upgrading, especially across significant version bumps.
- deprecated The `reply_to_message_id`, `allow_sending_without_reply`, and `disable_web_page_preview` parameters in `bot.send_message()` and similar methods have been deprecated by Telegram. While they might still function, it's recommended to use newer alternatives for reply parameters and link previews.
- gotcha The library offers both synchronous (`telebot.TeleBot`) and asynchronous (`telebot.async_telebot.AsyncTeleBot`) implementations. Mixing them incorrectly or using `TeleBot` with long-running operations in handlers without threading can block your bot. `TeleBot`'s `infinity_polling()` is synchronous, while `AsyncTeleBot` typically uses `asyncio.run(bot.polling())`.
- gotcha The `Message` object received by handlers has its `from` attribute renamed to `from_user` (`message.from_user`) to avoid conflict with Python's `from` keyword. Directly accessing `message.from` will raise an `AttributeError`.
Install
-
pip install pyTelegramBotAPI
Imports
- TeleBot
import telebot bot = telebot.TeleBot(TOKEN)
- AsyncTeleBot
from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot(TOKEN)
- types
from telebot import types
Quickstart
import os
import telebot
API_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE')
if not API_TOKEN or API_TOKEN == 'YOUR_BOT_TOKEN_HERE':
print("Warning: TELEGRAM_BOT_TOKEN environment variable not set or placeholder used. \n"\
"Please obtain a token from @BotFather on Telegram and set it.")
exit(1)
bot = telebot.TeleBot(API_TOKEN)
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Hi there, I am an EchoBot. I will echo your messages.")
@bot.message_handler(func=lambda message: True)
def echo_message(message):
bot.reply_to(message, message.text)
print("Bot started polling...")
bot.infinity_polling()