0
# Bot Core Operations
1
2
Primary bot functionality including initialization, authentication, and basic information retrieval. These are the essential operations every bot needs to function.
3
4
## Capabilities
5
6
### Bot Initialization
7
8
Create and configure a bot instance with authentication token and optional settings for threading, parsing, and handler management.
9
10
```python { .api }
11
class TeleBot:
12
def __init__(self, token: str, parse_mode: Optional[str] = None,
13
threaded: bool = True, skip_pending: bool = False,
14
num_threads: int = 2, next_step_backend=None,
15
reply_backend=None, exception_handler=None,
16
last_update_id: int = 0,
17
suppress_middleware_excepions: bool = False):
18
"""
19
Initialize bot instance with API token and configuration.
20
21
Parameters:
22
- token (str): Bot API token from @BotFather
23
- parse_mode (str, optional): Default parse mode ('HTML', 'Markdown', 'MarkdownV2')
24
- threaded (bool): Enable threaded message handling (default: True)
25
- skip_pending (bool): Skip pending updates on startup
26
- num_threads (int): Number of worker threads for message processing
27
- next_step_backend: Backend for storing next step handlers
28
- reply_backend: Backend for storing reply handlers
29
- exception_handler: Custom exception handler instance
30
- last_update_id (int): Last processed update ID
31
- suppress_middleware_excepions (bool): Continue processing if middleware fails
32
"""
33
```
34
35
### Bot Information
36
37
Retrieve basic information about the bot, authenticate with Telegram servers, and manage bot session lifecycle.
38
39
```python { .api }
40
def get_me(self) -> types.User:
41
"""
42
Get basic information about the bot.
43
44
Returns:
45
User: Bot information including ID, username, and capabilities
46
"""
47
48
def log_out(self) -> bool:
49
"""
50
Log out from the cloud Bot API server before running locally.
51
Must be called before switching to local Bot API server.
52
53
Returns:
54
bool: True on success
55
"""
56
57
def close(self) -> bool:
58
"""
59
Close the bot instance before moving to another server.
60
Should delete webhook before calling this method.
61
62
Returns:
63
bool: True on success
64
"""
65
```
66
67
### File Operations
68
69
Handle file downloads, uploads, and URL generation for media content shared through the bot.
70
71
```python { .api }
72
def get_file(self, file_id: str) -> types.File:
73
"""
74
Get basic info about a file and prepare it for downloading.
75
Files up to 20MB can be downloaded.
76
77
Parameters:
78
- file_id (str): File identifier to get info about
79
80
Returns:
81
File: File object with download path and metadata
82
"""
83
84
def get_file_url(self, file_id: str) -> str:
85
"""
86
Get download URL for a file.
87
88
Parameters:
89
- file_id (str): File identifier
90
91
Returns:
92
str: Direct download URL (valid for at least 1 hour)
93
"""
94
95
def download_file(self, file_path: str) -> bytes:
96
"""
97
Download file content from Telegram servers.
98
99
Parameters:
100
- file_path (str): File path from File object
101
102
Returns:
103
bytes: File content as bytes
104
"""
105
```
106
107
### User Profile Information
108
109
Retrieve user profile photos and related user information.
110
111
```python { .api }
112
def get_user_profile_photos(self, user_id: int, offset: Optional[int] = None,
113
limit: Optional[int] = None) -> types.UserProfilePhotos:
114
"""
115
Get user profile photos.
116
117
Parameters:
118
- user_id (int): Target user ID
119
- offset (int, optional): Sequential number of first photo to return
120
- limit (int, optional): Number of photos to return (1-100, default 100)
121
122
Returns:
123
UserProfilePhotos: User's profile photos
124
"""
125
```
126
127
### Bot Command Management
128
129
Manage the list of bot commands shown in the Telegram interface.
130
131
```python { .api }
132
def get_my_commands(self, scope: Optional[types.BotCommandScope] = None,
133
language_code: Optional[str] = None) -> List[types.BotCommand]:
134
"""
135
Get the current list of bot commands for the given scope and user language.
136
137
Parameters:
138
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
139
- language_code (str, optional): Two-letter ISO 639-1 language code
140
141
Returns:
142
List[BotCommand]: List of bot commands
143
"""
144
145
def set_my_commands(self, commands: List[types.BotCommand],
146
scope: Optional[types.BotCommandScope] = None,
147
language_code: Optional[str] = None) -> bool:
148
"""
149
Change the list of bot commands shown in Telegram interface.
150
151
Parameters:
152
- commands (List[BotCommand]): List of bot commands (maximum 100)
153
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
154
- language_code (str, optional): Two-letter ISO 639-1 language code
155
156
Returns:
157
bool: True on success
158
"""
159
160
def delete_my_commands(self, scope: Optional[types.BotCommandScope] = None,
161
language_code: Optional[str] = None) -> bool:
162
"""
163
Delete the list of bot commands for the given scope and user language.
164
After deletion, higher level commands will be shown to affected users.
165
166
Parameters:
167
- scope (BotCommandScope, optional): Scope of users for which commands are relevant
168
- language_code (str, optional): Two-letter ISO 639-1 language code
169
170
Returns:
171
bool: True on success
172
"""
173
```
174
175
### Bot Lifecycle Management
176
177
Control bot execution state and resource cleanup.
178
179
```python { .api }
180
def stop_polling(self):
181
"""
182
Stop the polling process.
183
Sets internal flag to stop polling loop.
184
"""
185
186
def stop_bot(self):
187
"""
188
Stop bot and clean up resources.
189
Stops polling and closes thread pool if threaded mode is enabled.
190
"""
191
```
192
193
## Usage Examples
194
195
### Basic Bot Setup
196
197
```python
198
import telebot
199
200
# Initialize bot with token
201
bot = telebot.TeleBot("YOUR_BOT_TOKEN")
202
203
# Get bot information
204
bot_info = bot.get_me()
205
print(f"Bot name: {bot_info.first_name}")
206
print(f"Bot username: @{bot_info.username}")
207
```
208
209
### Advanced Configuration
210
211
```python
212
import telebot
213
from telebot.handler_backends import FileHandlerBackend
214
215
# Create bot with custom configuration
216
bot = telebot.TeleBot(
217
token="YOUR_BOT_TOKEN",
218
parse_mode='HTML',
219
threaded=True,
220
num_threads=4,
221
skip_pending=True
222
)
223
224
# Enable persistent handler storage
225
bot.next_step_backend = FileHandlerBackend()
226
bot.reply_backend = FileHandlerBackend()
227
```
228
229
### File Download Example
230
231
```python
232
@bot.message_handler(content_types=['document', 'photo'])
233
def handle_files(message):
234
if message.document:
235
file_info = bot.get_file(message.document.file_id)
236
downloaded_file = bot.download_file(file_info.file_path)
237
238
# Save file locally
239
with open(message.document.file_name, 'wb') as f:
240
f.write(downloaded_file)
241
242
bot.reply_to(message, "File downloaded successfully!")
243
```
244
245
## Types
246
247
```python { .api }
248
class User:
249
id: int
250
is_bot: bool
251
first_name: str
252
last_name: Optional[str]
253
username: Optional[str]
254
language_code: Optional[str]
255
can_join_groups: Optional[bool]
256
can_read_all_group_messages: Optional[bool]
257
supports_inline_queries: Optional[bool]
258
259
class File:
260
file_id: str
261
file_unique_id: str
262
file_size: Optional[int]
263
file_path: Optional[str]
264
265
class UserProfilePhotos:
266
total_count: int
267
photos: List[List[PhotoSize]]
268
269
class PhotoSize:
270
file_id: str
271
file_unique_id: str
272
width: int
273
height: int
274
file_size: Optional[int]
275
276
class BotCommand:
277
command: str # Text of the command; 1-32 characters, lowercase letters, digits, underscores only
278
description: str # Description of the command; 1-256 characters
279
280
class BotCommandScope:
281
type: str # Scope type
282
283
class BotCommandScopeDefault(BotCommandScope):
284
type: str = "default" # Represents the default scope of bot commands
285
286
class BotCommandScopeAllPrivateChats(BotCommandScope):
287
type: str = "all_private_chats" # Represents scope of bot commands covering all private chats
288
289
class BotCommandScopeAllGroupChats(BotCommandScope):
290
type: str = "all_group_chats" # Represents scope of bot commands covering all group chats
291
292
class BotCommandScopeAllChatAdministrators(BotCommandScope):
293
type: str = "all_chat_administrators" # Represents scope of bot commands covering all chat administrators
294
295
class BotCommandScopeChat(BotCommandScope):
296
type: str = "chat"
297
chat_id: Union[int, str] # Unique identifier for the target chat
298
299
class BotCommandScopeChatAdministrators(BotCommandScope):
300
type: str = "chat_administrators"
301
chat_id: Union[int, str] # Unique identifier for the target chat
302
303
class BotCommandScopeChatMember(BotCommandScope):
304
type: str = "chat_member"
305
chat_id: Union[int, str] # Unique identifier for the target chat
306
user_id: int # Unique identifier of the target user
307
```