0
# pyTelegramBotAPI
1
2
A comprehensive Python library for building Telegram bots using the official Telegram Bot API. The library provides a simple yet extensible TeleBot class that encapsulates all API calls and offers convenient methods for sending messages, handling updates, and managing bot interactions with users and groups.
3
4
## Package Information
5
6
- **Package Name**: pyTelegramBotAPI
7
- **Language**: Python
8
- **Installation**: `pip install pyTelegramBotAPI`
9
10
## Core Imports
11
12
```python
13
import telebot
14
```
15
16
Common patterns:
17
18
```python
19
from telebot import TeleBot
20
from telebot import types
21
```
22
23
For advanced usage:
24
25
```python
26
from telebot import util, apihelper
27
from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend
28
```
29
30
## Basic Usage
31
32
```python
33
import telebot
34
35
# Create bot instance with your token
36
bot = telebot.TeleBot("YOUR_BOT_TOKEN")
37
38
# Handle /start and /help commands
39
@bot.message_handler(commands=['start', 'help'])
40
def send_welcome(message):
41
bot.reply_to(message, "Hello! I'm a bot.")
42
43
# Handle all text messages
44
@bot.message_handler(func=lambda message: True)
45
def echo_all(message):
46
bot.reply_to(message, message.text)
47
48
# Start polling for updates
49
bot.polling()
50
```
51
52
## Architecture
53
54
The library follows a layered architecture:
55
56
- **TeleBot**: Main bot class providing high-level API and handler management
57
- **apihelper**: Low-level functions that interface directly with Telegram Bot API
58
- **types**: Complete set of Telegram API type definitions and serialization
59
- **util**: Utility functions for text processing, threading, and image handling
60
- **handler_backends**: Pluggable storage for next-step and reply handlers
61
62
This design provides both simplicity for basic bots and extensibility for complex applications requiring custom middleware, handler persistence, and asynchronous processing.
63
64
## Capabilities
65
66
### Bot Core Operations
67
68
Primary bot functionality including initialization, authentication, basic information retrieval, and command management. Essential operations every bot needs.
69
70
```python { .api }
71
class TeleBot:
72
def __init__(self, token: str, parse_mode: Optional[str] = None,
73
threaded: bool = True, skip_pending: bool = False,
74
num_threads: int = 2, **kwargs): ...
75
def get_me(self) -> types.User: ...
76
def log_out(self) -> bool: ...
77
def close(self) -> bool: ...
78
def get_my_commands(self, scope: Optional[types.BotCommandScope] = None,
79
language_code: Optional[str] = None) -> List[types.BotCommand]: ...
80
def set_my_commands(self, commands: List[types.BotCommand], **kwargs) -> bool: ...
81
def delete_my_commands(self, scope: Optional[types.BotCommandScope] = None,
82
language_code: Optional[str] = None) -> bool: ...
83
```
84
85
[Bot Core](./bot-core.md)
86
87
### Message Operations
88
89
Comprehensive message handling including sending, forwarding, copying, deleting, and editing messages with support for all message types and formatting options.
90
91
```python { .api }
92
def send_message(self, chat_id: Union[int, str], text: str,
93
parse_mode: Optional[str] = None,
94
reply_markup: Optional[REPLY_MARKUP_TYPES] = None, **kwargs) -> types.Message: ...
95
def forward_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str],
96
message_id: int, **kwargs) -> types.Message: ...
97
def copy_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str],
98
message_id: int, **kwargs) -> int: ...
99
def delete_message(self, chat_id: Union[int, str], message_id: int, **kwargs) -> bool: ...
100
def edit_message_text(self, text: str, chat_id: Optional[Union[int, str]] = None,
101
message_id: Optional[int] = None, **kwargs) -> Union[types.Message, bool]: ...
102
```
103
104
[Message Operations](./message-operations.md)
105
106
### Media Handling
107
108
Sending and managing multimedia content including photos, videos, audio, documents, stickers, animations, media groups, and sticker set management with thumbnail and metadata support.
109
110
```python { .api }
111
def send_photo(self, chat_id: Union[int, str], photo: Union[Any, str],
112
caption: Optional[str] = None, **kwargs) -> types.Message: ...
113
def send_video(self, chat_id: Union[int, str], data: Union[Any, str],
114
duration: Optional[int] = None, **kwargs) -> types.Message: ...
115
def send_audio(self, chat_id: Union[int, str], audio: Union[Any, str],
116
caption: Optional[str] = None, **kwargs) -> types.Message: ...
117
def send_document(self, chat_id: Union[int, str], data: Union[Any, str], **kwargs) -> types.Message: ...
118
def send_media_group(self, chat_id: Union[int, str],
119
media: List[Union[types.InputMediaAudio, types.InputMediaDocument,
120
types.InputMediaPhoto, types.InputMediaVideo]],
121
**kwargs) -> List[types.Message]: ...
122
def create_new_sticker_set(self, user_id: int, name: str, title: str, emojis: str, **kwargs) -> bool: ...
123
def add_sticker_to_set(self, user_id: int, name: str, emojis: str, **kwargs) -> bool: ...
124
def delete_sticker_from_set(self, sticker: str) -> bool: ...
125
def set_sticker_set_thumb(self, name: str, user_id: int, **kwargs) -> bool: ...
126
def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: ...
127
```
128
129
[Media Handling](./media-handling.md)
130
131
### Handler System
132
133
Comprehensive event handling system supporting message handlers, callback query handlers, inline handlers, and various other update types with filtering capabilities.
134
135
```python { .api }
136
def message_handler(self, commands: Optional[List[str]] = None,
137
regexp: Optional[str] = None, func: Optional[Callable] = None,
138
content_types: Optional[List[str]] = None, **kwargs): ...
139
def callback_query_handler(self, func: Callable, **kwargs): ...
140
def inline_handler(self, func: Callable, **kwargs): ...
141
def register_next_step_handler(self, message: types.Message, callback: Callable,
142
*args, **kwargs) -> None: ...
143
def register_for_reply(self, message: types.Message, callback: Callable,
144
*args, **kwargs) -> None: ...
145
```
146
147
[Handler System](./handler-system.md)
148
149
### Update Processing
150
151
Update retrieval and processing including polling modes, webhook support, and update filtering with middleware support.
152
153
```python { .api }
154
def polling(self, non_stop: bool = False, skip_pending: bool = False,
155
interval: int = 0, timeout: int = 20,
156
long_polling_timeout: int = 20,
157
allowed_updates: Optional[List[str]] = None): ...
158
def infinity_polling(self, timeout: int = 20, skip_pending: bool = False,
159
long_polling_timeout: int = 20, **kwargs): ...
160
def set_webhook(self, url: Optional[str] = None, certificate = None,
161
max_connections: Optional[int] = None, **kwargs) -> bool: ...
162
def process_new_updates(self, updates: List[types.Update]): ...
163
```
164
165
[Update Processing](./update-processing.md)
166
167
### Chat Management
168
169
Chat administration capabilities including member management, permissions, invite links, and chat settings modification.
170
171
```python { .api }
172
def get_chat(self, chat_id: Union[int, str]) -> types.Chat: ...
173
def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: ...
174
def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: ...
175
def ban_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
176
def unban_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
177
def restrict_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
178
def promote_chat_member(self, chat_id: Union[int, str], user_id: int, **kwargs) -> bool: ...
179
```
180
181
[Chat Management](./chat-management.md)
182
183
### Interactive Elements
184
185
Interactive features including inline keyboards, custom keyboards, polls, games, payments, invoices, and callback query handling.
186
187
```python { .api }
188
def send_poll(self, chat_id: Union[int, str], question: str, options: List[str],
189
**kwargs) -> types.Message: ...
190
def stop_poll(self, chat_id: Union[int, str], message_id: int, **kwargs) -> types.Poll: ...
191
def send_game(self, chat_id: Union[int, str], game_short_name: str, **kwargs) -> types.Message: ...
192
def answer_callback_query(self, callback_query_id: int, text: Optional[str] = None,
193
**kwargs) -> bool: ...
194
def answer_inline_query(self, inline_query_id: str, results: List[Any], **kwargs) -> bool: ...
195
def send_invoice(self, chat_id: Union[int, str], title: str, description: str,
196
invoice_payload: str, provider_token: str, currency: str,
197
prices: List[types.LabeledPrice], **kwargs) -> types.Message: ...
198
def answer_shipping_query(self, shipping_query_id: str, ok: bool, **kwargs) -> bool: ...
199
def answer_pre_checkout_query(self, pre_checkout_query_id: str, ok: bool, **kwargs) -> bool: ...
200
```
201
202
[Interactive Elements](./interactive-elements.md)
203
204
### Utility Functions
205
206
Text processing, HTML formatting, and convenience functions for common bot development tasks.
207
208
```python { .api }
209
def is_command(text: str) -> bool:
210
"""
211
Check if text is a Telegram command (starts with '/').
212
213
Parameters:
214
- text (str): Text to check
215
216
Returns:
217
bool: True if text is a command
218
"""
219
220
def extract_command(text: str) -> Optional[str]:
221
"""
222
Extract command name from command text (without '/').
223
224
Parameters:
225
- text (str): Command text
226
227
Returns:
228
Optional[str]: Command name or None if not a command
229
"""
230
231
def extract_arguments(text: str) -> str:
232
"""
233
Extract arguments from command text.
234
235
Parameters:
236
- text (str): Command text
237
238
Returns:
239
str: Arguments following the command
240
"""
241
242
def split_string(text: str, chars_per_string: int) -> List[str]:
243
"""
244
Split long text into chunks for message length limits.
245
246
Parameters:
247
- text (str): Text to split
248
- chars_per_string (int): Maximum characters per chunk
249
250
Returns:
251
List[str]: List of text chunks
252
"""
253
254
def smart_split(text: str, chars_per_string: int = 4096) -> List[str]:
255
"""
256
Intelligently split text at natural boundaries (newlines, sentences, words).
257
258
Parameters:
259
- text (str): Text to split
260
- chars_per_string (int): Maximum characters per chunk (default 4096)
261
262
Returns:
263
List[str]: List of text chunks split at natural boundaries
264
"""
265
266
def escape(text: str) -> str:
267
"""
268
Escape HTML special characters (&, <, >) for HTML parse mode.
269
270
Parameters:
271
- text (str): Text to escape
272
273
Returns:
274
str: HTML-escaped text
275
"""
276
277
def user_link(user: types.User, include_id: bool = False) -> str:
278
"""
279
Generate HTML link for user mentions.
280
281
Parameters:
282
- user (User): User object
283
- include_id (bool): Include user ID in link text
284
285
Returns:
286
str: HTML user link
287
"""
288
289
def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int = 2) -> types.InlineKeyboardMarkup:
290
"""
291
Create inline keyboard markup from dictionary format.
292
293
Parameters:
294
- values (Dict[str, Dict[str, Any]]): Button text to kwargs mapping
295
- row_width (int): Buttons per row
296
297
Returns:
298
InlineKeyboardMarkup: Generated keyboard markup
299
"""
300
```
301
302
## Types
303
304
Core type definitions used throughout the API:
305
306
```python { .api }
307
REPLY_MARKUP_TYPES = Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup,
308
types.ReplyKeyboardRemove, types.ForceReply]
309
310
class Update:
311
update_id: int
312
message: Optional[Message]
313
edited_message: Optional[Message]
314
channel_post: Optional[Message]
315
edited_channel_post: Optional[Message]
316
inline_query: Optional[InlineQuery]
317
chosen_inline_result: Optional[ChosenInlineResult]
318
callback_query: Optional[CallbackQuery]
319
# ... additional fields
320
321
class Message:
322
message_id: int
323
from_user: Optional[User]
324
date: int
325
chat: Chat
326
content_type: str
327
text: Optional[str]
328
# ... additional fields based on content type
329
330
class User:
331
id: int
332
is_bot: bool
333
first_name: str
334
last_name: Optional[str]
335
username: Optional[str]
336
language_code: Optional[str]
337
338
class Chat:
339
id: int
340
type: str # 'private', 'group', 'supergroup', 'channel'
341
title: Optional[str]
342
username: Optional[str]
343
first_name: Optional[str]
344
last_name: Optional[str]
345
```