MCPcopy Index your code
hub / github.com/eternnoir/pyTelegramBotAPI

github.com/eternnoir/pyTelegramBotAPI @4.34.0 sqlite

repository ↗ · DeepWiki ↗ · release 4.34.0 ↗
2,991 symbols 7,658 edges 145 files 1,206 documented · 40% 2 cross-repo links
README

PyPi Package Version Supported Python versions Documentation Status PyPi downloads PyPi status

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API.

Both synchronous and asynchronous.

Supported Bot API version: Supported Bot API version

Official documentation

Official ru documentation

Contents

Getting started

This API is tested with Python 3.10-3.14 and PyPy 3. There are two ways to install the library:

  • Installation using pip (a Python package manager):
$ pip install pyTelegramBotAPI
  • Installation from source (requires git):
$ pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git

It is generally recommended to use the first option.

While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling

pip install pytelegrambotapi --upgrade

Writing your first bot

Prerequisites

It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN. Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.

A simple echo bot

The TeleBot class (defined in __init__.py) encapsulates all API calls in a single class. It provides functions such as send_xyz (send_message, send_document etc.) and several ways to listen for incoming messages.

Create a file called echo_bot.py. Then, open the file and create an instance of the TeleBot class.

import telebot

bot = telebot.TeleBot("TOKEN", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN

Note: Make sure to actually replace TOKEN with your own API token.

After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.

Let's define a message handler which handles incoming /start and /help commands.

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")

A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).

Let's add another handler:

@bot.message_handler(func=lambda m: True)
def echo_all(message):
    bot.reply_to(message, message.text)

This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.

Note: all handlers are tested in the order in which they were declared

We now have a basic bot which replies a static message to "/start" and "/help" commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:

bot.infinity_polling()

Alright, that's it! Our source file now looks like this:

import telebot

bot = telebot.TeleBot("YOUR_BOT_TOKEN")

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)

bot.infinity_polling()

To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands ('/start' and '/help') and arbitrary text messages.

General API Documentation

Types

All types are defined in types.py. They are all completely in line with the Telegram API's definition of the types, except for the Message's from field, which is renamed to from_user (because from is a Python reserved token). Thus, attributes such as message_id can be accessed directly with message.message_id. Note that message.chat can be either an instance of User or GroupChat (see How can I distinguish a User and a GroupChat in message.chat?).

The Message object also has a content_typeattribute, which defines the type of the Message. content_type can be one of the following strings: text, audio, document, animation, game, photo, sticker, video, video_note, voice, location, contact, venue, dice, new_chat_members, left_chat_member, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created, supergroup_chat_created, channel_chat_created, migrate_to_chat_id, migrate_from_chat_id, pinned_message, invoice, successful_payment, connected_website, poll, passport_data, proximity_alert_triggered, video_chat_scheduled, video_chat_started, video_chat_ended, video_chat_participants_invited, web_app_data, message_auto_delete_timer_changed, forum_topic_created, forum_topic_closed, forum_topic_reopened, forum_topic_edited, general_forum_topic_hidden, general_forum_topic_unhidden, write_access_allowed, user_shared, chat_shared, story.

You can use some types in one function. Example:

content_types=["text", "sticker", "pinned_message", "photo", "audio"]

Methods

All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. getMe is renamed to get_me and sendMessage to send_message.

General use of the API

Outlined below are some general use cases of the API.

Message handlers

A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):

@bot.message_handler(filters)
def function_name(message):
    bot.reply_to(message, "This is a message handler")

function_name is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle. filters is a list of keyword arguments. A filter is declared in the following manner: name=argument. One handler may have multiple filters. TeleBot supports the following filters:

name argument(s) Condition
content_types list of strings (default ['text']) True if message.content_type is in the list of strings.
regexp a regular expression as a string True if re.search(regexp_arg) returns True and message.content_type == 'text' (See Python Regular Expressions)
commands list of strings True if message.content_type == 'text' and message.text starts with a command that is in the list of strings.
chat_types list of chat types True if message.chat.type in your filter
func a function (lambda or function reference) True if the lambda or function reference returns True

Here are some examples of using the filters and message handlers:

import telebot
bot = telebot.TeleBot("TOKEN")

# Handles all text messages that contains the commands '/start' or '/help'.
@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
    pass

# Handles all sent documents and audio files
@bot.message_handler(content_types=['document', 'audio'])
def handle_docs_audio(message):
    pass

# Handles all text messages that match the regular expression
@bot.message_handler(regexp="SOME_REGEXP")
def handle_message(message):
    pass

# Handles all messages for which the lambda returns True
@bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document'])
def handle_text_doc(message):
    pass

# Which could also be defined as:
def test_message(message):
    return message.document.mime_type == 'text/plain'

@bot.message_handler(func=test_message, content_types=['document'])
def handle_text_doc(message):
    pass

# Handlers can be stacked to create a function which will be called if either message_handler is eligible
# This handler will be called if the message starts with '/hello' OR is some emoji
@bot.message_handler(commands=['hello'])
@bot.message_handler(func=lambda msg: msg.text.encode("utf-8") == SOME_FANCY_EMOJI)
def send_something(message):
    pass

Important: all handlers are tested in the order in which they were declared

Edited Message handler

Handle edited messages @bot.edited_message_handler(filters) # <- passes a Message type object to your function

Channel Post handler

Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function

Edited Channel Post handler

Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function

Callback Query Handler

Handle callback queries

@bot.callback_query_handler(func=lambda call: True)
def test_callback(call): # <- passes a CallbackQuery type object to your function
    logger.info(call)

Shipping Query Handler

Handle shipping queries @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function

Pre Checkout Query Handler

Handle pre checkout queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function

Poll Handler

Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function

Poll Answer Handler

Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function

My Chat Member Handler

Handle updates of a the bot's member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function

Chat Member Handler

Handle updates of a chat member's status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function *Note: "chat_member" updates are not requested by default. If you want to allow al

Core symbols most depended-on inside this repo

de_json
called by 553
telebot/types.py
send_message
called by 181
telebot/__init__.py
check_json
called by 181
telebot/types.py
_make_request
called by 174
telebot/apihelper.py
_process_request
called by 174
telebot/asyncio_helper.py
to_json
called by 98
telebot/types.py
to_dict
called by 96
telebot/types.py
get
called by 92
telebot/states/sync/context.py

Shape

Method 1,743
Function 830
Class 406
Route 12

Languages

Python100%
TypeScript1%

Modules by API surface

telebot/types.py991 symbols
telebot/__init__.py346 symbols
telebot/async_telebot.py324 symbols
telebot/asyncio_helper.py201 symbols
telebot/apihelper.py194 symbols
tests/test_telebot.py82 symbols
telebot/util.py49 symbols
tests/test_types.py39 symbols
telebot/handler_backends.py36 symbols
telebot/custom_filters.py30 symbols
telebot/asyncio_filters.py30 symbols
telebot/formatting.py25 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

Dependencies from manifests, versioned

Flask3.1.3 · 1×
Werkzeug3.1.6 · 1×
aiohttp3.13.4 · 1×
gunicorn23.0.0 · 1×
pyTelegramBotAPI4.11.0 · 1×
requests2.33.0 · 1×
wheel0.46.2 · 1×

For agents

$ claude mcp add pyTelegramBotAPI \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact