0
# Interactive Elements
1
2
Interactive features including inline keyboards, custom keyboards, polls, games, and callback query handling.
3
4
## Capabilities
5
6
### Polls and Voting
7
8
Create, send, and manage polls with various question types and voting options.
9
10
```python { .api }
11
def send_poll(self, chat_id: Union[int, str], question: str, options: List[str],
12
is_anonymous: Optional[bool] = None, type: Optional[str] = None,
13
allows_multiple_answers: Optional[bool] = None,
14
correct_option_id: Optional[int] = None,
15
explanation: Optional[str] = None,
16
explanation_parse_mode: Optional[str] = None,
17
open_period: Optional[int] = None,
18
close_date: Optional[Union[int, datetime]] = None,
19
is_closed: Optional[bool] = None,
20
disable_notification: Optional[bool] = False,
21
reply_to_message_id: Optional[int] = None,
22
reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
23
allow_sending_without_reply: Optional[bool] = None,
24
timeout: Optional[int] = None,
25
explanation_entities: Optional[List[types.MessageEntity]] = None) -> types.Message:
26
"""
27
Send polls with customizable voting options and behavior.
28
29
Parameters:
30
- chat_id (Union[int, str]): Target chat
31
- question (str): Poll question (1-300 characters)
32
- options (List[str]): List of answer options (2-10 options, 1-100 characters each)
33
- is_anonymous (bool, optional): True for anonymous polls
34
- type (str, optional): Poll type ('quiz' or 'regular')
35
- allows_multiple_answers (bool, optional): Allow multiple answers (regular polls only)
36
- correct_option_id (int, optional): Correct answer ID (quiz polls only)
37
- explanation (str, optional): Explanation for quiz answer (0-200 characters)
38
- explanation_parse_mode (str, optional): Explanation parsing mode
39
- open_period (int, optional): Auto-close period in seconds (5-600)
40
- close_date (Union[int, datetime], optional): Point when poll closes
41
- is_closed (bool, optional): Send closed poll
42
- disable_notification (bool, optional): Send silently
43
- reply_to_message_id (int, optional): Message to reply to
44
- reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
45
- allow_sending_without_reply (bool, optional): Send if reply target missing
46
- timeout (int, optional): Request timeout
47
- explanation_entities (List[MessageEntity], optional): Explanation entities
48
49
Returns:
50
Message: Sent poll message
51
"""
52
53
def stop_poll(self, chat_id: Union[int, str], message_id: int,
54
reply_markup: Optional[REPLY_MARKUP_TYPES] = None) -> types.Poll:
55
"""
56
Stop a poll which was sent by the bot.
57
58
Parameters:
59
- chat_id (Union[int, str]): Chat where poll was sent
60
- message_id (int): Poll message ID
61
- reply_markup (REPLY_MARKUP_TYPES, optional): New inline keyboard
62
63
Returns:
64
Poll: Stopped poll with final results
65
"""
66
```
67
68
### Games
69
70
Send and manage games with score tracking and leaderboards.
71
72
```python { .api }
73
def send_game(self, chat_id: Union[int, str], game_short_name: str,
74
disable_notification: Optional[bool] = None,
75
reply_to_message_id: Optional[int] = None,
76
reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
77
timeout: Optional[int] = None,
78
allow_sending_without_reply: Optional[bool] = None) -> types.Message:
79
"""
80
Send a game message.
81
82
Parameters:
83
- chat_id (Union[int, str]): Target chat
84
- game_short_name (str): Short name of the game
85
- disable_notification (bool, optional): Send silently
86
- reply_to_message_id (int, optional): Message to reply to
87
- reply_markup (REPLY_MARKUP_TYPES, optional): Inline keyboard
88
- timeout (int, optional): Request timeout
89
- allow_sending_without_reply (bool, optional): Send if reply target missing
90
91
Returns:
92
Message: Sent game message
93
"""
94
95
def set_game_score(self, user_id: Union[int, str], score: int,
96
force: Optional[bool] = None,
97
chat_id: Optional[Union[int, str]] = None,
98
message_id: Optional[int] = None,
99
inline_message_id: Optional[str] = None,
100
disable_edit_message: Optional[bool] = None) -> Union[types.Message, bool]:
101
"""
102
Set the score of the specified user in a game.
103
104
Parameters:
105
- user_id (Union[int, str]): User identifier
106
- score (int): New score (must be non-negative)
107
- force (bool, optional): Pass True to set score even if it's lower
108
- chat_id (Union[int, str], optional): Chat where game was sent
109
- message_id (int, optional): Game message ID
110
- inline_message_id (str, optional): Inline message ID
111
- disable_edit_message (bool, optional): Don't edit the game message
112
113
Returns:
114
Union[Message, bool]: Edited message or True for inline messages
115
"""
116
117
def get_game_high_scores(self, user_id: int, chat_id: Optional[Union[int, str]] = None,
118
message_id: Optional[int] = None,
119
inline_message_id: Optional[str] = None) -> List[types.GameHighScore]:
120
"""
121
Get data for high score tables of a game.
122
123
Parameters:
124
- user_id (int): Target user ID
125
- chat_id (Union[int, str], optional): Chat where game was sent
126
- message_id (int, optional): Game message ID
127
- inline_message_id (str, optional): Inline message ID
128
129
Returns:
130
List[GameHighScore]: Game high scores
131
"""
132
```
133
134
### Dice and Random Elements
135
136
Send animated dice and other random elements.
137
138
```python { .api }
139
def send_dice(self, chat_id: Union[int, str], emoji: Optional[str] = None,
140
disable_notification: Optional[bool] = None,
141
reply_to_message_id: Optional[int] = None,
142
reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
143
timeout: Optional[int] = None,
144
allow_sending_without_reply: Optional[bool] = None) -> types.Message:
145
"""
146
Send animated dice or other random value generators.
147
148
Parameters:
149
- chat_id (Union[int, str]): Target chat
150
- emoji (str, optional): Emoji type ('π²', 'π―', 'π', 'β½', 'π³', 'π°')
151
- disable_notification (bool, optional): Send silently
152
- reply_to_message_id (int, optional): Message to reply to
153
- reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
154
- timeout (int, optional): Request timeout
155
- allow_sending_without_reply (bool, optional): Send if reply target missing
156
157
Returns:
158
Message: Sent dice message with animation
159
"""
160
```
161
162
### Inline Query Handling
163
164
Handle and respond to inline queries for inline bot functionality.
165
166
```python { .api }
167
def answer_inline_query(self, inline_query_id: str, results: List[Any],
168
cache_time: Optional[int] = None,
169
is_personal: Optional[bool] = None,
170
next_offset: Optional[str] = None,
171
switch_pm_text: Optional[str] = None,
172
switch_pm_parameter: Optional[str] = None) -> bool:
173
"""
174
Send answers to an inline query.
175
176
Parameters:
177
- inline_query_id (str): Unique identifier for the query
178
- results (List[Any]): Array of results for the inline query (max 50)
179
- cache_time (int, optional): Cache time for results on server (default 300)
180
- is_personal (bool, optional): Cache results on server for user only
181
- next_offset (str, optional): Offset for next query with same text
182
- switch_pm_text (str, optional): Button text to switch to private chat
183
- switch_pm_parameter (str, optional): Parameter for the start message
184
185
Returns:
186
bool: True on success
187
"""
188
```
189
190
### Venue and Location Sharing
191
192
Send venue information and location data.
193
194
```python { .api }
195
def send_venue(self, chat_id: Union[int, str], latitude: float, longitude: float,
196
title: str, address: str, foursquare_id: Optional[str] = None,
197
foursquare_type: Optional[str] = None,
198
disable_notification: Optional[bool] = None,
199
reply_to_message_id: Optional[int] = None,
200
reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
201
timeout: Optional[int] = None,
202
allow_sending_without_reply: Optional[bool] = None,
203
google_place_id: Optional[str] = None,
204
google_place_type: Optional[str] = None) -> types.Message:
205
"""
206
Send information about a venue.
207
208
Parameters:
209
- chat_id (Union[int, str]): Target chat
210
- latitude (float): Venue latitude
211
- longitude (float): Venue longitude
212
- title (str): Venue name
213
- address (str): Venue address
214
- foursquare_id (str, optional): Foursquare identifier
215
- foursquare_type (str, optional): Foursquare type
216
- disable_notification (bool, optional): Send silently
217
- reply_to_message_id (int, optional): Message to reply to
218
- reply_markup (REPLY_MARKUP_TYPES, optional): Keyboard markup
219
- timeout (int, optional): Request timeout
220
- allow_sending_without_reply (bool, optional): Send if reply target missing
221
- google_place_id (str, optional): Google Places identifier
222
- google_place_type (str, optional): Google Places type
223
224
Returns:
225
Message: Sent venue message
226
"""
227
```
228
229
### Payments and Invoices
230
231
Send invoices, process payments, and handle shipping queries for e-commerce functionality.
232
233
```python { .api }
234
def send_invoice(self, chat_id: Union[int, str], title: str, description: str,
235
invoice_payload: str, provider_token: str, currency: str,
236
prices: List[types.LabeledPrice],
237
start_parameter: Optional[str] = None,
238
photo_url: Optional[str] = None,
239
photo_size: Optional[int] = None,
240
photo_width: Optional[int] = None,
241
photo_height: Optional[int] = None,
242
need_name: Optional[bool] = None,
243
need_phone_number: Optional[bool] = None,
244
need_email: Optional[bool] = None,
245
need_shipping_address: Optional[bool] = None,
246
send_phone_number_to_provider: Optional[bool] = None,
247
send_email_to_provider: Optional[bool] = None,
248
is_flexible: Optional[bool] = None,
249
disable_notification: Optional[bool] = None,
250
reply_to_message_id: Optional[int] = None,
251
reply_markup: Optional[REPLY_MARKUP_TYPES] = None,
252
provider_data: Optional[str] = None,
253
timeout: Optional[int] = None,
254
allow_sending_without_reply: Optional[bool] = None,
255
max_tip_amount: Optional[int] = None,
256
suggested_tip_amounts: Optional[List[int]] = None) -> types.Message:
257
"""
258
Send invoices for payment processing.
259
260
Parameters:
261
- chat_id (Union[int, str]): Target chat (must be private)
262
- title (str): Product name (1-32 characters)
263
- description (str): Product description (1-255 characters)
264
- invoice_payload (str): Bot-defined invoice payload (1-128 bytes)
265
- provider_token (str): Payment provider token from @BotFather
266
- currency (str): Three-letter ISO 4217 currency code
267
- prices (List[LabeledPrice]): Breakdown of prices
268
- start_parameter (str, optional): Deep-linking parameter
269
- photo_url (str, optional): Product photo URL
270
- photo_size (int, optional): Photo size in bytes
271
- photo_width (int, optional): Photo width
272
- photo_height (int, optional): Photo height
273
- need_name (bool, optional): Require user's full name
274
- need_phone_number (bool, optional): Require user's phone number
275
- need_email (bool, optional): Require user's email address
276
- need_shipping_address (bool, optional): Require user's shipping address
277
- send_phone_number_to_provider (bool, optional): Pass phone to provider
278
- send_email_to_provider (bool, optional): Pass email to provider
279
- is_flexible (bool, optional): Price depends on shipping method
280
- disable_notification (bool, optional): Send silently
281
- reply_to_message_id (int, optional): Message to reply to
282
- reply_markup (REPLY_MARKUP_TYPES, optional): Inline keyboard markup
283
- provider_data (str, optional): JSON data for payment provider
284
- timeout (int, optional): Request timeout
285
- allow_sending_without_reply (bool, optional): Send if reply target missing
286
- max_tip_amount (int, optional): Maximum accepted tip amount
287
- suggested_tip_amounts (List[int], optional): Suggested tip amounts
288
289
Returns:
290
Message: Sent invoice message
291
"""
292
293
def answer_shipping_query(self, shipping_query_id: str, ok: bool,
294
shipping_options: Optional[List[types.ShippingOption]] = None,
295
error_message: Optional[str] = None) -> bool:
296
"""
297
Reply to shipping queries for flexible invoices.
298
299
Parameters:
300
- shipping_query_id (str): Unique identifier for the query
301
- ok (bool): True if delivery is possible, False otherwise
302
- shipping_options (List[ShippingOption], optional): Available shipping options
303
- error_message (str, optional): Error message if ok is False
304
305
Returns:
306
bool: True on success
307
"""
308
309
def answer_pre_checkout_query(self, pre_checkout_query_id: str, ok: bool,
310
error_message: Optional[str] = None) -> bool:
311
"""
312
Respond to pre-checkout queries for final payment confirmation.
313
314
Parameters:
315
- pre_checkout_query_id (str): Unique identifier for the query
316
- ok (bool): True if ready to proceed, False if problems exist
317
- error_message (str, optional): Error message if ok is False
318
319
Returns:
320
bool: True on success
321
"""
322
```
323
324
## Usage Examples
325
326
### Poll Creation Examples
327
328
```python
329
# Simple poll
330
bot.send_poll(
331
chat_id,
332
"What's your favorite color?",
333
["Red", "Blue", "Green", "Yellow"]
334
)
335
336
# Quiz poll with explanation
337
bot.send_poll(
338
chat_id,
339
"What is 2+2?",
340
["3", "4", "5"],
341
type="quiz",
342
correct_option_id=1,
343
explanation="Basic arithmetic: 2+2=4"
344
)
345
346
# Anonymous poll with multiple answers
347
bot.send_poll(
348
chat_id,
349
"Which programming languages do you know?",
350
["Python", "JavaScript", "Java", "C++", "Go"],
351
is_anonymous=True,
352
allows_multiple_answers=True
353
)
354
```
355
356
### Game Integration Example
357
358
```python
359
from telebot import types
360
361
@bot.message_handler(commands=['game'])
362
def send_game(message):
363
markup = types.InlineKeyboardMarkup()
364
markup.add(types.InlineKeyboardButton("Play Game", callback_game=True))
365
366
bot.send_game(
367
message.chat.id,
368
"my_game_short_name",
369
reply_markup=markup
370
)
371
372
@bot.callback_query_handler(func=lambda call: call.game_short_name)
373
def handle_game_callback(call):
374
# Handle game callback
375
bot.answer_callback_query(
376
call.id,
377
url=f"https://mygame.com/play?user_id={call.from_user.id}"
378
)
379
380
# Set game score after user plays
381
def update_game_score(user_id, score):
382
bot.set_game_score(user_id, score, force=True)
383
```
384
385
### Dice and Random Elements
386
387
```python
388
@bot.message_handler(commands=['dice'])
389
def roll_dice(message):
390
bot.send_dice(message.chat.id, 'π²')
391
392
@bot.message_handler(commands=['darts'])
393
def throw_darts(message):
394
bot.send_dice(message.chat.id, 'π―')
395
396
@bot.message_handler(commands=['basketball'])
397
def shoot_basketball(message):
398
bot.send_dice(message.chat.id, 'π')
399
```
400
401
### Inline Query Example
402
403
```python
404
@bot.inline_handler(lambda query: len(query.query) > 0)
405
def handle_inline_query(query):
406
results = []
407
408
# Create inline results based on query
409
for i in range(5):
410
result = types.InlineQueryResultArticle(
411
id=str(i),
412
title=f"Result {i}",
413
input_message_content=types.InputTextMessageContent(
414
f"You searched for: {query.query} - Result {i}"
415
)
416
)
417
results.append(result)
418
419
bot.answer_inline_query(query.id, results, cache_time=1)
420
```
421
422
### Venue Sharing Example
423
424
```python
425
@bot.message_handler(commands=['venue'])
426
def share_venue(message):
427
bot.send_venue(
428
message.chat.id,
429
latitude=40.7589,
430
longitude=-73.9851,
431
title="Times Square",
432
address="Times Square, New York, NY 10036, USA",
433
google_place_id="ChIJmQJIxlVYwokRLgeuocVOGVU"
434
)
435
```
436
437
## Types
438
439
```python { .api }
440
class Poll:
441
id: str
442
question: str
443
options: List[PollOption]
444
total_voter_count: int
445
is_closed: bool
446
is_anonymous: bool
447
type: str # 'quiz' or 'regular'
448
allows_multiple_answers: bool
449
correct_option_id: Optional[int]
450
explanation: Optional[str]
451
explanation_entities: Optional[List[MessageEntity]]
452
open_period: Optional[int]
453
close_date: Optional[int]
454
455
class PollOption:
456
text: str
457
voter_count: int
458
459
class Dice:
460
emoji: str
461
value: int
462
463
class Game:
464
title: str
465
description: str
466
photo: List[PhotoSize]
467
text: Optional[str]
468
text_entities: Optional[List[MessageEntity]]
469
animation: Optional[Animation]
470
471
class GameHighScore:
472
position: int
473
user: User
474
score: int
475
476
class InlineQueryResultArticle:
477
type: str = "article"
478
id: str
479
title: str
480
input_message_content: InputMessageContent
481
reply_markup: Optional[InlineKeyboardMarkup]
482
url: Optional[str]
483
hide_url: Optional[bool]
484
description: Optional[str]
485
thumb_url: Optional[str]
486
thumb_width: Optional[int]
487
thumb_height: Optional[int]
488
489
class Venue:
490
location: Location
491
title: str
492
address: str
493
foursquare_id: Optional[str]
494
foursquare_type: Optional[str]
495
google_place_id: Optional[str]
496
google_place_type: Optional[str]
497
498
class LabeledPrice:
499
label: str # Portion label
500
amount: int # Price of the product in the smallest units of the currency
501
502
class Invoice:
503
title: str
504
description: str
505
start_parameter: str
506
currency: str
507
total_amount: int
508
509
class ShippingAddress:
510
country_code: str
511
state: str
512
city: str
513
street_line1: str
514
street_line2: str
515
post_code: str
516
517
class OrderInfo:
518
name: Optional[str]
519
phone_number: Optional[str]
520
email: Optional[str]
521
shipping_address: Optional[ShippingAddress]
522
523
class ShippingOption:
524
id: str
525
title: str
526
prices: List[LabeledPrice]
527
528
class SuccessfulPayment:
529
currency: str
530
total_amount: int
531
invoice_payload: str
532
shipping_option_id: Optional[str]
533
order_info: Optional[OrderInfo]
534
telegram_payment_charge_id: str
535
provider_payment_charge_id: str
536
537
class ShippingQuery:
538
id: str
539
from_user: User
540
invoice_payload: str
541
shipping_address: ShippingAddress
542
543
class PreCheckoutQuery:
544
id: str
545
from_user: User
546
currency: str
547
total_amount: int
548
invoice_payload: str
549
shipping_option_id: Optional[str]
550
order_info: Optional[OrderInfo]
551
```