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