· 6 years ago · Apr 09, 2020, 11:30 AM
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
4#
5# A library that provides a Python interface to the Telegram Bot API
6# Copyright (C) 2015-2020
7# Leandro Toledo de Souza <devs@python-telegram-bot.org>
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU Lesser Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU Lesser Public License for more details.
18#
19# You should have received a copy of the GNU Lesser Public License
20# along with this program. If not, see [http://www.gnu.org/licenses/].
21"""This module contains an object that represents a Telegram Bot."""
22
23import functools
24import inspect
25from decorator import decorate
26
27try:
28 import ujson as json
29except ImportError:
30 import json
31import logging
32import warnings
33from datetime import datetime
34
35from cryptography.hazmat.backends import default_backend
36from cryptography.hazmat.primitives import serialization
37from future.utils import string_types
38
39from telegram import (User, Message, Update, Chat, ChatMember, UserProfilePhotos, File,
40 ReplyMarkup, TelegramObject, WebhookInfo, GameHighScore, StickerSet,
41 PhotoSize, Audio, Document, Sticker, Video, Animation, Voice, VideoNote,
42 Location, Venue, Contact, InputFile, Poll)
43from telegram.error import InvalidToken, TelegramError
44from telegram.utils.helpers import to_timestamp, DEFAULT_NONE
45from telegram.utils.request import Request
46
47logging.getLogger(__name__).addHandler(logging.NullHandler())
48
49
50def info(func):
51 @functools.wraps(func)
52 def decorator(self, *args, **kwargs):
53 if not self.bot:
54 self.get_me()
55
56 result = func(self, *args, **kwargs)
57 return result
58
59 return decorator
60
61
62def log(func, *args, **kwargs):
63 logger = logging.getLogger(func.__module__)
64
65 def decorator(self, *args, **kwargs):
66 logger.debug('Entering: %s', func.__name__)
67 result = func(*args, **kwargs)
68 logger.debug(result)
69 logger.debug('Exiting: %s', func.__name__)
70 return result
71
72 return decorate(func, decorator)
73
74
75class Bot(TelegramObject):
76 """This object represents a Telegram Bot.
77
78 Args:
79 token (:obj:`str`): Bot's unique authentication.
80 base_url (:obj:`str`, optional): Telegram Bot API service URL.
81 base_file_url (:obj:`str`, optional): Telegram Bot API file URL.
82 request (:obj:`telegram.utils.request.Request`, optional): Pre initialized
83 :obj:`telegram.utils.request.Request`.
84 private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
85 private_key_password (:obj:`bytes`, optional): Password for above private key.
86 defaults (:class:`telegram.ext.Defaults`, optional): An object containing default values to
87 be used if not set explicitly in the bot methods.
88
89 """
90
91 def __new__(cls, *args, **kwargs):
92 # Get default values from kwargs
93 defaults = kwargs.get('defaults')
94
95 # Make an instance of the class
96 instance = super(Bot, cls).__new__(cls)
97
98 if not defaults:
99 return instance
100
101 # For each method ...
102 for method_name, method in inspect.getmembers(instance, predicate=inspect.ismethod):
103 # ... get kwargs
104 argspec = inspect.getargspec(method)
105 kwarg_names = argspec.args[-len(argspec.defaults or []):]
106 # ... check if Defaults has a attribute that matches the kwarg name
107 needs_default = [
108 kwarg_name for kwarg_name in kwarg_names if hasattr(defaults, kwarg_name)
109 ]
110 # ... make a dict of kwarg name and the default value
111 default_kwargs = {
112 kwarg_name: getattr(defaults, kwarg_name) for kwarg_name in needs_default if (
113 getattr(defaults, kwarg_name) is not DEFAULT_NONE
114 )
115 }
116 # ... apply the defaults using a partial
117 if default_kwargs:
118 setattr(instance, method_name, functools.partial(method, **default_kwargs))
119
120 return instance
121
122 def __init__(self,
123 token,
124 base_url=None,
125 base_file_url=None,
126 request=None,
127 private_key=None,
128 private_key_password=None,
129 defaults=None):
130 self.token = self._validate_token(token)
131
132 # Gather default
133 self.defaults = defaults
134
135 if base_url is None:
136 base_url = 'https://api.telegram.org/bot'
137
138 if base_file_url is None:
139 base_file_url = 'https://api.telegram.org/file/bot'
140
141 self.base_url = str(base_url) + str(self.token)
142 self.base_file_url = str(base_file_url) + str(self.token)
143 self.bot = None
144 self._request = request or Request()
145 self.logger = logging.getLogger(__name__)
146
147 if private_key:
148 self.private_key = serialization.load_pem_private_key(private_key,
149 password=private_key_password,
150 backend=default_backend())
151
152 def _message(self, url, data, reply_to_message_id=None, disable_notification=None,
153 reply_markup=None, timeout=None, **kwargs):
154 if reply_to_message_id is not None:
155 data['reply_to_message_id'] = reply_to_message_id
156
157 if disable_notification is not None:
158 data['disable_notification'] = disable_notification
159
160 if reply_markup is not None:
161 if isinstance(reply_markup, ReplyMarkup):
162 data['reply_markup'] = reply_markup.to_json()
163 else:
164 data['reply_markup'] = reply_markup
165
166 if data.get('media') and (data['media'].parse_mode == DEFAULT_NONE):
167 if self.defaults:
168 data['media'].parse_mode = self.defaults.parse_mode
169 else:
170 data['media'].parse_mode = None
171
172 result = self._request.post(url, data, timeout=timeout)
173
174 if result is True:
175 return result
176
177 if self.defaults:
178 result['default_quote'] = self.defaults.quote
179
180 return Message.de_json(result, self)
181
182 @property
183 def request(self):
184 return self._request
185
186 @staticmethod
187 def _validate_token(token):
188 """A very basic validation on token."""
189 if any(x.isspace() for x in token):
190 raise InvalidToken()
191
192 left, sep, _right = token.partition(':')
193 if (not sep) or (not left.isdigit()) or (len(left) < 3):
194 raise InvalidToken()
195
196 return token
197
198 @property
199 @info
200 def id(self):
201 """:obj:`int`: Unique identifier for this bot."""
202
203 return self.bot.id
204
205 @property
206 @info
207 def first_name(self):
208 """:obj:`str`: Bot's first name."""
209
210 return self.bot.first_name
211
212 @property
213 @info
214 def last_name(self):
215 """:obj:`str`: Optional. Bot's last name."""
216
217 return self.bot.last_name
218
219 @property
220 @info
221 def username(self):
222 """:obj:`str`: Bot's username."""
223
224 return self.bot.username
225
226 @property
227 @info
228 def link(self):
229 """:obj:`str`: Convenience property. Returns the t.me link of the bot."""
230
231 return "https://t.me/{}".format(self.username)
232
233 @property
234 @info
235 def can_join_groups(self):
236 """:obj:`str`: Bot's can_join_groups attribute."""
237
238 return self.bot.can_join_groups
239
240 @property
241 @info
242 def can_read_all_group_messages(self):
243 """:obj:`str`: Bot's can_read_all_group_messages attribute."""
244
245 return self.bot.can_read_all_group_messages
246
247 @property
248 @info
249 def supports_inline_queries(self):
250 """:obj:`str`: Bot's supports_inline_queries attribute."""
251
252 return self.bot.supports_inline_queries
253
254 @property
255 def name(self):
256 """:obj:`str`: Bot's @username."""
257
258 return '@{0}'.format(self.username)
259
260 @log
261 def get_me(self, timeout=None, **kwargs):
262 """A simple method for testing your bot's auth token. Requires no parameters.
263
264 Args:
265 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
266 the read timeout from the server (instead of the one specified during creation of
267 the connection pool).
268
269 Returns:
270 :class:`telegram.User`: A :class:`telegram.User` instance representing that bot if the
271 credentials are valid, :obj:`None` otherwise.
272
273 Raises:
274 :class:`telegram.TelegramError`
275
276 """
277 url = '{0}/getMe'.format(self.base_url)
278
279 result = self._request.get(url, timeout=timeout)
280
281 self.bot = User.de_json(result, self)
282
283 return self.bot
284
285 @log
286 def send_message(self,
287 chat_id,
288 text,
289 parse_mode=None,
290 disable_web_page_preview=None,
291 disable_notification=False,
292 reply_to_message_id=None,
293 reply_markup=None,
294 timeout=None,
295 **kwargs):
296 """Use this method to send text messages.
297
298 Args:
299 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
300 of the target channel (in the format @channelusername).
301 text (:obj:`str`): Text of the message to be sent. Max 4096 characters after entities
302 parsing. Also found as :attr:`telegram.constants.MAX_MESSAGE_LENGTH`.
303 parse_mode (:obj:`str`): Send Markdown or HTML, if you want Telegram apps to show bold,
304 italic, fixed-width text or inline URLs in your bot's message. See the constants in
305 :class:`telegram.ParseMode` for the available modes.
306 disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in
307 this message.
308 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
309 receive a notification with no sound.
310 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
311 original message.
312 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options.
313 A JSON-serialized object for an inline keyboard, custom reply keyboard,
314 instructions to remove reply keyboard or to force a reply from the user.
315 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
316 the read timeout from the server (instead of the one specified during creation of
317 the connection pool).
318 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
319
320 Returns:
321 :class:`telegram.Message`: On success, the sent message is returned.
322
323 Raises:
324 :class:`telegram.TelegramError`
325
326 """
327 url = '{0}/sendMessage'.format(self.base_url)
328
329 data = {'chat_id': chat_id, 'text': text}
330
331 if parse_mode:
332 data['parse_mode'] = parse_mode
333 if disable_web_page_preview:
334 data['disable_web_page_preview'] = disable_web_page_preview
335
336 return self._message(url, data, disable_notification=disable_notification,
337 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
338 timeout=timeout, **kwargs)
339
340 @log
341 def delete_message(self, chat_id, message_id, timeout=None, **kwargs):
342 """
343 Use this method to delete a message, including service messages, with the following
344 limitations:
345
346 - A message can only be deleted if it was sent less than 48 hours ago.
347 - A dice message in a private chat can only be deleted if it was sent more than 24
348 hours ago.
349 - Bots can delete outgoing messages in private chats, groups, and supergroups.
350 - Bots can delete incoming messages in private chats.
351 - Bots granted can_post_messages permissions can delete outgoing messages in channels.
352 - If the bot is an administrator of a group, it can delete any message there.
353 - If the bot has can_delete_messages permission in a supergroup or a channel, it can
354 delete any message there.
355
356 Args:
357 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
358 of the target channel (in the format @channelusername).
359 message_id (:obj:`int`): Identifier of the message to delete.
360 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
361 the read timeout from the server (instead of the one specified during creation of
362 the connection pool).
363 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
364
365 Returns:
366 :obj:`bool`: On success, ``True`` is returned.
367
368 Raises:
369 :class:`telegram.TelegramError`
370
371 """
372 url = '{0}/deleteMessage'.format(self.base_url)
373
374 data = {'chat_id': chat_id, 'message_id': message_id}
375
376 result = self._request.post(url, data, timeout=timeout)
377
378 return result
379
380 @log
381 def forward_message(self,
382 chat_id,
383 from_chat_id,
384 message_id,
385 disable_notification=False,
386 timeout=None,
387 **kwargs):
388 """Use this method to forward messages of any kind.
389
390 Args:
391 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
392 of the target channel (in the format @channelusername).
393 from_chat_id (:obj:`int` | :obj:`str`): Unique identifier for the chat where the
394 original message was sent (or channel username in the format @channelusername).
395 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
396 receive a notification with no sound.
397 message_id (:obj:`int`): Message identifier in the chat specified in from_chat_id.
398 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
399 the read timeout from the server (instead of the one specified during creation of
400 the connection pool).
401 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
402
403 Returns:
404 :class:`telegram.Message`: On success, the sent Message is returned.
405
406 Raises:
407 :class:`telegram.TelegramError`
408
409 """
410 url = '{0}/forwardMessage'.format(self.base_url)
411
412 data = {}
413
414 if chat_id:
415 data['chat_id'] = chat_id
416 if from_chat_id:
417 data['from_chat_id'] = from_chat_id
418 if message_id:
419 data['message_id'] = message_id
420
421 return self._message(url, data, disable_notification=disable_notification,
422 timeout=timeout, **kwargs)
423
424 @log
425 def send_photo(self,
426 chat_id,
427 photo,
428 caption=None,
429 disable_notification=False,
430 reply_to_message_id=None,
431 reply_markup=None,
432 timeout=20,
433 parse_mode=None,
434 **kwargs):
435 """Use this method to send photos.
436
437 Note:
438 The photo argument can be either a file_id, an URL or a file from disk
439 ``open(filename, 'rb')``
440
441 Args:
442 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
443 of the target channel (in the format @channelusername).
444 photo (:obj:`str` | `filelike object` | :class:`telegram.PhotoSize`): Photo to send.
445 Pass a file_id as String to send a photo that exists on the Telegram servers
446 (recommended), pass an HTTP URL as a String for Telegram to get a photo from the
447 Internet, or upload a new photo using multipart/form-data. Lastly you can pass
448 an existing :class:`telegram.PhotoSize` object to send.
449 caption (:obj:`str`, optional): Photo caption (may also be used when resending photos
450 by file_id), 0-1024 characters after entities parsing.
451 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
452 show bold, italic, fixed-width text or inline URLs in the media caption. See the
453 constants in :class:`telegram.ParseMode` for the available modes.
454 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
455 receive a notification with no sound.
456 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
457 original message.
458 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
459 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
460 to remove reply keyboard or to force a reply from the user.
461 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
462 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
463
464 Returns:
465 :class:`telegram.Message`: On success, the sent Message is returned.
466
467 Raises:
468 :class:`telegram.TelegramError`
469
470 """
471 url = '{0}/sendPhoto'.format(self.base_url)
472
473 if isinstance(photo, PhotoSize):
474 photo = photo.file_id
475 elif InputFile.is_file(photo):
476 photo = InputFile(photo)
477
478 data = {'chat_id': chat_id, 'photo': photo}
479
480 if caption:
481 data['caption'] = caption
482 if parse_mode:
483 data['parse_mode'] = parse_mode
484
485 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
486 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
487 **kwargs)
488
489 @log
490 def send_audio(self,
491 chat_id,
492 audio,
493 duration=None,
494 performer=None,
495 title=None,
496 caption=None,
497 disable_notification=False,
498 reply_to_message_id=None,
499 reply_markup=None,
500 timeout=20,
501 parse_mode=None,
502 thumb=None,
503 **kwargs):
504 """
505 Use this method to send audio files, if you want Telegram clients to display them in the
506 music player. Your audio must be in the .mp3 or .m4a format. On success, the sent Message is
507 returned. Bots can currently send audio files of up to 50 MB in size, this limit may be
508 changed in the future.
509
510 For sending voice messages, use the sendVoice method instead.
511
512 Note:
513 The audio argument can be either a file_id, an URL or a file from disk
514 ``open(filename, 'rb')``
515
516 Args:
517 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
518 of the target channel (in the format @channelusername).
519 audio (:obj:`str` | `filelike object` | :class:`telegram.Audio`): Audio file to send.
520 Pass a file_id as String to send an audio file that exists on the Telegram servers
521 (recommended), pass an HTTP URL as a String for Telegram to get an audio file from
522 the Internet, or upload a new one using multipart/form-data. Lastly you can pass
523 an existing :class:`telegram.Audio` object to send.
524 caption (:obj:`str`, optional): Audio caption, 0-1024 characters after entities
525 parsing.
526 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
527 show bold, italic, fixed-width text or inline URLs in the media caption. See the
528 constants in :class:`telegram.ParseMode` for the available modes.
529 duration (:obj:`int`, optional): Duration of sent audio in seconds.
530 performer (:obj:`str`, optional): Performer.
531 title (:obj:`str`, optional): Track name.
532 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
533 receive a notification with no sound.
534 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
535 original message.
536 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
537 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
538 to remove reply keyboard or to force a reply from the user.
539 thumb (`filelike object`, optional): Thumbnail of the file sent; can be ignored if
540 thumbnail generation for the file is supported server-side. The thumbnail should
541 be in JPEG format and less than 200 kB in size. A thumbnail's width and height
542 should not exceed 320. Ignored if the file is not is passed as a string or file_id.
543 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
544 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
545
546 Returns:
547 :class:`telegram.Message`: On success, the sent Message is returned.
548
549 Raises:
550 :class:`telegram.TelegramError`
551
552 """
553 url = '{0}/sendAudio'.format(self.base_url)
554
555 if isinstance(audio, Audio):
556 audio = audio.file_id
557 elif InputFile.is_file(audio):
558 audio = InputFile(audio)
559
560 data = {'chat_id': chat_id, 'audio': audio}
561
562 if duration:
563 data['duration'] = duration
564 if performer:
565 data['performer'] = performer
566 if title:
567 data['title'] = title
568 if caption:
569 data['caption'] = caption
570 if parse_mode:
571 data['parse_mode'] = parse_mode
572 if thumb:
573 if InputFile.is_file(thumb):
574 thumb = InputFile(thumb, attach=True)
575 data['thumb'] = thumb
576
577 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
578 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
579 **kwargs)
580
581 @log
582 def send_document(self,
583 chat_id,
584 document,
585 filename=None,
586 caption=None,
587 disable_notification=False,
588 reply_to_message_id=None,
589 reply_markup=None,
590 timeout=20,
591 parse_mode=None,
592 thumb=None,
593 **kwargs):
594 """
595 Use this method to send general files. On success, the sent Message is returned.
596 Bots can currently send files of any type of up to 50 MB in size, this limit may be
597 changed in the future.
598
599 Note:
600 The document argument can be either a file_id, an URL or a file from disk
601 ``open(filename, 'rb')``
602
603 Args:
604 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
605 of the target channel (in the format @channelusername).
606 document (:obj:`str` | `filelike object` | :class:`telegram.Document`): File to send.
607 Pass a file_id as String to send a file that exists on the Telegram servers
608 (recommended), pass an HTTP URL as a String for Telegram to get a file from the
609 Internet, or upload a new one using multipart/form-data. Lastly you can pass
610 an existing :class:`telegram.Document` object to send.
611 filename (:obj:`str`, optional): File name that shows in telegram message (it is useful
612 when you send file generated by temp module, for example). Undocumented.
613 caption (:obj:`str`, optional): Document caption (may also be used when resending
614 documents by file_id), 0-1024 characters after entities parsing.
615 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
616 show bold, italic, fixed-width text or inline URLs in the media caption. See the
617 constants in :class:`telegram.ParseMode` for the available modes.
618 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
619 receive a notification with no sound.
620 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
621 original message.
622 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
623 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
624 to remove reply keyboard or to force a reply from the user.
625 thumb (`filelike object`, optional): Thumbnail of the file sent; can be ignored if
626 thumbnail generation for the file is supported server-side. The thumbnail should
627 be in JPEG format and less than 200 kB in size. A thumbnail's width and height
628 should not exceed 320. Ignored if the file is not passed as a string or file_id.
629 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
630 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
631
632 Returns:
633 :class:`telegram.Message`: On success, the sent Message is returned.
634
635 Raises:
636 :class:`telegram.TelegramError`
637
638 """
639 url = '{0}/sendDocument'.format(self.base_url)
640
641 if isinstance(document, Document):
642 document = document.file_id
643 elif InputFile.is_file(document):
644 document = InputFile(document, filename=filename)
645
646 data = {'chat_id': chat_id, 'document': document}
647
648 if caption:
649 data['caption'] = caption
650 if parse_mode:
651 data['parse_mode'] = parse_mode
652 if thumb:
653 if InputFile.is_file(thumb):
654 thumb = InputFile(thumb, attach=True)
655 data['thumb'] = thumb
656
657 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
658 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
659 **kwargs)
660
661 @log
662 def send_sticker(self,
663 chat_id,
664 sticker,
665 disable_notification=False,
666 reply_to_message_id=None,
667 reply_markup=None,
668 timeout=20,
669 **kwargs):
670 """
671 Use this method to send static .WEBP or animated .TGS stickers.
672 On success, the sent Message is returned.
673
674 Note:
675 The sticker argument can be either a file_id, an URL or a file from disk
676 ``open(filename, 'rb')``
677
678 Args:
679 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
680 of the target channel (in the format @channelusername).
681 sticker (:obj:`str` | `filelike object` :class:`telegram.Sticker`): Sticker to send.
682 Pass a file_id as String to send a file that exists on the Telegram servers
683 (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from
684 the Internet, or upload a new one using multipart/form-data. Lastly you can pass
685 an existing :class:`telegram.Sticker` object to send.
686 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
687 receive a notification with no sound.
688 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
689 original message.
690 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
691 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
692 to remove reply keyboard or to force a reply from the user.
693 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
694 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
695
696 Returns:
697 :class:`telegram.Message`: On success, the sent Message is returned.
698
699 Raises:
700 :class:`telegram.TelegramError`
701
702 """
703 url = '{0}/sendSticker'.format(self.base_url)
704
705 if isinstance(sticker, Sticker):
706 sticker = sticker.file_id
707 elif InputFile.is_file(sticker):
708 sticker = InputFile(sticker)
709
710 data = {'chat_id': chat_id, 'sticker': sticker}
711
712 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
713 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
714 **kwargs)
715
716 @log
717 def send_video(self,
718 chat_id,
719 video,
720 duration=None,
721 caption=None,
722 disable_notification=False,
723 reply_to_message_id=None,
724 reply_markup=None,
725 timeout=20,
726 width=None,
727 height=None,
728 parse_mode=None,
729 supports_streaming=None,
730 thumb=None,
731 **kwargs):
732 """
733 Use this method to send video files, Telegram clients support mp4 videos
734 (other formats may be sent as Document). On success, the sent Message is returned.
735 Bots can currently send video files of up to 50 MB in size, this limit may be changed in
736 the future.
737
738 Note:
739 The video argument can be either a file_id, an URL or a file from disk
740 ``open(filename, 'rb')``
741
742 Args:
743 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
744 of the target channel (in the format @channelusername).
745 video (:obj:`str` | `filelike object` | :class:`telegram.Video`): Video file to send.
746 Pass a file_id as String to send an video file that exists on the Telegram servers
747 (recommended), pass an HTTP URL as a String for Telegram to get an video file from
748 the Internet, or upload a new one using multipart/form-data. Lastly you can pass
749 an existing :class:`telegram.Video` object to send.
750 duration (:obj:`int`, optional): Duration of sent video in seconds.
751 width (:obj:`int`, optional): Video width.
752 height (:obj:`int`, optional): Video height.
753 caption (:obj:`str`, optional): Video caption (may also be used when resending videos
754 by file_id), 0-1024 characters after entities parsing.
755 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
756 show bold, italic, fixed-width text or inline URLs in the media caption. See the
757 constants in :class:`telegram.ParseMode` for the available modes.
758 supports_streaming (:obj:`bool`, optional): Pass True, if the uploaded video is
759 suitable for streaming.
760 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
761 receive a notification with no sound.
762 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
763 original message.
764 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
765 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
766 to remove reply keyboard or to force a reply from the user.
767 thumb (`filelike object`, optional): Thumbnail of the file sent; can be ignored if
768 thumbnail generation for the file is supported server-side. The thumbnail should
769 be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height
770 should not exceed 320. Ignored if the file is not is passed as a string or file_id.
771 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
772 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
773
774 Returns:
775 :class:`telegram.Message`: On success, the sent Message is returned.
776
777 Raises:
778 :class:`telegram.TelegramError`
779
780 """
781 url = '{0}/sendVideo'.format(self.base_url)
782
783 if isinstance(video, Video):
784 video = video.file_id
785 elif InputFile.is_file(video):
786 video = InputFile(video)
787
788 data = {'chat_id': chat_id, 'video': video}
789
790 if duration:
791 data['duration'] = duration
792 if caption:
793 data['caption'] = caption
794 if parse_mode:
795 data['parse_mode'] = parse_mode
796 if supports_streaming:
797 data['supports_streaming'] = supports_streaming
798 if width:
799 data['width'] = width
800 if height:
801 data['height'] = height
802 if thumb:
803 if InputFile.is_file(thumb):
804 thumb = InputFile(thumb, attach=True)
805 data['thumb'] = thumb
806
807 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
808 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
809 **kwargs)
810
811 @log
812 def send_video_note(self,
813 chat_id,
814 video_note,
815 duration=None,
816 length=None,
817 disable_notification=False,
818 reply_to_message_id=None,
819 reply_markup=None,
820 timeout=20,
821 thumb=None,
822 **kwargs):
823 """
824 As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
825 Use this method to send video messages. On success, the sent Message is returned.
826
827 Note:
828 The video_note argument can be either a file_id or a file from disk
829 ``open(filename, 'rb')``
830
831 Args:
832 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
833 of the target channel (in the format @channelusername).
834 video_note (:obj:`str` | `filelike object` | :class:`telegram.VideoNote`): Video note
835 to send. Pass a file_id as String to send a video note that exists on the Telegram
836 servers (recommended) or upload a new video using multipart/form-data. Or you can
837 pass an existing :class:`telegram.VideoNote` object to send. Sending video notes by
838 a URL is currently unsupported.
839 duration (:obj:`int`, optional): Duration of sent video in seconds.
840 length (:obj:`int`, optional): Video width and height, i.e. diameter of the video
841 message.
842 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
843 receive a notification with no sound.
844 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
845 original message.
846 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
847 JSON-serialized object for an inline keyboard, custom reply keyboard,
848 instructions to remove reply keyboard or to force a reply from the user.
849 thumb (`filelike object`, optional): Thumbnail of the file sent; can be ignored if
850 thumbnail generation for the file is supported server-side. The thumbnail should
851 be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height
852 should not exceed 320. Ignored if the file is not is passed as a string or file_id.
853 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
854 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
855
856 Returns:
857 :class:`telegram.Message`: On success, the sent Message is returned.
858
859 Raises:
860 :class:`telegram.TelegramError`
861
862 """
863 url = '{0}/sendVideoNote'.format(self.base_url)
864
865 if isinstance(video_note, VideoNote):
866 video_note = video_note.file_id
867 elif InputFile.is_file(video_note):
868 video_note = InputFile(video_note)
869
870 data = {'chat_id': chat_id, 'video_note': video_note}
871
872 if duration is not None:
873 data['duration'] = duration
874 if length is not None:
875 data['length'] = length
876 if thumb:
877 if InputFile.is_file(thumb):
878 thumb = InputFile(thumb, attach=True)
879 data['thumb'] = thumb
880
881 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
882 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
883 **kwargs)
884
885 @log
886 def send_animation(self,
887 chat_id,
888 animation,
889 duration=None,
890 width=None,
891 height=None,
892 thumb=None,
893 caption=None,
894 parse_mode=None,
895 disable_notification=False,
896 reply_to_message_id=None,
897 reply_markup=None,
898 timeout=20,
899 **kwargs):
900 """
901 Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
902 On success, the sent Message is returned. Bots can currently send animation files of
903 up to 50 MB in size, this limit may be changed in the future.
904
905 Args:
906 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
907 of the target channel (in the format @channelusername).
908 animation (:obj:`str` | `filelike object` | :class:`telegram.Animation`): Animation to
909 send. Pass a file_id as String to send an animation that exists on the Telegram
910 servers (recommended), pass an HTTP URL as a String for Telegram to get an
911 animation from the Internet, or upload a new animation using multipart/form-data.
912 Lastly you can pass an existing :class:`telegram.Animation` object to send.
913 duration (:obj:`int`, optional): Duration of sent animation in seconds.
914 width (:obj:`int`, optional): Animation width.
915 height (:obj:`int`, optional): Animation height.
916 thumb (`filelike object`, optional): Thumbnail of the file sent; can be ignored if
917 thumbnail generation for the file is supported server-side. The thumbnail should
918 be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height
919 should not exceed 320. Ignored if the file is not is passed as a string or file_id.
920 caption (:obj:`str`, optional): Animation caption (may also be used when resending
921 animations by file_id), 0-1024 characters after entities parsing.
922 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
923 show bold, italic, fixed-width text or inline URLs in the media caption. See the
924 constants in :class:`telegram.ParseMode` for the available modes.
925 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
926 receive a notification with no sound.
927 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
928 original message.
929 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
930 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
931 to remove reply keyboard or to force a reply from the user.
932 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
933 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
934
935 Returns:
936 :class:`telegram.Message`: On success, the sent Message is returned.
937
938 Raises:
939 :class:`telegram.TelegramError`
940
941 """
942 url = '{0}/sendAnimation'.format(self.base_url)
943
944 if isinstance(animation, Animation):
945 animation = animation.file_id
946 elif InputFile.is_file(animation):
947 animation = InputFile(animation)
948
949 data = {'chat_id': chat_id, 'animation': animation}
950
951 if duration:
952 data['duration'] = duration
953 if width:
954 data['width'] = width
955 if height:
956 data['height'] = height
957 if thumb:
958 if InputFile.is_file(thumb):
959 thumb = InputFile(thumb, attach=True)
960 data['thumb'] = thumb
961 if caption:
962 data['caption'] = caption
963 if parse_mode:
964 data['parse_mode'] = parse_mode
965
966 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
967 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
968 **kwargs)
969
970 @log
971 def send_voice(self,
972 chat_id,
973 voice,
974 duration=None,
975 caption=None,
976 disable_notification=False,
977 reply_to_message_id=None,
978 reply_markup=None,
979 timeout=20,
980 parse_mode=None,
981 **kwargs):
982 """
983 Use this method to send audio files, if you want Telegram clients to display the file
984 as a playable voice message. For this to work, your audio must be in an .ogg file
985 encoded with OPUS (other formats may be sent as Audio or Document). Bots can currently
986 send voice messages of up to 50 MB in size, this limit may be changed in the future.
987
988 Note:
989 The voice argument can be either a file_id, an URL or a file from disk
990 ``open(filename, 'rb')``
991
992 Args:
993 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
994 of the target channel (in the format @channelusername).
995 voice (:obj:`str` | `filelike object` | :class:`telegram.Voice`): Voice file to send.
996 Pass a file_id as String to send an voice file that exists on the Telegram servers
997 (recommended), pass an HTTP URL as a String for Telegram to get an voice file from
998 the Internet, or upload a new one using multipart/form-data. Lastly you can pass
999 an existing :class:`telegram.Voice` object to send.
1000 caption (:obj:`str`, optional): Voice message caption, 0-1024 characters after entities
1001 parsing.
1002 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
1003 show bold, italic, fixed-width text or inline URLs in the media caption. See the
1004 constants in :class:`telegram.ParseMode` for the available modes.
1005 duration (:obj:`int`, optional): Duration of the voice message in seconds.
1006 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1007 receive a notification with no sound.
1008 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1009 original message.
1010 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
1011 JSON-serialized object for an inline keyboard, custom reply keyboard,
1012 instructions to remove reply keyboard or to force a reply from the user.
1013 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
1014 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1015
1016 Returns:
1017 :class:`telegram.Message`: On success, the sent Message is returned.
1018
1019 Raises:
1020 :class:`telegram.TelegramError`
1021
1022 """
1023 url = '{0}/sendVoice'.format(self.base_url)
1024
1025 if isinstance(voice, Voice):
1026 voice = voice.file_id
1027 elif InputFile.is_file(voice):
1028 voice = InputFile(voice)
1029
1030 data = {'chat_id': chat_id, 'voice': voice}
1031
1032 if duration:
1033 data['duration'] = duration
1034 if caption:
1035 data['caption'] = caption
1036 if parse_mode:
1037 data['parse_mode'] = parse_mode
1038
1039 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
1040 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
1041 **kwargs)
1042
1043 @log
1044 def send_media_group(self,
1045 chat_id,
1046 media,
1047 disable_notification=None,
1048 reply_to_message_id=None,
1049 timeout=20,
1050 **kwargs):
1051 """Use this method to send a group of photos or videos as an album.
1052
1053 Args:
1054 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1055 of the target channel (in the format @channelusername).
1056 media (List[:class:`telegram.InputMedia`]): An array describing photos and videos to be
1057 sent, must include 2–10 items.
1058 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1059 receive a notification with no sound.
1060 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1061 original message.
1062 timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
1063 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1064
1065 Returns:
1066 List[:class:`telegram.Message`]: An array of the sent Messages.
1067
1068 Raises:
1069 :class:`telegram.TelegramError`
1070 """
1071
1072 url = '{0}/sendMediaGroup'.format(self.base_url)
1073
1074 data = {'chat_id': chat_id, 'media': media}
1075
1076 for m in data['media']:
1077 if m.parse_mode == DEFAULT_NONE:
1078 if self.defaults:
1079 m.parse_mode = self.defaults.parse_mode
1080 else:
1081 m.parse_mode = None
1082
1083 if reply_to_message_id:
1084 data['reply_to_message_id'] = reply_to_message_id
1085 if disable_notification:
1086 data['disable_notification'] = disable_notification
1087
1088 result = self._request.post(url, data, timeout=timeout)
1089
1090 if self.defaults:
1091 for res in result:
1092 res['default_quote'] = self.defaults.quote
1093
1094 return [Message.de_json(res, self) for res in result]
1095
1096 @log
1097 def send_location(self,
1098 chat_id,
1099 latitude=None,
1100 longitude=None,
1101 disable_notification=False,
1102 reply_to_message_id=None,
1103 reply_markup=None,
1104 timeout=None,
1105 location=None,
1106 live_period=None,
1107 **kwargs):
1108 """Use this method to send point on the map.
1109
1110 Note:
1111 You can either supply a :obj:`latitude` and :obj:`longitude` or a :obj:`location`.
1112
1113 Args:
1114 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1115 of the target channel (in the format @channelusername).
1116 latitude (:obj:`float`, optional): Latitude of location.
1117 longitude (:obj:`float`, optional): Longitude of location.
1118 location (:class:`telegram.Location`, optional): The location to send.
1119 live_period (:obj:`int`, optional): Period in seconds for which the location will be
1120 updated, should be between 60 and 86400.
1121 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1122 receive a notification with no sound.
1123 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1124 original message.
1125 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
1126 JSON-serialized object for an inline keyboard, custom reply keyboard,
1127 instructions to remove reply keyboard or to force a reply from the user.
1128 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1129 the read timeout from the server (instead of the one specified during creation of
1130 the connection pool).
1131 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1132
1133 Returns:
1134 :class:`telegram.Message`: On success, the sent Message is returned.
1135
1136 Raises:
1137 :class:`telegram.TelegramError`
1138
1139 """
1140 url = '{0}/sendLocation'.format(self.base_url)
1141
1142 if not ((latitude is not None and longitude is not None) or location):
1143 raise ValueError("Either location or latitude and longitude must be passed as"
1144 "argument.")
1145
1146 if not ((latitude is not None or longitude is not None) ^ bool(location)):
1147 raise ValueError("Either location or latitude and longitude must be passed as"
1148 "argument. Not both.")
1149
1150 if isinstance(location, Location):
1151 latitude = location.latitude
1152 longitude = location.longitude
1153
1154 data = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
1155
1156 if live_period:
1157 data['live_period'] = live_period
1158
1159 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
1160 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
1161 **kwargs)
1162
1163 @log
1164 def edit_message_live_location(self,
1165 chat_id=None,
1166 message_id=None,
1167 inline_message_id=None,
1168 latitude=None,
1169 longitude=None,
1170 location=None,
1171 reply_markup=None,
1172 timeout=None,
1173 **kwargs):
1174 """Use this method to edit live location messages sent by the bot or via the bot
1175 (for inline bots). A location can be edited until its :attr:`live_period` expires or
1176 editing is explicitly disabled by a call to :attr:`stop_message_live_location`.
1177
1178 Note:
1179 You can either supply a :obj:`latitude` and :obj:`longitude` or a :obj:`location`.
1180
1181 Args:
1182 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
1183 specified. Unique identifier for the target chat or username of the target channel
1184 (in the format @channelusername).
1185 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
1186 Identifier of the message to edit.
1187 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
1188 specified. Identifier of the inline message.
1189 latitude (:obj:`float`, optional): Latitude of location.
1190 longitude (:obj:`float`, optional): Longitude of location.
1191 location (:class:`telegram.Location`, optional): The location to send.
1192 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1193 object for a new inline keyboard.
1194 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1195 the read timeout from the server (instead of the one specified during creation of
1196 the connection pool).
1197
1198 Returns:
1199 :class:`telegram.Message`: On success the edited message.
1200 :obj:`bool`: ``True`` is returned on failure.
1201 """
1202
1203 url = '{0}/editMessageLiveLocation'.format(self.base_url)
1204
1205 if not (all([latitude, longitude]) or location):
1206 raise ValueError("Either location or latitude and longitude must be passed as"
1207 "argument.")
1208 if not ((latitude is not None or longitude is not None) ^ bool(location)):
1209 raise ValueError("Either location or latitude and longitude must be passed as"
1210 "argument. Not both.")
1211
1212 if isinstance(location, Location):
1213 latitude = location.latitude
1214 longitude = location.longitude
1215
1216 data = {'latitude': latitude, 'longitude': longitude}
1217
1218 if chat_id:
1219 data['chat_id'] = chat_id
1220 if message_id:
1221 data['message_id'] = message_id
1222 if inline_message_id:
1223 data['inline_message_id'] = inline_message_id
1224
1225 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
1226
1227 @log
1228 def stop_message_live_location(self,
1229 chat_id=None,
1230 message_id=None,
1231 inline_message_id=None,
1232 reply_markup=None,
1233 timeout=None,
1234 **kwargs):
1235 """Use this method to stop updating a live location message sent by the bot or via the bot
1236 (for inline bots) before live_period expires.
1237
1238 Args:
1239 chat_id (:obj:`int` | :obj:`str`): Required if inline_message_id is not specified.
1240 Unique identifier for the target chat or username of the target channel
1241 (in the format @channelusername).
1242 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
1243 Identifier of the sent message with live location to stop.
1244 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
1245 specified. Identifier of the inline message.
1246 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1247 object for a new inline keyboard.
1248 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1249 the read timeout from the server (instead of the one specified during creation of
1250 the connection pool).
1251
1252 Returns:
1253 :class:`telegram.Message`: On success the edited message.
1254 `:obj:`bool`: ``True`` is returned on failure.
1255 """
1256
1257 url = '{0}/stopMessageLiveLocation'.format(self.base_url)
1258
1259 data = {}
1260
1261 if chat_id:
1262 data['chat_id'] = chat_id
1263 if message_id:
1264 data['message_id'] = message_id
1265 if inline_message_id:
1266 data['inline_message_id'] = inline_message_id
1267
1268 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
1269
1270 @log
1271 def send_venue(self,
1272 chat_id,
1273 latitude=None,
1274 longitude=None,
1275 title=None,
1276 address=None,
1277 foursquare_id=None,
1278 disable_notification=False,
1279 reply_to_message_id=None,
1280 reply_markup=None,
1281 timeout=None,
1282 venue=None,
1283 foursquare_type=None,
1284 **kwargs):
1285 """Use this method to send information about a venue.
1286
1287 Note:
1288 You can either supply :obj:`venue`, or :obj:`latitude`, :obj:`longitude`,
1289 :obj:`title` and :obj:`address` and optionally :obj:`foursquare_id` and optionally
1290 :obj:`foursquare_type`.
1291
1292 Args:
1293 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1294 of the target channel (in the format @channelusername).
1295 latitude (:obj:`float`, optional): Latitude of venue.
1296 longitude (:obj:`float`, optional): Longitude of venue.
1297 title (:obj:`str`, optional): Name of the venue.
1298 address (:obj:`str`, optional): Address of the venue.
1299 foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue.
1300 foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
1301 (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
1302 "food/icecream".)
1303 venue (:class:`telegram.Venue`, optional): The venue to send.
1304 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1305 receive a notification with no sound.
1306 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1307 original message.
1308 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
1309 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
1310 to remove reply keyboard or to force a reply from the user.
1311 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1312 the read timeout from the server (instead of the one specified during creation of
1313 the connection pool).
1314 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1315
1316 Returns:
1317 :class:`telegram.Message`: On success, the sent Message is returned.
1318
1319 Raises:
1320 :class:`telegram.TelegramError`
1321
1322 """
1323 url = '{0}/sendVenue'.format(self.base_url)
1324
1325 if not (venue or all([latitude, longitude, address, title])):
1326 raise ValueError("Either venue or latitude, longitude, address and title must be"
1327 "passed as arguments.")
1328
1329 if isinstance(venue, Venue):
1330 latitude = venue.location.latitude
1331 longitude = venue.location.longitude
1332 address = venue.address
1333 title = venue.title
1334 foursquare_id = venue.foursquare_id
1335 foursquare_type = venue.foursquare_type
1336
1337 data = {
1338 'chat_id': chat_id,
1339 'latitude': latitude,
1340 'longitude': longitude,
1341 'address': address,
1342 'title': title
1343 }
1344
1345 if foursquare_id:
1346 data['foursquare_id'] = foursquare_id
1347 if foursquare_type:
1348 data['foursquare_type'] = foursquare_type
1349
1350 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
1351 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
1352 **kwargs)
1353
1354 @log
1355 def send_contact(self,
1356 chat_id,
1357 phone_number=None,
1358 first_name=None,
1359 last_name=None,
1360 disable_notification=False,
1361 reply_to_message_id=None,
1362 reply_markup=None,
1363 timeout=None,
1364 contact=None,
1365 vcard=None,
1366 **kwargs):
1367 """Use this method to send phone contacts.
1368
1369 Note:
1370 You can either supply :obj:`contact` or :obj:`phone_number` and :obj:`first_name`
1371 with optionally :obj:`last_name` and optionally :obj:`vcard`.
1372
1373 Args:
1374 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1375 of the target channel (in the format @channelusername).
1376 phone_number (:obj:`str`, optional): Contact's phone number.
1377 first_name (:obj:`str`, optional): Contact's first name.
1378 last_name (:obj:`str`, optional): Contact's last name.
1379 vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
1380 0-2048 bytes.
1381 contact (:class:`telegram.Contact`, optional): The contact to send.
1382 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1383 receive a notification with no sound.
1384 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1385 original message.
1386 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
1387 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
1388 to remove reply keyboard or to force a reply from the user.
1389 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1390 the read timeout from the server (instead of the one specified during creation of
1391 the connection pool).
1392 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1393
1394 Returns:
1395 :class:`telegram.Message`: On success, the sent Message is returned.
1396
1397 Raises:
1398 :class:`telegram.TelegramError`
1399
1400 """
1401 url = '{0}/sendContact'.format(self.base_url)
1402
1403 if (not contact) and (not all([phone_number, first_name])):
1404 raise ValueError("Either contact or phone_number and first_name must be passed as"
1405 "arguments.")
1406
1407 if isinstance(contact, Contact):
1408 phone_number = contact.phone_number
1409 first_name = contact.first_name
1410 last_name = contact.last_name
1411 vcard = contact.vcard
1412
1413 data = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
1414
1415 if last_name:
1416 data['last_name'] = last_name
1417 if vcard:
1418 data['vcard'] = vcard
1419
1420 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
1421 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
1422 **kwargs)
1423
1424 @log
1425 def send_game(self,
1426 chat_id,
1427 game_short_name,
1428 disable_notification=False,
1429 reply_to_message_id=None,
1430 reply_markup=None,
1431 timeout=None,
1432 **kwargs):
1433 """Use this method to send a game.
1434
1435 Args:
1436 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1437 of the target channel (in the format @channelusername).
1438 game_short_name (:obj:`str`): Short name of the game, serves as the unique identifier
1439 for the game. Set up your games via Botfather.
1440 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
1441 receive a notification with no sound.
1442 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
1443 original message.
1444 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1445 object for a new inline keyboard. If empty, one ‘Play game_title’ button will be
1446 shown. If not empty, the first button must launch the game.
1447 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1448 the read timeout from the server (instead of the one specified during creation of
1449 the connection pool).
1450 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1451
1452 Returns:
1453 :class:`telegram.Message`: On success, the sent Message is returned.
1454
1455 Raises:
1456 :class:`telegram.TelegramError`
1457
1458 """
1459 url = '{0}/sendGame'.format(self.base_url)
1460
1461 data = {'chat_id': chat_id, 'game_short_name': game_short_name}
1462
1463 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
1464 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
1465 **kwargs)
1466
1467 @log
1468 def send_chat_action(self, chat_id, action, timeout=None, **kwargs):
1469 """
1470 Use this method when you need to tell the user that something is happening on the bot's
1471 side. The status is set for 5 seconds or less (when a message arrives from your bot,
1472 Telegram clients clear its typing status). We only recommend using this method when a
1473 response from the bot will take a noticeable amount of time to arrive.
1474
1475 Args:
1476 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1477 of the target channel (in the format @channelusername).
1478 action(:class:`telegram.ChatAction` | :obj:`str`): Type of action to broadcast. Choose
1479 one, depending on what the user is about to receive. For convenience look at the
1480 constants in :class:`telegram.ChatAction`
1481 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1482 the read timeout from the server (instead of the one specified during creation of
1483 the connection pool).
1484 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1485
1486 Returns:
1487 :obj:`bool`: ``True`` on success.
1488
1489 Raises:
1490 :class:`telegram.TelegramError`
1491
1492 """
1493 url = '{0}/sendChatAction'.format(self.base_url)
1494
1495 data = {'chat_id': chat_id, 'action': action}
1496 data.update(kwargs)
1497
1498 result = self._request.post(url, data, timeout=timeout)
1499
1500 return result
1501
1502 @log
1503 def answer_inline_query(self,
1504 inline_query_id,
1505 results,
1506 cache_time=300,
1507 is_personal=None,
1508 next_offset=None,
1509 switch_pm_text=None,
1510 switch_pm_parameter=None,
1511 timeout=None,
1512 **kwargs):
1513 """
1514 Use this method to send answers to an inline query. No more than 50 results per query are
1515 allowed.
1516
1517 Args:
1518 inline_query_id (:obj:`str`): Unique identifier for the answered query.
1519 results (List[:class:`telegram.InlineQueryResult`)]: A list of results for the inline
1520 query.
1521 cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the
1522 result of the inline query may be cached on the server. Defaults to 300.
1523 is_personal (:obj:`bool`, optional): Pass True, if results may be cached on the server
1524 side only for the user that sent the query. By default, results may be returned to
1525 any user who sends the same query.
1526 next_offset (:obj:`str`, optional): Pass the offset that a client should send in the
1527 next query with the same text to receive more results. Pass an empty string if
1528 there are no more results or if you don't support pagination. Offset length can't
1529 exceed 64 bytes.
1530 switch_pm_text (:obj:`str`, optional): If passed, clients will display a button with
1531 specified text that switches the user to a private chat with the bot and sends the
1532 bot a start message with the parameter switch_pm_parameter.
1533 switch_pm_parameter (:obj:`str`, optional): Deep-linking parameter for the /start
1534 message sent to the bot when user presses the switch button. 1-64 characters,
1535 only A-Z, a-z, 0-9, _ and - are allowed.
1536 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1537 he read timeout from the server (instead of the one specified during creation of
1538 the connection pool).
1539 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1540
1541 Example:
1542 An inline bot that sends YouTube videos can ask the user to connect the bot to their
1543 YouTube account to adapt search results accordingly. To do this, it displays a
1544 'Connect your YouTube account' button above the results, or even before showing any.
1545 The user presses the button, switches to a private chat with the bot and, in doing so,
1546 passes a start parameter that instructs the bot to return an oauth link. Once done, the
1547 bot can offer a switch_inline button so that the user can easily return to the chat
1548 where they wanted to use the bot's inline capabilities.
1549
1550 Returns:
1551 :obj:`bool` On success, ``True`` is returned.
1552
1553 Raises:
1554 :class:`telegram.TelegramError`
1555
1556 """
1557 url = '{0}/answerInlineQuery'.format(self.base_url)
1558
1559 for res in results:
1560 if res._has_parse_mode and res.parse_mode == DEFAULT_NONE:
1561 if self.defaults:
1562 res.parse_mode = self.defaults.parse_mode
1563 else:
1564 res.parse_mode = None
1565 if res._has_input_message_content and res.input_message_content:
1566 if (res.input_message_content._has_parse_mode
1567 and res.input_message_content.parse_mode == DEFAULT_NONE):
1568 if self.defaults:
1569 res.input_message_content.parse_mode = self.defaults.parse_mode
1570 else:
1571 res.input_message_content.parse_mode = None
1572 if (res.input_message_content._has_disable_web_page_preview
1573 and res.input_message_content.disable_web_page_preview == DEFAULT_NONE):
1574 if self.defaults:
1575 res.input_message_content.disable_web_page_preview = \
1576 self.defaults.disable_web_page_preview
1577 else:
1578 res.input_message_content.disable_web_page_preview = None
1579
1580 results = [res.to_dict() for res in results]
1581
1582 data = {'inline_query_id': inline_query_id, 'results': results}
1583
1584 if cache_time or cache_time == 0:
1585 data['cache_time'] = cache_time
1586 if is_personal:
1587 data['is_personal'] = is_personal
1588 if next_offset is not None:
1589 data['next_offset'] = next_offset
1590 if switch_pm_text:
1591 data['switch_pm_text'] = switch_pm_text
1592 if switch_pm_parameter:
1593 data['switch_pm_parameter'] = switch_pm_parameter
1594
1595 data.update(kwargs)
1596
1597 result = self._request.post(url, data, timeout=timeout)
1598
1599 return result
1600
1601 @log
1602 def get_user_profile_photos(self, user_id, offset=None, limit=100, timeout=None, **kwargs):
1603 """Use this method to get a list of profile pictures for a user.
1604
1605 Args:
1606 user_id (:obj:`int`): Unique identifier of the target user.
1607 offset (:obj:`int`, optional): Sequential number of the first photo to be returned.
1608 By default, all photos are returned.
1609 limit (:obj:`int`, optional): Limits the number of photos to be retrieved. Values
1610 between 1-100 are accepted. Defaults to 100.
1611 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1612 the read timeout from the server (instead of the one specified during creation of
1613 the connection pool).
1614 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1615
1616 Returns:
1617 :class:`telegram.UserProfilePhotos`
1618
1619 Raises:
1620 :class:`telegram.TelegramError`
1621
1622 """
1623 url = '{0}/getUserProfilePhotos'.format(self.base_url)
1624
1625 data = {'user_id': user_id}
1626
1627 if offset is not None:
1628 data['offset'] = offset
1629 if limit:
1630 data['limit'] = limit
1631 data.update(kwargs)
1632
1633 result = self._request.post(url, data, timeout=timeout)
1634
1635 return UserProfilePhotos.de_json(result, self)
1636
1637 @log
1638 def get_file(self, file_id, timeout=None, **kwargs):
1639 """
1640 Use this method to get basic info about a file and prepare it for downloading. For the
1641 moment, bots can download files of up to 20MB in size. The file can then be downloaded
1642 with :attr:`telegram.File.download`. It is guaranteed that the link will be
1643 valid for at least 1 hour. When the link expires, a new one can be requested by
1644 calling get_file again.
1645
1646 Note:
1647 This function may not preserve the original file name and MIME type.
1648 You should save the file's MIME type and name (if available) when the File object
1649 is received.
1650
1651 Args:
1652 file_id (:obj:`str` | :class:`telegram.Animation` | :class:`telegram.Audio` | \
1653 :class:`telegram.ChatPhoto` | :class:`telegram.Document` | \
1654 :class:`telegram.PhotoSize` | :class:`telegram.Sticker` | \
1655 :class:`telegram.Video` | :class:`telegram.VideoNote` | \
1656 :class:`telegram.Voice`):
1657 Either the file identifier or an object that has a file_id attribute
1658 to get file information about.
1659 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1660 the read timeout from the server (instead of the one specified during creation of
1661 the connection pool).
1662 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1663
1664 Returns:
1665 :class:`telegram.File`
1666
1667 Raises:
1668 :class:`telegram.TelegramError`
1669
1670 """
1671 url = '{0}/getFile'.format(self.base_url)
1672
1673 try:
1674 file_id = file_id.file_id
1675 except AttributeError:
1676 pass
1677
1678 data = {'file_id': file_id}
1679 data.update(kwargs)
1680
1681 result = self._request.post(url, data, timeout=timeout)
1682
1683 if result.get('file_path'):
1684 result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path'])
1685
1686 return File.de_json(result, self)
1687
1688 @log
1689 def kick_chat_member(self, chat_id, user_id, timeout=None, until_date=None, **kwargs):
1690 """
1691 Use this method to kick a user from a group or a supergroup or a channel. In the case of
1692 supergroups and channels, the user will not be able to return to the group on their own
1693 using invite links, etc., unless unbanned first. The bot must be an administrator in the
1694 group for this to work.
1695
1696 Args:
1697 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1698 of the target channel (in the format @channelusername).
1699 user_id (:obj:`int`): Unique identifier of the target user.
1700 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1701 the read timeout from the server (instead of the one specified during creation of
1702 the connection pool).
1703 until_date (:obj:`int` | :obj:`datetime.datetime`, optional): Date when the user will
1704 be unbanned, unix time. If user is banned for more than 366 days or less than 30
1705 seconds from the current time they are considered to be banned forever.
1706 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1707
1708 Returns:
1709 :obj:`bool` On success, ``True`` is returned.
1710
1711 Raises:
1712 :class:`telegram.TelegramError`
1713
1714 """
1715 url = '{0}/kickChatMember'.format(self.base_url)
1716
1717 data = {'chat_id': chat_id, 'user_id': user_id}
1718 data.update(kwargs)
1719
1720 if until_date is not None:
1721 if isinstance(until_date, datetime):
1722 until_date = to_timestamp(until_date)
1723 data['until_date'] = until_date
1724
1725 result = self._request.post(url, data, timeout=timeout)
1726
1727 return result
1728
1729 @log
1730 def unban_chat_member(self, chat_id, user_id, timeout=None, **kwargs):
1731 """Use this method to unban a previously kicked user in a supergroup or channel.
1732
1733 The user will not return to the group automatically, but will be able to join via link,
1734 etc. The bot must be an administrator in the group for this to work.
1735
1736 Args:
1737 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
1738 of the target channel (in the format @channelusername).
1739 user_id (:obj:`int`): Unique identifier of the target user.
1740 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1741 the read timeout from the server (instead of the one specified during creation of
1742 the connection pool).
1743 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1744
1745 Returns:
1746 :obj:`bool` On success, ``True`` is returned.
1747
1748 Raises:
1749 :class:`telegram.TelegramError`
1750
1751 """
1752 url = '{0}/unbanChatMember'.format(self.base_url)
1753
1754 data = {'chat_id': chat_id, 'user_id': user_id}
1755 data.update(kwargs)
1756
1757 result = self._request.post(url, data, timeout=timeout)
1758
1759 return result
1760
1761 @log
1762 def answer_callback_query(self,
1763 callback_query_id,
1764 text=None,
1765 show_alert=False,
1766 url=None,
1767 cache_time=None,
1768 timeout=None,
1769 **kwargs):
1770 """
1771 Use this method to send answers to callback queries sent from inline keyboards. The answer
1772 will be displayed to the user as a notification at the top of the chat screen or as an
1773 alert.
1774 Alternatively, the user can be redirected to the specified Game URL. For this option to
1775 work, you must first create a game for your bot via BotFather and accept the terms.
1776 Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with
1777 a parameter.
1778
1779 Args:
1780 callback_query_id (:obj:`str`): Unique identifier for the query to be answered.
1781 text (:obj:`str`, optional): Text of the notification. If not specified, nothing will
1782 be shown to the user, 0-200 characters.
1783 show_alert (:obj:`bool`, optional): If true, an alert will be shown by the client
1784 instead of a notification at the top of the chat screen. Defaults to false.
1785 url (:obj:`str`, optional): URL that will be opened by the user's client. If you have
1786 created a Game and accepted the conditions via @Botfather, specify the URL that
1787 opens your game - note that this will only work if the query comes from a callback
1788 game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open
1789 your bot with a parameter.
1790 cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the
1791 result of the callback query may be cached client-side. Defaults to 0.
1792 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1793 the read timeout from the server (instead of the one specified during creation of
1794 the connection pool).
1795 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1796
1797 Returns:
1798 :obj:`bool` On success, ``True`` is returned.
1799
1800 Raises:
1801 :class:`telegram.TelegramError`
1802
1803 """
1804 url_ = '{0}/answerCallbackQuery'.format(self.base_url)
1805
1806 data = {'callback_query_id': callback_query_id}
1807
1808 if text:
1809 data['text'] = text
1810 if show_alert:
1811 data['show_alert'] = show_alert
1812 if url:
1813 data['url'] = url
1814 if cache_time is not None:
1815 data['cache_time'] = cache_time
1816 data.update(kwargs)
1817
1818 result = self._request.post(url_, data, timeout=timeout)
1819
1820 return result
1821
1822 @log
1823 def edit_message_text(self,
1824 text,
1825 chat_id=None,
1826 message_id=None,
1827 inline_message_id=None,
1828 parse_mode=None,
1829 disable_web_page_preview=None,
1830 reply_markup=None,
1831 timeout=None,
1832 **kwargs):
1833 """
1834 Use this method to edit text and game messages sent by the bot or via the bot (for inline
1835 bots).
1836
1837 Args:
1838 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
1839 specified. Unique identifier for the target chat or username of the target channel
1840 (in the format @channelusername)
1841 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
1842 Identifier of the message to edit.
1843 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
1844 specified. Identifier of the inline message.
1845 text (:obj:`str`): New text of the message, 1-4096 characters after entities parsing.
1846 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
1847 show bold, italic, fixed-width text or inline URLs in your bot's message. See the
1848 constants in :class:`telegram.ParseMode` for the available modes.
1849 disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in
1850 this message.
1851 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1852 object for an inline keyboard.
1853 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1854 the read timeout from the server (instead of the one specified during creation of
1855 the connection pool).
1856 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1857
1858 Returns:
1859 :class:`telegram.Message`: On success, if edited message is sent by the bot, the
1860 edited Message is returned, otherwise ``True`` is returned.
1861
1862 Raises:
1863 :class:`telegram.TelegramError`
1864
1865 """
1866 url = '{0}/editMessageText'.format(self.base_url)
1867
1868 data = {'text': text}
1869
1870 if chat_id:
1871 data['chat_id'] = chat_id
1872 if message_id:
1873 data['message_id'] = message_id
1874 if inline_message_id:
1875 data['inline_message_id'] = inline_message_id
1876 if parse_mode:
1877 data['parse_mode'] = parse_mode
1878 if disable_web_page_preview:
1879 data['disable_web_page_preview'] = disable_web_page_preview
1880
1881 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
1882
1883 @log
1884 def edit_message_caption(self,
1885 chat_id=None,
1886 message_id=None,
1887 inline_message_id=None,
1888 caption=None,
1889 reply_markup=None,
1890 timeout=None,
1891 parse_mode=None,
1892 **kwargs):
1893 """
1894 Use this method to edit captions of messages sent by the bot or via the bot
1895 (for inline bots).
1896
1897 Args:
1898 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
1899 specified. Unique identifier for the target chat or username of the target channel
1900 (in the format @channelusername)
1901 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
1902 Identifier of the message to edit.
1903 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
1904 specified. Identifier of the inline message.
1905 caption (:obj:`str`, optional): New caption of the message, 0-1024 characters after
1906 entities parsing.
1907 parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
1908 show bold, italic, fixed-width text or inline URLs in the media caption. See the
1909 constants in :class:`telegram.ParseMode` for the available modes.
1910 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1911 object for an inline keyboard.
1912 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1913 the read timeout from the server (instead of the one specified during creation of
1914 the connection pool).
1915 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1916
1917 Returns:
1918 :class:`telegram.Message`: On success, if edited message is sent by the bot, the
1919 edited Message is returned, otherwise ``True`` is returned.
1920
1921 Raises:
1922 :class:`telegram.TelegramError`
1923
1924 """
1925 if inline_message_id is None and (chat_id is None or message_id is None):
1926 raise ValueError(
1927 'edit_message_caption: Both chat_id and message_id are required when '
1928 'inline_message_id is not specified')
1929
1930 url = '{0}/editMessageCaption'.format(self.base_url)
1931
1932 data = {}
1933
1934 if caption:
1935 data['caption'] = caption
1936 if parse_mode:
1937 data['parse_mode'] = parse_mode
1938 if chat_id:
1939 data['chat_id'] = chat_id
1940 if message_id:
1941 data['message_id'] = message_id
1942 if inline_message_id:
1943 data['inline_message_id'] = inline_message_id
1944
1945 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
1946
1947 @log
1948 def edit_message_media(self,
1949 chat_id=None,
1950 message_id=None,
1951 inline_message_id=None,
1952 media=None,
1953 reply_markup=None,
1954 timeout=None,
1955 **kwargs):
1956 """
1957 Use this method to edit animation, audio, document, photo, or video messages. If a
1958 message is a part of a message album, then it can be edited only to a photo or a video.
1959 Otherwise, message type can be changed arbitrarily. When inline message is edited,
1960 new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL.
1961
1962 Args:
1963 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
1964 specified. Unique identifier for the target chat or username of the target channel
1965 (in the format @channelusername).
1966 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
1967 Identifier of the message to edit.
1968 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
1969 specified. Identifier of the inline message.
1970 media (:class:`telegram.InputMedia`): An object for a new media content
1971 of the message.
1972 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
1973 object for an inline keyboard.
1974 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
1975 the read timeout from the server (instead of the one specified during creation of
1976 the connection pool).
1977 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
1978
1979 Returns:
1980 :class:`telegram.Message`: On success, if edited message is sent by the bot, the
1981 edited Message is returned, otherwise ``True`` is returned.
1982
1983 Raises:
1984 :class:`telegram.TelegramError`
1985 """
1986
1987 if inline_message_id is None and (chat_id is None or message_id is None):
1988 raise ValueError(
1989 'edit_message_media: Both chat_id and message_id are required when '
1990 'inline_message_id is not specified')
1991
1992 url = '{0}/editMessageMedia'.format(self.base_url)
1993
1994 data = {'media': media}
1995
1996 if chat_id:
1997 data['chat_id'] = chat_id
1998 if message_id:
1999 data['message_id'] = message_id
2000 if inline_message_id:
2001 data['inline_message_id'] = inline_message_id
2002
2003 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
2004
2005 @log
2006 def edit_message_reply_markup(self,
2007 chat_id=None,
2008 message_id=None,
2009 inline_message_id=None,
2010 reply_markup=None,
2011 timeout=None,
2012 **kwargs):
2013 """
2014 Use this method to edit only the reply markup of messages sent by the bot or via the bot
2015 (for inline bots).
2016
2017 Args:
2018 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
2019 specified. Unique identifier for the target chat or username of the target channel
2020 (in the format @channelusername).
2021 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
2022 Identifier of the message to edit.
2023 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
2024 specified. Identifier of the inline message.
2025 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
2026 object for an inline keyboard.
2027 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2028 the read timeout from the server (instead of the one specified during creation of
2029 the connection pool).
2030 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2031
2032 Returns:
2033 :class:`telegram.Message`: On success, if edited message is sent by the bot, the
2034 editedMessage is returned, otherwise ``True`` is returned.
2035
2036 Raises:
2037 :class:`telegram.TelegramError`
2038
2039 """
2040 if inline_message_id is None and (chat_id is None or message_id is None):
2041 raise ValueError(
2042 'edit_message_reply_markup: Both chat_id and message_id are required when '
2043 'inline_message_id is not specified')
2044
2045 url = '{0}/editMessageReplyMarkup'.format(self.base_url)
2046
2047 data = {}
2048
2049 if chat_id:
2050 data['chat_id'] = chat_id
2051 if message_id:
2052 data['message_id'] = message_id
2053 if inline_message_id:
2054 data['inline_message_id'] = inline_message_id
2055
2056 return self._message(url, data, timeout=timeout, reply_markup=reply_markup, **kwargs)
2057
2058 @log
2059 def get_updates(self,
2060 offset=None,
2061 limit=100,
2062 timeout=0,
2063 read_latency=2.,
2064 allowed_updates=None,
2065 **kwargs):
2066 """Use this method to receive incoming updates using long polling.
2067
2068 Args:
2069 offset (:obj:`int`, optional): Identifier of the first update to be returned. Must be
2070 greater by one than the highest among the identifiers of previously received
2071 updates. By default, updates starting with the earliest unconfirmed update are
2072 returned. An update is considered confirmed as soon as getUpdates is called with an
2073 offset higher than its update_id. The negative offset can be specified to retrieve
2074 updates starting from -offset update from the end of the updates queue. All
2075 previous updates will forgotten.
2076 limit (:obj:`int`, optional): Limits the number of updates to be retrieved. Values
2077 between 1-100 are accepted. Defaults to 100.
2078 timeout (:obj:`int`, optional): Timeout in seconds for long polling. Defaults to 0,
2079 i.e. usual short polling. Should be positive, short polling should be used for
2080 testing purposes only.
2081 allowed_updates (List[:obj:`str`]), optional): A JSON-serialized list the types of
2082 updates you want your bot to receive. For example, specify ["message",
2083 "edited_channel_post", "callback_query"] to only receive updates of these types.
2084 See :class:`telegram.Update` for a complete list of available update types.
2085 Specify an empty list to receive all updates regardless of type (default). If not
2086 specified, the previous setting will be used. Please note that this parameter
2087 doesn't affect updates created before the call to the get_updates, so unwanted
2088 updates may be received for a short period of time.
2089 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2090
2091 Notes:
2092 1. This method will not work if an outgoing webhook is set up.
2093 2. In order to avoid getting duplicate updates, recalculate offset after each
2094 server response.
2095 3. To take full advantage of this library take a look at :class:`telegram.ext.Updater`
2096
2097 Returns:
2098 List[:class:`telegram.Update`]
2099
2100 Raises:
2101 :class:`telegram.TelegramError`
2102
2103 """
2104 url = '{0}/getUpdates'.format(self.base_url)
2105
2106 data = {'timeout': timeout}
2107
2108 if offset:
2109 data['offset'] = offset
2110 if limit:
2111 data['limit'] = limit
2112 if allowed_updates is not None:
2113 data['allowed_updates'] = allowed_updates
2114 data.update(kwargs)
2115
2116 # Ideally we'd use an aggressive read timeout for the polling. However,
2117 # * Short polling should return within 2 seconds.
2118 # * Long polling poses a different problem: the connection might have been dropped while
2119 # waiting for the server to return and there's no way of knowing the connection had been
2120 # dropped in real time.
2121 result = self._request.post(url, data, timeout=float(read_latency) + float(timeout))
2122
2123 if result:
2124 self.logger.debug('Getting updates: %s', [u['update_id'] for u in result])
2125 else:
2126 self.logger.debug('No new updates found.')
2127
2128 if self.defaults:
2129 for u in result:
2130 u['default_quote'] = self.defaults.quote
2131
2132 return [Update.de_json(u, self) for u in result]
2133
2134 @log
2135 def set_webhook(self,
2136 url=None,
2137 certificate=None,
2138 timeout=None,
2139 max_connections=40,
2140 allowed_updates=None,
2141 **kwargs):
2142 """
2143 Use this method to specify a url and receive incoming updates via an outgoing webhook.
2144 Whenever there is an update for the bot, we will send an HTTPS POST request to the
2145 specified url, containing a JSON-serialized Update. In case of an unsuccessful request,
2146 we will give up after a reasonable amount of attempts.
2147
2148 If you'd like to make sure that the Webhook request comes from Telegram, we recommend
2149 using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else
2150 knows your bot's token, you can be pretty sure it's us.
2151
2152 Note:
2153 The certificate argument should be a file from disk ``open(filename, 'rb')``.
2154
2155 Args:
2156 url (:obj:`str`): HTTPS url to send updates to. Use an empty string to remove webhook
2157 integration.
2158 certificate (:obj:`filelike`): Upload your public key certificate so that the root
2159 certificate in use can be checked. See our self-signed guide for details.
2160 (https://goo.gl/rw7w6Y)
2161 max_connections (:obj:`int`, optional): Maximum allowed number of simultaneous HTTPS
2162 connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower
2163 values to limit the load on your bot's server, and higher values to increase your
2164 bot's throughput.
2165 allowed_updates (List[:obj:`str`], optional): A JSON-serialized list the types of
2166 updates you want your bot to receive. For example, specify ["message",
2167 "edited_channel_post", "callback_query"] to only receive updates of these types.
2168 See :class:`telegram.Update` for a complete list of available update types.
2169 Specify an empty list to receive all updates regardless of type (default). If not
2170 specified, the previous setting will be used. Please note that this parameter
2171 doesn't affect updates created before the call to the set_webhook, so unwanted
2172 updates may be received for a short period of time.
2173 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2174 the read timeout from the server (instead of the one specified during creation of
2175 the connection pool).
2176 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2177
2178 Note:
2179 1. You will not be able to receive updates using get_updates for as long as an outgoing
2180 webhook is set up.
2181 2. To use a self-signed certificate, you need to upload your public key certificate
2182 using certificate parameter. Please upload as InputFile, sending a String will not
2183 work.
2184 3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
2185
2186 If you're having any trouble setting up webhooks, please check out this `guide to
2187 Webhooks`_.
2188
2189 Returns:
2190 :obj:`bool` On success, ``True`` is returned.
2191
2192 Raises:
2193 :class:`telegram.TelegramError`
2194
2195 .. _`guide to Webhooks`: https://core.telegram.org/bots/webhooks
2196
2197 """
2198 url_ = '{0}/setWebhook'.format(self.base_url)
2199
2200 # Backwards-compatibility: 'url' used to be named 'webhook_url'
2201 if 'webhook_url' in kwargs: # pragma: no cover
2202 warnings.warn("The 'webhook_url' parameter has been renamed to 'url' in accordance "
2203 "with the API")
2204
2205 if url is not None:
2206 raise ValueError("The parameters 'url' and 'webhook_url' are mutually exclusive")
2207
2208 url = kwargs['webhook_url']
2209 del kwargs['webhook_url']
2210
2211 data = {}
2212
2213 if url is not None:
2214 data['url'] = url
2215 if certificate:
2216 if InputFile.is_file(certificate):
2217 certificate = InputFile(certificate)
2218 data['certificate'] = certificate
2219 if max_connections is not None:
2220 data['max_connections'] = max_connections
2221 if allowed_updates is not None:
2222 data['allowed_updates'] = allowed_updates
2223 data.update(kwargs)
2224
2225 result = self._request.post(url_, data, timeout=timeout)
2226
2227 return result
2228
2229 @log
2230 def delete_webhook(self, timeout=None, **kwargs):
2231 """
2232 Use this method to remove webhook integration if you decide to switch back to
2233 getUpdates. Requires no parameters.
2234
2235 Args:
2236 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2237 the read timeout from the server (instead of the one specified during creation of
2238 the connection pool).
2239 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2240
2241 Returns:
2242 :obj:`bool` On success, ``True`` is returned.
2243
2244 Raises:
2245 :class:`telegram.TelegramError`
2246
2247 """
2248 url = '{0}/deleteWebhook'.format(self.base_url)
2249
2250 data = kwargs
2251
2252 result = self._request.post(url, data, timeout=timeout)
2253
2254 return result
2255
2256 @log
2257 def leave_chat(self, chat_id, timeout=None, **kwargs):
2258 """Use this method for your bot to leave a group, supergroup or channel.
2259
2260 Args:
2261 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2262 of the target channel (in the format @channelusername).
2263 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2264 the read timeout from the server (instead of the one specified during creation of
2265 the connection pool).
2266 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2267
2268 Returns:
2269 :obj:`bool` On success, ``True`` is returned.
2270
2271 Raises:
2272 :class:`telegram.TelegramError`
2273
2274 """
2275 url = '{0}/leaveChat'.format(self.base_url)
2276
2277 data = {'chat_id': chat_id}
2278 data.update(kwargs)
2279
2280 result = self._request.post(url, data, timeout=timeout)
2281
2282 return result
2283
2284 @log
2285 def get_chat(self, chat_id, timeout=None, **kwargs):
2286 """
2287 Use this method to get up to date information about the chat (current name of the user for
2288 one-on-one conversations, current username of a user, group or channel, etc.).
2289
2290 Args:
2291 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2292 of the target channel (in the format @channelusername).
2293 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2294 the read timeout from the server (instead of the one specified during creation of
2295 the connection pool).
2296 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2297
2298 Returns:
2299 :class:`telegram.Chat`
2300
2301 Raises:
2302 :class:`telegram.TelegramError`
2303
2304 """
2305 url = '{0}/getChat'.format(self.base_url)
2306
2307 data = {'chat_id': chat_id}
2308 data.update(kwargs)
2309
2310 result = self._request.post(url, data, timeout=timeout)
2311
2312 if self.defaults:
2313 result['default_quote'] = self.defaults.quote
2314
2315 return Chat.de_json(result, self)
2316
2317 @log
2318 def get_chat_administrators(self, chat_id, timeout=None, **kwargs):
2319 """
2320 Use this method to get a list of administrators in a chat. On success, returns an Array of
2321 ChatMember objects that contains information about all chat administrators except other
2322 bots. If the chat is a group or a supergroup and no administrators were appointed,
2323 only the creator will be returned.
2324
2325 Args:
2326 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2327 of the target channel (in the format @channelusername).
2328 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2329 the read timeout from the server (instead of the one specified during creation of
2330 the connection pool).
2331 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2332
2333 Returns:
2334 List[:class:`telegram.ChatMember`]
2335
2336 Raises:
2337 :class:`telegram.TelegramError`
2338
2339 """
2340 url = '{0}/getChatAdministrators'.format(self.base_url)
2341
2342 data = {'chat_id': chat_id}
2343 data.update(kwargs)
2344
2345 result = self._request.post(url, data, timeout=timeout)
2346
2347 return [ChatMember.de_json(x, self) for x in result]
2348
2349 @log
2350 def get_chat_members_count(self, chat_id, timeout=None, **kwargs):
2351 """Use this method to get the number of members in a chat.
2352
2353 Args:
2354 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2355 of the target channel (in the format @channelusername).
2356 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2357 the read timeout from the server (instead of the one specified during creation of
2358 the connection pool).
2359 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2360
2361 Returns:
2362 int: Number of members in the chat.
2363
2364 Raises:
2365 :class:`telegram.TelegramError`
2366
2367 """
2368 url = '{0}/getChatMembersCount'.format(self.base_url)
2369
2370 data = {'chat_id': chat_id}
2371 data.update(kwargs)
2372
2373 result = self._request.post(url, data, timeout=timeout)
2374
2375 return result
2376
2377 @log
2378 def get_chat_member(self, chat_id, user_id, timeout=None, **kwargs):
2379 """Use this method to get information about a member of a chat.
2380
2381 Args:
2382 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2383 of the target channel (in the format @channelusername).
2384 user_id (:obj:`int`): Unique identifier of the target user.
2385 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2386 the read timeout from the server (instead of the one specified during creation of
2387 the connection pool).
2388 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2389
2390 Returns:
2391 :class:`telegram.ChatMember`
2392
2393 Raises:
2394 :class:`telegram.TelegramError`
2395
2396 """
2397 url = '{0}/getChatMember'.format(self.base_url)
2398
2399 data = {'chat_id': chat_id, 'user_id': user_id}
2400 data.update(kwargs)
2401
2402 result = self._request.post(url, data, timeout=timeout)
2403
2404 return ChatMember.de_json(result, self)
2405
2406 @log
2407 def set_chat_sticker_set(self, chat_id, sticker_set_name, timeout=None, **kwargs):
2408 """Use this method to set a new group sticker set for a supergroup.
2409 The bot must be an administrator in the chat for this to work and must have the appropriate
2410 admin rights. Use the field :attr:`telegram.Chat.can_set_sticker_set` optionally returned
2411 in :attr:`get_chat` requests to check if the bot can use this method.
2412
2413 Args:
2414 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2415 of the target supergroup (in the format @supergroupusername).
2416 sticker_set_name (:obj:`str`): Name of the sticker set to be set as the group
2417 sticker set.
2418 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2419 the read timeout from the server (instead of the one specified during creation of
2420 the connection pool).
2421 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2422
2423
2424 Returns:
2425 :obj:`bool`: True on success.
2426 """
2427
2428 url = '{0}/setChatStickerSet'.format(self.base_url)
2429
2430 data = {'chat_id': chat_id, 'sticker_set_name': sticker_set_name}
2431
2432 result = self._request.post(url, data, timeout=timeout)
2433
2434 return result
2435
2436 @log
2437 def delete_chat_sticker_set(self, chat_id, timeout=None, **kwargs):
2438 """Use this method to delete a group sticker set from a supergroup. The bot must be an
2439 administrator in the chat for this to work and must have the appropriate admin rights.
2440 Use the field :attr:`telegram.Chat.can_set_sticker_set` optionally returned in
2441 :attr:`get_chat` requests to check if the bot can use this method.
2442
2443 Args:
2444 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2445 of the target supergroup (in the format @supergroupusername).
2446 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2447 the read timeout from the server (instead of the one specified during creation of
2448 the connection pool).
2449 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2450
2451 Returns:
2452 :obj:`bool`: True on success.
2453 """
2454
2455 url = '{0}/deleteChatStickerSet'.format(self.base_url)
2456
2457 data = {'chat_id': chat_id}
2458
2459 result = self._request.post(url, data, timeout=timeout)
2460
2461 return result
2462
2463 def get_webhook_info(self, timeout=None, **kwargs):
2464 """Use this method to get current webhook status. Requires no parameters.
2465
2466 If the bot is using getUpdates, will return an object with the url field empty.
2467
2468 Args:
2469 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2470 the read timeout from the server (instead of the one specified during creation of
2471 the connection pool).
2472 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2473
2474 Returns:
2475 :class:`telegram.WebhookInfo`
2476
2477 """
2478 url = '{0}/getWebhookInfo'.format(self.base_url)
2479
2480 data = kwargs
2481
2482 result = self._request.post(url, data, timeout=timeout)
2483
2484 return WebhookInfo.de_json(result, self)
2485
2486 @log
2487 def set_game_score(self,
2488 user_id,
2489 score,
2490 chat_id=None,
2491 message_id=None,
2492 inline_message_id=None,
2493 force=None,
2494 disable_edit_message=None,
2495 timeout=None,
2496 **kwargs):
2497 """
2498 Use this method to set the score of the specified user in a game. On success, if the
2499 message was sent by the bot, returns the edited Message, otherwise returns True. Returns
2500 an error, if the new score is not greater than the user's current score in the chat and
2501 force is False.
2502
2503 Args:
2504 user_id (:obj:`int`): User identifier.
2505 score (:obj:`int`): New score, must be non-negative.
2506 force (:obj:`bool`, optional): Pass True, if the high score is allowed to decrease.
2507 This can be useful when fixing mistakes or banning cheaters.
2508 disable_edit_message (:obj:`bool`, optional): Pass True, if the game message should not
2509 be automatically edited to include the current scoreboard.
2510 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
2511 specified. Unique identifier for the target chat.
2512 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
2513 Identifier of the sent message.
2514 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
2515 specified. Identifier of the inline message.
2516 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2517 the read timeout from the server (instead of the one specified during creation of
2518 the connection pool).
2519 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2520
2521 Returns:
2522 :class:`telegram.Message`: The edited message, or if the message wasn't sent by the bot
2523 , ``True``.
2524
2525 Raises:
2526 :class:`telegram.TelegramError`: If the new score is not greater than the user's
2527 current score in the chat and force is False.
2528
2529 """
2530 url = '{0}/setGameScore'.format(self.base_url)
2531
2532 data = {'user_id': user_id, 'score': score}
2533
2534 if chat_id:
2535 data['chat_id'] = chat_id
2536 if message_id:
2537 data['message_id'] = message_id
2538 if inline_message_id:
2539 data['inline_message_id'] = inline_message_id
2540 if force is not None:
2541 data['force'] = force
2542 if disable_edit_message is not None:
2543 data['disable_edit_message'] = disable_edit_message
2544
2545 return self._message(url, data, timeout=timeout, **kwargs)
2546
2547 @log
2548 def get_game_high_scores(self,
2549 user_id,
2550 chat_id=None,
2551 message_id=None,
2552 inline_message_id=None,
2553 timeout=None,
2554 **kwargs):
2555 """
2556 Use this method to get data for high score tables. Will return the score of the specified
2557 user and several of his neighbors in a game.
2558
2559 Args:
2560 user_id (:obj:`int`): Target user id.
2561 chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
2562 specified. Unique identifier for the target chat.
2563 message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
2564 Identifier of the sent message.
2565 inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
2566 specified. Identifier of the inline message.
2567 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2568 the read timeout from the server (instead of the one specified during creation of
2569 the connection pool).
2570 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2571
2572 Returns:
2573 List[:class:`telegram.GameHighScore`]
2574
2575 Raises:
2576 :class:`telegram.TelegramError`
2577
2578 """
2579 url = '{0}/getGameHighScores'.format(self.base_url)
2580
2581 data = {'user_id': user_id}
2582
2583 if chat_id:
2584 data['chat_id'] = chat_id
2585 if message_id:
2586 data['message_id'] = message_id
2587 if inline_message_id:
2588 data['inline_message_id'] = inline_message_id
2589 data.update(kwargs)
2590
2591 result = self._request.post(url, data, timeout=timeout)
2592
2593 return [GameHighScore.de_json(hs, self) for hs in result]
2594
2595 @log
2596 def send_invoice(self,
2597 chat_id,
2598 title,
2599 description,
2600 payload,
2601 provider_token,
2602 start_parameter,
2603 currency,
2604 prices,
2605 photo_url=None,
2606 photo_size=None,
2607 photo_width=None,
2608 photo_height=None,
2609 need_name=None,
2610 need_phone_number=None,
2611 need_email=None,
2612 need_shipping_address=None,
2613 is_flexible=None,
2614 disable_notification=False,
2615 reply_to_message_id=None,
2616 reply_markup=None,
2617 provider_data=None,
2618 send_phone_number_to_provider=None,
2619 send_email_to_provider=None,
2620 timeout=None,
2621 **kwargs):
2622 """Use this method to send invoices.
2623
2624 Args:
2625 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target private chat.
2626 title (:obj:`str`): Product name, 1-32 characters.
2627 description (:obj:`str`): Product description, 1-255 characters.
2628 payload (:obj:`str`): Bot-defined invoice payload, 1-128 bytes. This will not be
2629 displayed to the user, use for your internal processes.
2630 provider_token (:obj:`str`): Payments provider token, obtained via Botfather.
2631 start_parameter (:obj:`str`): Unique deep-linking parameter that can be used to
2632 generate this invoice when used as a start parameter.
2633 currency (:obj:`str`): Three-letter ISO 4217 currency code.
2634 prices (List[:class:`telegram.LabeledPrice`)]: Price breakdown, a JSON-serialized list
2635 of components (e.g. product price, tax, discount, delivery cost, delivery tax,
2636 bonus, etc.).
2637 provider_data (:obj:`str` | :obj:`object`, optional): JSON-encoded data about the
2638 invoice, which will be shared with the payment provider. A detailed description of
2639 required fields should be provided by the payment provider. When an object is
2640 passed, it will be encoded as JSON.
2641 photo_url (:obj:`str`, optional): URL of the product photo for the invoice. Can be a
2642 photo of the goods or a marketing image for a service. People like it better when
2643 they see what they are paying for.
2644 photo_size (:obj:`str`, optional): Photo size.
2645 photo_width (:obj:`int`, optional): Photo width.
2646 photo_height (:obj:`int`, optional): Photo height.
2647 need_name (:obj:`bool`, optional): Pass True, if you require the user's full name to
2648 complete the order.
2649 need_phone_number (:obj:`bool`, optional): Pass True, if you require the user's
2650 phone number to complete the order.
2651 need_email (:obj:`bool`, optional): Pass True, if you require the user's email to
2652 complete the order.
2653 need_shipping_address (:obj:`bool`, optional): Pass True, if you require the user's
2654 shipping address to complete the order.
2655 send_phone_number_to_provider (:obj:`bool`, optional): Pass True, if user's phone
2656 number should be sent to provider.
2657 send_email_to_provider (:obj:`bool`, optional): Pass True, if user's email address
2658 should be sent to provider.
2659 is_flexible (:obj:`bool`, optional): Pass True, if the final price depends on the
2660 shipping method.
2661 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
2662 receive a notification with no sound.
2663 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
2664 original message.
2665 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): A JSON-serialized
2666 object for an inline keyboard. If empty, one 'Pay total price' button will be
2667 shown. If not empty, the first button must be a Pay button.
2668 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2669 the read timeout from the server (instead of the one specified during creation of
2670 the connection pool).
2671 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2672
2673 Returns:
2674 :class:`telegram.Message`: On success, the sent Message is returned.
2675
2676 Raises:
2677 :class:`telegram.TelegramError`
2678
2679 """
2680 url = '{0}/sendInvoice'.format(self.base_url)
2681
2682 data = {
2683 'chat_id': chat_id,
2684 'title': title,
2685 'description': description,
2686 'payload': payload,
2687 'provider_token': provider_token,
2688 'start_parameter': start_parameter,
2689 'currency': currency,
2690 'prices': [p.to_dict() for p in prices]
2691 }
2692 if provider_data is not None:
2693 if isinstance(provider_data, string_types):
2694 data['provider_data'] = provider_data
2695 else:
2696 data['provider_data'] = json.dumps(provider_data)
2697 if photo_url is not None:
2698 data['photo_url'] = photo_url
2699 if photo_size is not None:
2700 data['photo_size'] = photo_size
2701 if photo_width is not None:
2702 data['photo_width'] = photo_width
2703 if photo_height is not None:
2704 data['photo_height'] = photo_height
2705 if need_name is not None:
2706 data['need_name'] = need_name
2707 if need_phone_number is not None:
2708 data['need_phone_number'] = need_phone_number
2709 if need_email is not None:
2710 data['need_email'] = need_email
2711 if need_shipping_address is not None:
2712 data['need_shipping_address'] = need_shipping_address
2713 if is_flexible is not None:
2714 data['is_flexible'] = is_flexible
2715 if send_phone_number_to_provider is not None:
2716 data['send_phone_number_to_provider'] = send_email_to_provider
2717 if send_email_to_provider is not None:
2718 data['send_email_to_provider'] = send_email_to_provider
2719
2720 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
2721 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
2722 **kwargs)
2723
2724 @log
2725 def answer_shipping_query(self,
2726 shipping_query_id,
2727 ok,
2728 shipping_options=None,
2729 error_message=None,
2730 timeout=None,
2731 **kwargs):
2732 """
2733 If you sent an invoice requesting a shipping address and the parameter is_flexible was
2734 specified, the Bot API will send an Update with a shipping_query field to the bot. Use
2735 this method to reply to shipping queries.
2736
2737 Args:
2738 shipping_query_id (:obj:`str`): Unique identifier for the query to be answered.
2739 ok (:obj:`bool`): Specify True if delivery to the specified address is possible and
2740 False if there are any problems (for example, if delivery to the specified address
2741 is not possible).
2742 shipping_options (List[:class:`telegram.ShippingOption`]), optional]: Required if ok is
2743 True. A JSON-serialized array of available shipping options.
2744 error_message (:obj:`str`, optional): Required if ok is False. Error message in
2745 human readable form that explains why it is impossible to complete the order (e.g.
2746 "Sorry, delivery to your desired address is unavailable"). Telegram will display
2747 this message to the user.
2748 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2749 the read timeout from the server (instead of the one specified during creation of
2750 the connection pool).
2751 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2752
2753 Returns:
2754 :obj:`bool`; On success, True is returned.
2755
2756 Raises:
2757 :class:`telegram.TelegramError`
2758
2759 """
2760 ok = bool(ok)
2761
2762 if ok and (shipping_options is None or error_message is not None):
2763 raise TelegramError(
2764 'answerShippingQuery: If ok is True, shipping_options '
2765 'should not be empty and there should not be error_message')
2766
2767 if not ok and (shipping_options is not None or error_message is None):
2768 raise TelegramError(
2769 'answerShippingQuery: If ok is False, error_message '
2770 'should not be empty and there should not be shipping_options')
2771
2772 url_ = '{0}/answerShippingQuery'.format(self.base_url)
2773
2774 data = {'shipping_query_id': shipping_query_id, 'ok': ok}
2775
2776 if ok:
2777 data['shipping_options'] = [option.to_dict() for option in shipping_options]
2778 if error_message is not None:
2779 data['error_message'] = error_message
2780 data.update(kwargs)
2781
2782 result = self._request.post(url_, data, timeout=timeout)
2783
2784 return result
2785
2786 @log
2787 def answer_pre_checkout_query(self, pre_checkout_query_id, ok,
2788 error_message=None, timeout=None, **kwargs):
2789 """
2790 Once the user has confirmed their payment and shipping details, the Bot API sends the final
2791 confirmation in the form of an Update with the field pre_checkout_query. Use this method to
2792 respond to such pre-checkout queries.
2793
2794 Note:
2795 The Bot API must receive an answer within 10 seconds after the pre-checkout
2796 query was sent.
2797
2798 Args:
2799 pre_checkout_query_id (:obj:`str`): Unique identifier for the query to be answered.
2800 ok (:obj:`bool`): Specify True if everything is alright (goods are available, etc.) and
2801 the bot is ready to proceed with the order. Use False if there are any problems.
2802 error_message (:obj:`str`, optional): Required if ok is False. Error message in human
2803 readable form that explains the reason for failure to proceed with the checkout
2804 (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you
2805 were busy filling out your payment details. Please choose a different color or
2806 garment!"). Telegram will display this message to the user.
2807 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2808 the read timeout from the server (instead of the one specified during creation of
2809 the connection pool).
2810 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
2811
2812 Returns:
2813 :obj:`bool`: On success, ``True`` is returned.
2814
2815 Raises:
2816 :class:`telegram.TelegramError`
2817
2818 """
2819 ok = bool(ok)
2820
2821 if not (ok ^ (error_message is not None)):
2822 raise TelegramError(
2823 'answerPreCheckoutQuery: If ok is True, there should '
2824 'not be error_message; if ok is False, error_message '
2825 'should not be empty')
2826
2827 url_ = '{0}/answerPreCheckoutQuery'.format(self.base_url)
2828
2829 data = {'pre_checkout_query_id': pre_checkout_query_id, 'ok': ok}
2830
2831 if error_message is not None:
2832 data['error_message'] = error_message
2833 data.update(kwargs)
2834
2835 result = self._request.post(url_, data, timeout=timeout)
2836
2837 return result
2838
2839 @log
2840 def restrict_chat_member(self, chat_id, user_id, permissions, until_date=None,
2841 timeout=None, **kwargs):
2842 """
2843 Use this method to restrict a user in a supergroup. The bot must be an administrator in
2844 the supergroup for this to work and must have the appropriate admin rights. Pass True for
2845 all boolean parameters to lift restrictions from a user.
2846
2847 Note:
2848 Since Bot API 4.4, :attr:`restrict_chat_member` takes the new user permissions in a
2849 single argument of type :class:`telegram.ChatPermissions`. The old way of passing
2850 parameters will not keep working forever.
2851
2852 Args:
2853 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2854 of the target supergroup (in the format @supergroupusername).
2855 user_id (:obj:`int`): Unique identifier of the target user.
2856 until_date (:obj:`int` | :obj:`datetime.datetime`, optional): Date when restrictions
2857 will be lifted for the user, unix time. If user is restricted for more than 366
2858 days or less than 30 seconds from the current time, they are considered to be
2859 restricted forever.
2860 permissions (:class:`telegram.ChatPermissions`): New user permissions.
2861 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2862 the read timeout from the server (instead of the one specified during creation of
2863 the connection pool).
2864 **kwargs (:obj:`dict`): Arbitrary keyword arguments
2865
2866 Returns:
2867 :obj:`bool`: Returns True on success.
2868
2869 Raises:
2870 :class:`telegram.TelegramError`
2871 """
2872 url = '{0}/restrictChatMember'.format(self.base_url)
2873
2874 data = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions.to_dict()}
2875
2876 if until_date is not None:
2877 if isinstance(until_date, datetime):
2878 until_date = to_timestamp(until_date)
2879 data['until_date'] = until_date
2880 data.update(kwargs)
2881
2882 result = self._request.post(url, data, timeout=timeout)
2883
2884 return result
2885
2886 @log
2887 def promote_chat_member(self, chat_id, user_id, can_change_info=None,
2888 can_post_messages=None, can_edit_messages=None,
2889 can_delete_messages=None, can_invite_users=None,
2890 can_restrict_members=None, can_pin_messages=None,
2891 can_promote_members=None, timeout=None, **kwargs):
2892 """
2893 Use this method to promote or demote a user in a supergroup or a channel. The bot must be
2894 an administrator in the chat for this to work and must have the appropriate admin rights.
2895 Pass False for all boolean parameters to demote a user.
2896
2897 Args:
2898 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
2899 of the target supergroup (in the format @supergroupusername).
2900 user_id (:obj:`int`): Unique identifier of the target user.
2901 can_change_info (:obj:`bool`, optional): Pass True, if the administrator can change
2902 chat title, photo and other settings.
2903 can_post_messages (:obj:`bool`, optional): Pass True, if the administrator can
2904 create channel posts, channels only.
2905 can_edit_messages (:obj:`bool`, optional): Pass True, if the administrator can edit
2906 messages of other users, channels only.
2907 can_delete_messages (:obj:`bool`, optional): Pass True, if the administrator can
2908 delete messages of other users.
2909 can_invite_users (:obj:`bool`, optional): Pass True, if the administrator can invite
2910 new users to the chat.
2911 can_restrict_members (:obj:`bool`, optional): Pass True, if the administrator can
2912 restrict, ban or unban chat members.
2913 can_pin_messages (:obj:`bool`, optional): Pass True, if the administrator can pin
2914 messages, supergroups only.
2915 can_promote_members (:obj:`bool`, optional): Pass True, if the administrator can add
2916 new administrators with a subset of his own privileges or demote administrators
2917 that he has promoted, directly or indirectly (promoted by administrators that were
2918 appointed by him).
2919 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2920 the read timeout from the server (instead of the one specified during creation of
2921 the connection pool).
2922 **kwargs (:obj:`dict`): Arbitrary keyword arguments
2923
2924 Returns:
2925 :obj:`bool`: Returns True on success.
2926
2927 Raises:
2928 :class:`telegram.TelegramError`
2929
2930 """
2931 url = '{0}/promoteChatMember'.format(self.base_url)
2932
2933 data = {'chat_id': chat_id, 'user_id': user_id}
2934
2935 if can_change_info is not None:
2936 data['can_change_info'] = can_change_info
2937 if can_post_messages is not None:
2938 data['can_post_messages'] = can_post_messages
2939 if can_edit_messages is not None:
2940 data['can_edit_messages'] = can_edit_messages
2941 if can_delete_messages is not None:
2942 data['can_delete_messages'] = can_delete_messages
2943 if can_invite_users is not None:
2944 data['can_invite_users'] = can_invite_users
2945 if can_restrict_members is not None:
2946 data['can_restrict_members'] = can_restrict_members
2947 if can_pin_messages is not None:
2948 data['can_pin_messages'] = can_pin_messages
2949 if can_promote_members is not None:
2950 data['can_promote_members'] = can_promote_members
2951 data.update(kwargs)
2952
2953 result = self._request.post(url, data, timeout=timeout)
2954
2955 return result
2956
2957 @log
2958 def set_chat_permissions(self, chat_id, permissions, timeout=None, **kwargs):
2959 """
2960 Use this method to set default chat permissions for all members. The bot must be an
2961 administrator in the group or a supergroup for this to work and must have the
2962 :attr:`can_restrict_members` admin rights. Returns True on success.
2963
2964 Args:
2965 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of
2966 the target supergroup (in the format `@supergroupusername`).
2967 permissions (:class:`telegram.ChatPermissions`): New default chat permissions.
2968 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
2969 the read timeout from the server (instead of the one specified during creation of
2970 the connection pool).
2971 **kwargs (:obj:`dict`): Arbitrary keyword arguments
2972
2973 Returns:
2974 :obj:`bool`: Returns True on success.
2975
2976 Raises:
2977 :class:`telegram.TelegramError`
2978
2979 """
2980 url = '{0}/setChatPermissions'.format(self.base_url)
2981
2982 data = {'chat_id': chat_id, 'permissions': permissions.to_dict()}
2983 data.update(kwargs)
2984
2985 result = self._request.post(url, data, timeout=timeout)
2986
2987 return result
2988
2989 @log
2990 def set_chat_administrator_custom_title(self,
2991 chat_id,
2992 user_id,
2993 custom_title,
2994 timeout=None,
2995 **kwargs):
2996 """
2997 Use this method to set a custom title for administrators promoted by the bot in a
2998 supergroup. The bot must be an administrator for this to work. Returns True on success.
2999
3000 Args:
3001 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of
3002 the target supergroup (in the format `@supergroupusername`).
3003 user_id (:obj:`int`): Unique identifier of the target administrator.
3004 custom_title (:obj:`str`) New custom title for the administrator; 0-16 characters,
3005 emoji are not allowed.
3006 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3007 the read timeout from the server (instead of the one specified during creation of
3008 the connection pool).
3009 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3010
3011 Returns:
3012 :obj:`bool`: Returns True on success.
3013
3014 Raises:
3015 :class:`telegram.TelegramError`
3016
3017 """
3018 url = '{0}/setChatAdministratorCustomTitle'.format(self.base_url)
3019
3020 data = {'chat_id': chat_id, 'user_id': user_id, 'custom_title': custom_title}
3021 data.update(kwargs)
3022
3023 result = self._request.post(url, data, timeout=timeout)
3024
3025 return result
3026
3027 @log
3028 def export_chat_invite_link(self, chat_id, timeout=None, **kwargs):
3029 """
3030 Use this method to generate a new invite link for a chat; any previously generated link
3031 is revoked. The bot must be an administrator in the chat for this to work and must have
3032 the appropriate admin rights.
3033
3034 Args:
3035 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3036 of the target channel (in the format @channelusername).
3037 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3038 the read timeout from the server (instead of the one specified during creation of
3039 the connection pool).
3040 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3041
3042 Returns:
3043 :obj:`str`: New invite link on success.
3044
3045 Raises:
3046 :class:`telegram.TelegramError`
3047
3048 """
3049 url = '{0}/exportChatInviteLink'.format(self.base_url)
3050
3051 data = {'chat_id': chat_id}
3052 data.update(kwargs)
3053
3054 result = self._request.post(url, data, timeout=timeout)
3055
3056 return result
3057
3058 @log
3059 def set_chat_photo(self, chat_id, photo, timeout=20, **kwargs):
3060 """Use this method to set a new profile photo for the chat.
3061
3062 Photos can't be changed for private chats. The bot must be an administrator in the chat
3063 for this to work and must have the appropriate admin rights.
3064
3065 Args:
3066 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3067 of the target channel (in the format @channelusername).
3068 photo (`filelike object`): New chat photo.
3069 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3070 the read timeout from the server (instead of the one specified during creation of
3071 the connection pool).
3072 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3073
3074 Returns:
3075 :obj:`bool`: Returns True on success.
3076
3077 Raises:
3078 :class:`telegram.TelegramError`
3079
3080 """
3081 url = '{0}/setChatPhoto'.format(self.base_url)
3082
3083 if InputFile.is_file(photo):
3084 photo = InputFile(photo)
3085
3086 data = {'chat_id': chat_id, 'photo': photo}
3087 data.update(kwargs)
3088
3089 result = self._request.post(url, data, timeout=timeout)
3090
3091 return result
3092
3093 @log
3094 def delete_chat_photo(self, chat_id, timeout=None, **kwargs):
3095 """
3096 Use this method to delete a chat photo. Photos can't be changed for private chats. The bot
3097 must be an administrator in the chat for this to work and must have the appropriate admin
3098 rights.
3099
3100 Args:
3101 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3102 of the target channel (in the format @channelusername).
3103 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3104 the read timeout from the server (instead of the one specified during creation of
3105 the connection pool).
3106 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3107
3108 Returns:
3109 :obj:`bool`: Returns ``True`` on success.
3110
3111 Raises:
3112 :class:`telegram.TelegramError`
3113
3114 """
3115 url = '{0}/deleteChatPhoto'.format(self.base_url)
3116
3117 data = {'chat_id': chat_id}
3118 data.update(kwargs)
3119
3120 result = self._request.post(url, data, timeout=timeout)
3121
3122 return result
3123
3124 @log
3125 def set_chat_title(self, chat_id, title, timeout=None, **kwargs):
3126 """
3127 Use this method to change the title of a chat. Titles can't be changed for private chats.
3128 The bot must be an administrator in the chat for this to work and must have the appropriate
3129 admin rights.
3130
3131 Args:
3132 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3133 of the target channel (in the format @channelusername).
3134 title (:obj:`str`): New chat title, 1-255 characters.
3135 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3136 the read timeout from the server (instead of the one specified during creation of
3137 the connection pool).
3138 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3139
3140 Returns:
3141 :obj:`bool`: Returns ``True`` on success.
3142
3143 Raises:
3144 :class:`telegram.TelegramError`
3145
3146 """
3147 url = '{0}/setChatTitle'.format(self.base_url)
3148
3149 data = {'chat_id': chat_id, 'title': title}
3150 data.update(kwargs)
3151
3152 result = self._request.post(url, data, timeout=timeout)
3153
3154 return result
3155
3156 @log
3157 def set_chat_description(self, chat_id, description, timeout=None, **kwargs):
3158 """
3159 Use this method to change the description of a group, a supergroup or a channel. The bot
3160 must be an administrator in the chat for this to work and must have the appropriate admin
3161 rights.
3162
3163 Args:
3164 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3165 of the target channel (in the format @channelusername).
3166 description (:obj:`str`): New chat description, 0-255 characters.
3167 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3168 the read timeout from the server (instead of the one specified during creation of
3169 the connection pool).
3170 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3171
3172 Returns:
3173 :obj:`bool`: Returns ``True`` on success.
3174
3175 Raises:
3176 :class:`telegram.TelegramError`
3177
3178 """
3179 url = '{0}/setChatDescription'.format(self.base_url)
3180
3181 data = {'chat_id': chat_id, 'description': description}
3182 data.update(kwargs)
3183
3184 result = self._request.post(url, data, timeout=timeout)
3185
3186 return result
3187
3188 @log
3189 def pin_chat_message(self, chat_id, message_id, disable_notification=None, timeout=None,
3190 **kwargs):
3191 """
3192 Use this method to pin a message in a group, a supergroup, or a channel.
3193 The bot must be an administrator in the chat for this to work and must have the
3194 ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right
3195 in the channel.
3196
3197 Args:
3198 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3199 of the target channel (in the format @channelusername).
3200 message_id (:obj:`int`): Identifier of a message to pin.
3201 disable_notification (:obj:`bool`, optional): Pass True, if it is not necessary to send
3202 a notification to all group members about the new pinned message. Notifications
3203 are always disabled in channels.
3204 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3205 the read timeout from the server (instead of the one specified during creation of
3206 the connection pool).
3207 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3208
3209 Returns:
3210 :obj:`bool`: Returns ``True`` on success.
3211
3212 Raises:
3213 :class:`telegram.TelegramError`
3214
3215 """
3216 url = '{0}/pinChatMessage'.format(self.base_url)
3217
3218 data = {'chat_id': chat_id, 'message_id': message_id}
3219
3220 if disable_notification is not None:
3221 data['disable_notification'] = disable_notification
3222 data.update(kwargs)
3223
3224 result = self._request.post(url, data, timeout=timeout)
3225
3226 return result
3227
3228 @log
3229 def unpin_chat_message(self, chat_id, timeout=None, **kwargs):
3230 """
3231 Use this method to unpin a message in a group, a supergroup, or a channel.
3232 The bot must be an administrator in the chat for this to work and must have the
3233 ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right
3234 in the channel.
3235
3236 Args:
3237 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3238 of the target channel (in the format @channelusername).
3239 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3240 the read timeout from the server (instead of the one specified during creation of
3241 the connection pool).
3242 **kwargs (:obj:`dict`): Arbitrary keyword arguments
3243
3244 Returns:
3245 :obj:`bool`: Returns ``True`` on success.
3246
3247 Raises:
3248 :class:`telegram.TelegramError`
3249
3250 """
3251 url = '{0}/unpinChatMessage'.format(self.base_url)
3252
3253 data = {'chat_id': chat_id}
3254 data.update(kwargs)
3255
3256 result = self._request.post(url, data, timeout=timeout)
3257
3258 return result
3259
3260 @log
3261 def get_sticker_set(self, name, timeout=None, **kwargs):
3262 """Use this method to get a sticker set.
3263
3264 Args:
3265 name (:obj:`str`): Name of the sticker set.
3266 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3267 the read timeout from the server (instead of the one specified during
3268 creation of the connection pool).
3269 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3270
3271 Returns:
3272 :class:`telegram.StickerSet`
3273
3274 Raises:
3275 :class:`telegram.TelegramError`
3276
3277 """
3278 url = '{0}/getStickerSet'.format(self.base_url)
3279
3280 data = {'name': name}
3281 data.update(kwargs)
3282
3283 result = self._request.post(url, data, timeout=timeout)
3284
3285 return StickerSet.de_json(result, self)
3286
3287 @log
3288 def upload_sticker_file(self, user_id, png_sticker, timeout=20, **kwargs):
3289 """
3290 Use this method to upload a .png file with a sticker for later use in
3291 :attr:`create_new_sticker_set` and :attr:`add_sticker_to_set` methods (can be used multiple
3292 times).
3293
3294 Note:
3295 The png_sticker argument can be either a file_id, an URL or a file from disk
3296 ``open(filename, 'rb')``
3297
3298 Args:
3299 user_id (:obj:`int`): User identifier of sticker file owner.
3300 png_sticker (:obj:`str` | `filelike object`): Png image with the sticker,
3301 must be up to 512 kilobytes in size, dimensions must not exceed 512px,
3302 and either width or height must be exactly 512px.
3303 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3304 the read timeout from the server (instead of the one specified during
3305 creation of the connection pool).
3306 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3307
3308 Returns:
3309 :class:`telegram.File`: The uploaded File
3310
3311 Raises:
3312 :class:`telegram.TelegramError`
3313
3314 """
3315 url = '{0}/uploadStickerFile'.format(self.base_url)
3316
3317 if InputFile.is_file(png_sticker):
3318 png_sticker = InputFile(png_sticker)
3319
3320 data = {'user_id': user_id, 'png_sticker': png_sticker}
3321 data.update(kwargs)
3322
3323 result = self._request.post(url, data, timeout=timeout)
3324
3325 return File.de_json(result, self)
3326
3327 @log
3328 def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis,
3329 contains_masks=None, mask_position=None, timeout=20, **kwargs):
3330 """
3331 Use this method to create new sticker set owned by a user.
3332 The bot will be able to edit the created sticker set.
3333 You must use exactly one of the fields png_sticker or tgs_sticker.
3334
3335 Note:
3336 The png_sticker argument can be either a file_id, an URL or a file from disk
3337 ``open(filename, 'rb')``
3338
3339 Args:
3340 user_id (:obj:`int`): User identifier of created sticker set owner.
3341 name (:obj:`str`): Short name of sticker set, to be used in t.me/addstickers/ URLs
3342 (e.g., animals). Can contain only english letters, digits and underscores.
3343 Must begin with a letter, can't contain consecutive underscores and
3344 must end in "_by_<bot username>". <bot_username> is case insensitive.
3345 1-64 characters.
3346 title (:obj:`str`): Sticker set title, 1-64 characters.
3347 png_sticker (:obj:`str` | `filelike object`): Png image with the sticker, must be up
3348 to 512 kilobytes in size, dimensions must not exceed 512px,
3349 and either width or height must be exactly 512px. Pass a file_id as a String to
3350 send a file that already exists on the Telegram servers, pass an HTTP URL as a
3351 String for Telegram to get a file from the Internet, or upload a new one
3352 using multipart/form-data.
3353 emojis (:obj:`str`): One or more emoji corresponding to the sticker.
3354 contains_masks (:obj:`bool`, optional): Pass True, if a set of mask stickers should be
3355 created.
3356 mask_position (:class:`telegram.MaskPosition`, optional): Position where the mask
3357 should be placed on faces.
3358 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3359 the read timeout from the server (instead of the one specified during
3360 creation of the connection pool).
3361 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3362
3363 Returns:
3364 :obj:`bool`: On success, ``True`` is returned.
3365
3366 Raises:
3367 :class:`telegram.TelegramError`
3368
3369 """
3370 url = '{0}/createNewStickerSet'.format(self.base_url)
3371
3372 if InputFile.is_file(png_sticker):
3373 png_sticker = InputFile(png_sticker)
3374
3375 data = {'user_id': user_id, 'name': name, 'title': title, 'png_sticker': png_sticker,
3376 'emojis': emojis}
3377
3378 if contains_masks is not None:
3379 data['contains_masks'] = contains_masks
3380 if mask_position is not None:
3381 data['mask_position'] = mask_position
3382 data.update(kwargs)
3383
3384 result = self._request.post(url, data, timeout=timeout)
3385
3386 return result
3387
3388 @log
3389 def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None,
3390 timeout=20, **kwargs):
3391 """
3392 Use this method to add a new sticker to a set created by the bot.
3393 You must use exactly one of the fields png_sticker or tgs_sticker. Animated stickers
3394 can be added to animated sticker sets and only to them. Animated sticker sets can have up
3395 to 50 stickers. Static sticker sets can have up to 120 stickers.
3396
3397 Note:
3398 The png_sticker argument can be either a file_id, an URL or a file from disk
3399 ``open(filename, 'rb')``
3400
3401 Args:
3402 user_id (:obj:`int`): User identifier of created sticker set owner.
3403 name (:obj:`str`): Sticker set name.
3404 png_sticker (:obj:`str` | `filelike object`): Png image with the sticker, must be up
3405 to 512 kilobytes in size, dimensions must not exceed 512px,
3406 and either width or height must be exactly 512px. Pass a file_id as a String to
3407 send a file that already exists on the Telegram servers, pass an HTTP URL as a
3408 String for Telegram to get a file from the Internet, or upload a new one
3409 using multipart/form-data.
3410 emojis (:obj:`str`): One or more emoji corresponding to the sticker.
3411 mask_position (:class:`telegram.MaskPosition`, optional): Position where the mask
3412 should be placed on faces.
3413 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3414 the read timeout from the server (instead of the one specified during
3415 creation of the connection pool).
3416 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3417
3418 Returns:
3419 :obj:`bool`: On success, ``True`` is returned.
3420
3421 Raises:
3422 :class:`telegram.TelegramError`
3423
3424 """
3425 url = '{0}/addStickerToSet'.format(self.base_url)
3426
3427 if InputFile.is_file(png_sticker):
3428 png_sticker = InputFile(png_sticker)
3429
3430 data = {'user_id': user_id, 'name': name, 'png_sticker': png_sticker, 'emojis': emojis}
3431
3432 if mask_position is not None:
3433 data['mask_position'] = mask_position
3434 data.update(kwargs)
3435
3436 result = self._request.post(url, data, timeout=timeout)
3437
3438 return result
3439
3440 @log
3441 def set_sticker_position_in_set(self, sticker, position, timeout=None, **kwargs):
3442 """Use this method to move a sticker in a set created by the bot to a specific position.
3443
3444 Args:
3445 sticker (:obj:`str`): File identifier of the sticker.
3446 position (:obj:`int`): New sticker position in the set, zero-based.
3447 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3448 the read timeout from the server (instead of the one specified during
3449 creation of the connection pool).
3450 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3451
3452 Returns:
3453 :obj:`bool`: On success, ``True`` is returned.
3454
3455 Raises:
3456 :class:`telegram.TelegramError`
3457
3458 """
3459 url = '{0}/setStickerPositionInSet'.format(self.base_url)
3460
3461 data = {'sticker': sticker, 'position': position}
3462 data.update(kwargs)
3463
3464 result = self._request.post(url, data, timeout=timeout)
3465
3466 return result
3467
3468 @log
3469 def delete_sticker_from_set(self, sticker, timeout=None, **kwargs):
3470 """Use this method to delete a sticker from a set created by the bot.
3471
3472 Args:
3473 sticker (:obj:`str`): File identifier of the sticker.
3474 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3475 the read timeout from the server (instead of the one specified during
3476 creation of the connection pool).
3477 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3478
3479 Returns:
3480 :obj:`bool`: On success, ``True`` is returned.
3481
3482 Raises:
3483 :class:`telegram.TelegramError`
3484
3485 """
3486 url = '{0}/deleteStickerFromSet'.format(self.base_url)
3487
3488 data = {'sticker': sticker}
3489 data.update(kwargs)
3490
3491 result = self._request.post(url, data, timeout=timeout)
3492
3493 return result
3494
3495 @log
3496 def set_passport_data_errors(self, user_id, errors, timeout=None, **kwargs):
3497 """
3498 Informs a user that some of the Telegram Passport elements they provided contains errors.
3499 The user will not be able to re-submit their Passport to you until the errors are fixed
3500 (the contents of the field for which you returned the error must change). Returns True
3501 on success.
3502
3503 Use this if the data submitted by the user doesn't satisfy the standards your service
3504 requires for any reason. For example, if a birthday date seems invalid, a submitted
3505 document is blurry, a scan shows evidence of tampering, etc. Supply some details in the
3506 error message to make sure the user knows how to correct the issues.
3507
3508 Args:
3509 user_id (:obj:`int`): User identifier
3510 errors (List[:class:`PassportElementError`]): A JSON-serialized array describing the
3511 errors.
3512 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3513 the read timeout from the server (instead of the one specified during
3514 creation of the connection pool).
3515 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3516
3517 Returns:
3518 :obj:`bool`: On success, ``True`` is returned.
3519
3520 Raises:
3521 :class:`telegram.TelegramError`
3522
3523 """
3524 url_ = '{0}/setPassportDataErrors'.format(self.base_url)
3525
3526 data = {'user_id': user_id, 'errors': [error.to_dict() for error in errors]}
3527 data.update(kwargs)
3528
3529 result = self._request.post(url_, data, timeout=timeout)
3530
3531 return result
3532
3533 @log
3534 def send_poll(self,
3535 chat_id,
3536 question,
3537 options,
3538 is_anonymous=True,
3539 type=Poll.REGULAR,
3540 allows_multiple_answers=False,
3541 correct_option_id=None,
3542 is_closed=None,
3543 disable_notification=None,
3544 reply_to_message_id=None,
3545 reply_markup=None,
3546 timeout=None,
3547 **kwargs):
3548 """
3549 Use this method to send a native poll.
3550
3551 Args:
3552 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3553 of the target channel (in the format @channelusername).
3554 question (:obj:`str`): Poll question, 1-255 characters.
3555 options (List[:obj:`str`]): List of answer options, 2-10 strings 1-100 characters each.
3556 is_anonymous (:obj:`bool`, optional): True, if the poll needs to be anonymous,
3557 defaults to True.
3558 type (:obj:`str`, optional): Poll type, :attr:`telegram.Poll.QUIZ` or
3559 :attr:`telegram.Poll.REGULAR`, defaults to :attr:`telegram.Poll.REGULAR`.
3560 allows_multiple_answers (:obj:`bool`, optional): True, if the poll allows multiple
3561 answers, ignored for polls in quiz mode, defaults to False.
3562 correct_option_id (:obj:`int`, optional): 0-based identifier of the correct answer
3563 option, required for polls in quiz mode.
3564 is_closed (:obj:`bool`, optional): Pass True, if the poll needs to be immediately
3565 closed. This can be useful for poll preview.
3566 disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
3567 receive a notification with no sound.
3568 reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
3569 original message.
3570 reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
3571 JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
3572 to remove reply keyboard or to force a reply from the user.
3573 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3574 the read timeout from the server (instead of the one specified during creation of
3575 the connection pool).
3576 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3577
3578 Returns:
3579 :class:`telegram.Message`: On success, the sent Message is returned.
3580
3581 Raises:
3582 :class:`telegram.TelegramError`
3583
3584 """
3585 url = '{0}/sendPoll'.format(self.base_url)
3586
3587 data = {
3588 'chat_id': chat_id,
3589 'question': question,
3590 'options': options
3591 }
3592
3593 if not is_anonymous:
3594 data['is_anonymous'] = is_anonymous
3595 if type:
3596 data['type'] = type
3597 if allows_multiple_answers:
3598 data['allows_multiple_answers'] = allows_multiple_answers
3599 if correct_option_id is not None:
3600 data['correct_option_id'] = correct_option_id
3601 if is_closed:
3602 data['is_closed'] = is_closed
3603
3604 return self._message(url, data, timeout=timeout, disable_notification=disable_notification,
3605 reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
3606 **kwargs)
3607
3608 @log
3609 def stop_poll(self,
3610 chat_id,
3611 message_id,
3612 reply_markup=None,
3613 timeout=None,
3614 **kwargs):
3615 """
3616 Use this method to stop a poll which was sent by the bot.
3617
3618 Args:
3619 chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
3620 of the target channel (in the format @channelusername).
3621 message_id (:obj:`int`): Identifier of the original message with the poll.
3622 reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): AA JSON-serialized
3623 object for a new message inline keyboard.
3624 timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
3625 the read timeout from the server (instead of the one specified during creation of
3626 the connection pool).
3627 **kwargs (:obj:`dict`): Arbitrary keyword arguments.
3628
3629 Returns:
3630 :class:`telegram.Poll`: On success, the stopped Poll with the
3631 final results is returned.
3632
3633 Raises:
3634 :class:`telegram.TelegramError`
3635
3636 """
3637 url = '{0}/stopPoll'.format(self.base_url)
3638
3639 data = {
3640 'chat_id': chat_id,
3641 'message_id': message_id
3642 }
3643
3644 if reply_markup:
3645 if isinstance(reply_markup, ReplyMarkup):
3646 data['reply_markup'] = reply_markup.to_json()
3647 else:
3648 data['reply_markup'] = reply_markup
3649
3650 result = self._request.post(url, data, timeout=timeout)
3651
3652 return Poll.de_json(result, self)
3653
3654 def to_dict(self):
3655 data = {'id': self.id, 'username': self.username, 'first_name': self.first_name}
3656
3657 if self.last_name:
3658 data['last_name'] = self.last_name
3659
3660 return data
3661
3662 def __reduce__(self):
3663 return (self.__class__, (self.token, self.base_url.replace(self.token, ''),
3664 self.base_file_url.replace(self.token, '')))
3665
3666 # camelCase aliases
3667 getMe = get_me
3668 """Alias for :attr:`get_me`"""
3669 sendMessage = send_message
3670 """Alias for :attr:`send_message`"""
3671 deleteMessage = delete_message
3672 """Alias for :attr:`delete_message`"""
3673 forwardMessage = forward_message
3674 """Alias for :attr:`forward_message`"""
3675 sendPhoto = send_photo
3676 """Alias for :attr:`send_photo`"""
3677 sendAudio = send_audio
3678 """Alias for :attr:`send_audio`"""
3679 sendDocument = send_document
3680 """Alias for :attr:`send_document`"""
3681 sendSticker = send_sticker
3682 """Alias for :attr:`send_sticker`"""
3683 sendVideo = send_video
3684 """Alias for :attr:`send_video`"""
3685 sendAnimation = send_animation
3686 """Alias for :attr:`send_animation`"""
3687 sendVoice = send_voice
3688 """Alias for :attr:`send_voice`"""
3689 sendVideoNote = send_video_note
3690 """Alias for :attr:`send_video_note`"""
3691 sendMediaGroup = send_media_group
3692 """Alias for :attr:`send_media_group`"""
3693 sendLocation = send_location
3694 """Alias for :attr:`send_location`"""
3695 editMessageLiveLocation = edit_message_live_location
3696 """Alias for :attr:`edit_message_live_location`"""
3697 stopMessageLiveLocation = stop_message_live_location
3698 """Alias for :attr:`stop_message_live_location`"""
3699 sendVenue = send_venue
3700 """Alias for :attr:`send_venue`"""
3701 sendContact = send_contact
3702 """Alias for :attr:`send_contact`"""
3703 sendGame = send_game
3704 """Alias for :attr:`send_game`"""
3705 sendChatAction = send_chat_action
3706 """Alias for :attr:`send_chat_action`"""
3707 answerInlineQuery = answer_inline_query
3708 """Alias for :attr:`answer_inline_query`"""
3709 getUserProfilePhotos = get_user_profile_photos
3710 """Alias for :attr:`get_user_profile_photos`"""
3711 getFile = get_file
3712 """Alias for :attr:`get_file`"""
3713 kickChatMember = kick_chat_member
3714 """Alias for :attr:`kick_chat_member`"""
3715 unbanChatMember = unban_chat_member
3716 """Alias for :attr:`unban_chat_member`"""
3717 answerCallbackQuery = answer_callback_query
3718 """Alias for :attr:`answer_callback_query`"""
3719 editMessageText = edit_message_text
3720 """Alias for :attr:`edit_message_text`"""
3721 editMessageCaption = edit_message_caption
3722 """Alias for :attr:`edit_message_caption`"""
3723 editMessageMedia = edit_message_media
3724 """Alias for :attr:`edit_message_media`"""
3725 editMessageReplyMarkup = edit_message_reply_markup
3726 """Alias for :attr:`edit_message_reply_markup`"""
3727 getUpdates = get_updates
3728 """Alias for :attr:`get_updates`"""
3729 setWebhook = set_webhook
3730 """Alias for :attr:`set_webhook`"""
3731 deleteWebhook = delete_webhook
3732 """Alias for :attr:`delete_webhook`"""
3733 leaveChat = leave_chat
3734 """Alias for :attr:`leave_chat`"""
3735 getChat = get_chat
3736 """Alias for :attr:`get_chat`"""
3737 getChatAdministrators = get_chat_administrators
3738 """Alias for :attr:`get_chat_administrators`"""
3739 getChatMember = get_chat_member
3740 """Alias for :attr:`get_chat_member`"""
3741 setChatStickerSet = set_chat_sticker_set
3742 """Alias for :attr:`set_chat_sticker_set`"""
3743 deleteChatStickerSet = delete_chat_sticker_set
3744 """Alias for :attr:`delete_chat_sticker_set`"""
3745 getChatMembersCount = get_chat_members_count
3746 """Alias for :attr:`get_chat_members_count`"""
3747 getWebhookInfo = get_webhook_info
3748 """Alias for :attr:`get_webhook_info`"""
3749 setGameScore = set_game_score
3750 """Alias for :attr:`set_game_score`"""
3751 getGameHighScores = get_game_high_scores
3752 """Alias for :attr:`get_game_high_scores`"""
3753 sendInvoice = send_invoice
3754 """Alias for :attr:`send_invoice`"""
3755 answerShippingQuery = answer_shipping_query
3756 """Alias for :attr:`answer_shipping_query`"""
3757 answerPreCheckoutQuery = answer_pre_checkout_query
3758 """Alias for :attr:`answer_pre_checkout_query`"""
3759 restrictChatMember = restrict_chat_member
3760 """Alias for :attr:`restrict_chat_member`"""
3761 promoteChatMember = promote_chat_member
3762 """Alias for :attr:`promote_chat_member`"""
3763 setChatPermissions = set_chat_permissions
3764 """Alias for :attr:`set_chat_permissions`"""
3765 setChatAdministratorCustomTitle = set_chat_administrator_custom_title
3766 """Alias for :attr:`set_chat_administrator_custom_title`"""
3767 exportChatInviteLink = export_chat_invite_link
3768 """Alias for :attr:`export_chat_invite_link`"""
3769 setChatPhoto = set_chat_photo
3770 """Alias for :attr:`set_chat_photo`"""
3771 deleteChatPhoto = delete_chat_photo
3772 """Alias for :attr:`delete_chat_photo`"""
3773 setChatTitle = set_chat_title
3774 """Alias for :attr:`set_chat_title`"""
3775 setChatDescription = set_chat_description
3776 """Alias for :attr:`set_chat_description`"""
3777 pinChatMessage = pin_chat_message
3778 """Alias for :attr:`pin_chat_message`"""
3779 unpinChatMessage = unpin_chat_message
3780 """Alias for :attr:`unpin_chat_message`"""
3781 getStickerSet = get_sticker_set
3782 """Alias for :attr:`get_sticker_set`"""
3783 uploadStickerFile = upload_sticker_file
3784 """Alias for :attr:`upload_sticker_file`"""
3785 createNewStickerSet = create_new_sticker_set
3786 """Alias for :attr:`create_new_sticker_set`"""
3787 addStickerToSet = add_sticker_to_set
3788 """Alias for :attr:`add_sticker_to_set`"""
3789 setStickerPositionInSet = set_sticker_position_in_set
3790 """Alias for :attr:`set_sticker_position_in_set`"""
3791 deleteStickerFromSet = delete_sticker_from_set
3792 """Alias for :attr:`delete_sticker_from_set`"""
3793 setPassportDataErrors = set_passport_data_errors
3794 """Alias for :attr:`set_passport_data_errors`"""
3795 sendPoll = send_poll
3796 """Alias for :attr:`send_poll`"""
3797 stopPoll = stop_poll
3798 """Alias for :attr:`stop_poll`"""