-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
bot.py
6248 lines (5361 loc) · 272 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# pylint: disable=E0611,E0213,E1102,E1101,R0913,R0904
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Bot."""
import functools
import logging
import warnings
from datetime import datetime
from typing import (
TYPE_CHECKING,
Callable,
List,
Optional,
Tuple,
TypeVar,
Union,
no_type_check,
Dict,
cast,
Sequence,
)
try:
import ujson as json
except ImportError:
import json # type: ignore[no-redef] # noqa: F723
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
CRYPTO_INSTALLED = True
except ImportError:
default_backend = None # type: ignore[assignment]
serialization = None # type: ignore[assignment]
CRYPTO_INSTALLED = False
from telegram import (
Animation,
Audio,
BotCommand,
BotCommandScope,
Chat,
ChatMember,
ChatPermissions,
ChatPhoto,
Contact,
Document,
File,
GameHighScore,
Location,
MaskPosition,
Message,
MessageId,
PassportElementError,
PhotoSize,
Poll,
ReplyMarkup,
ShippingOption,
Sticker,
StickerSet,
TelegramObject,
Update,
User,
UserProfilePhotos,
Venue,
Video,
VideoNote,
Voice,
WebhookInfo,
InlineKeyboardMarkup,
ChatInviteLink,
SentWebAppMessage,
ChatAdministratorRights,
MenuButton,
)
from telegram.constants import MAX_INLINE_QUERY_RESULTS
from telegram.error import InvalidToken, TelegramError
from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.utils.helpers import (
DEFAULT_NONE,
DefaultValue,
to_timestamp,
is_local_file,
parse_file_input,
DEFAULT_20,
)
from telegram.utils.request import Request
from telegram.utils.types import FileInput, JSONDict, ODVInput, DVInput
if TYPE_CHECKING:
from telegram.ext import Defaults
from telegram import (
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
InputMedia,
InlineQueryResult,
LabeledPrice,
MessageEntity,
)
RT = TypeVar('RT')
def log( # skipcq: PY-D0003
func: Callable[..., RT], *args: object, **kwargs: object # pylint: disable=W0613
) -> Callable[..., RT]:
logger = logging.getLogger(func.__module__)
@functools.wraps(func)
def decorator(*args: object, **kwargs: object) -> RT: # pylint: disable=W0613
logger.debug('Entering: %s', func.__name__)
result = func(*args, **kwargs)
logger.debug(result)
logger.debug('Exiting: %s', func.__name__)
return result
return decorator
class Bot(TelegramObject):
"""This object represents a Telegram Bot.
.. versionadded:: 13.2
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`bot` is equal.
Note:
Most bot methods have the argument ``api_kwargs`` which allows to pass arbitrary keywords
to the Telegram API. This can be used to access new features of the API before they were
incorporated into PTB. However, this is not guaranteed to work, i.e. it will fail for
passing files.
Args:
token (:obj:`str`): Bot's unique authentication.
base_url (:obj:`str`, optional): Telegram Bot API service URL.
base_file_url (:obj:`str`, optional): Telegram Bot API file URL.
request (:obj:`telegram.utils.request.Request`, optional): Pre initialized
:obj:`telegram.utils.request.Request`.
private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
private_key_password (:obj:`bytes`, optional): Password for above private key.
defaults (:class:`telegram.ext.Defaults`, optional): An object containing default values to
be used if not set explicitly in the bot methods.
.. deprecated:: 13.6
Passing :class:`telegram.ext.Defaults` to :class:`telegram.Bot` is deprecated. If
you want to use :class:`telegram.ext.Defaults`, please use
:class:`telegram.ext.ExtBot` instead.
"""
__slots__ = (
'token',
'base_url',
'base_file_url',
'private_key',
'defaults',
'_bot',
'_commands',
'_request',
'logger',
)
def __init__(
self,
token: str,
base_url: str = None,
base_file_url: str = None,
request: 'Request' = None,
private_key: bytes = None,
private_key_password: bytes = None,
defaults: 'Defaults' = None,
):
self.token = self._validate_token(token)
# Gather default
self.defaults = defaults
if self.defaults:
warnings.warn(
'Passing Defaults to telegram.Bot is deprecated. Use telegram.ext.ExtBot instead.',
TelegramDeprecationWarning,
stacklevel=3,
)
if base_url is None:
base_url = 'https://api.telegram.org/bot'
if base_file_url is None:
base_file_url = 'https://api.telegram.org/file/bot'
self.base_url = str(base_url) + str(self.token)
self.base_file_url = str(base_file_url) + str(self.token)
self._bot: Optional[User] = None
self._commands: Optional[List[BotCommand]] = None
self._request = request or Request()
self.private_key = None
self.logger = logging.getLogger(__name__)
if private_key:
if not CRYPTO_INSTALLED:
raise RuntimeError(
'To use Telegram Passports, PTB must be installed via `pip install '
'python-telegram-bot[passport]`.'
)
self.private_key = serialization.load_pem_private_key(
private_key, password=private_key_password, backend=default_backend()
)
# The ext_bot argument is a little hack to get warnings handled correctly.
# It's not very clean, but the warnings will be dropped at some point anyway.
def __setattr__(self, key: str, value: object, ext_bot: bool = False) -> None:
if issubclass(self.__class__, Bot) and self.__class__ is not Bot and not ext_bot:
object.__setattr__(self, key, value)
return
super().__setattr__(key, value)
def _insert_defaults(
self, data: Dict[str, object], timeout: ODVInput[float]
) -> Optional[float]:
"""
Inserts the defaults values for optional kwargs for which tg.ext.Defaults provides
convenience functionality, i.e. the kwargs with a tg.utils.helpers.DefaultValue default
data is edited in-place. As timeout is not passed via the kwargs, it needs to be passed
separately and gets returned.
This can only work, if all kwargs that may have defaults are passed in data!
"""
effective_timeout = DefaultValue.get_value(timeout)
# If we have no Defaults, we just need to replace DefaultValue instances
# with the actual value
if not self.defaults:
data.update((key, DefaultValue.get_value(value)) for key, value in data.items())
return effective_timeout
# if we have Defaults, we replace all DefaultValue instances with the relevant
# Defaults value. If there is none, we fall back to the default value of the bot method
for key, val in data.items():
if isinstance(val, DefaultValue):
data[key] = self.defaults.api_defaults.get(key, val.value)
if isinstance(timeout, DefaultValue):
# If we get here, we use Defaults.timeout, unless that's not set, which is the
# case if isinstance(self.defaults.timeout, DefaultValue)
return (
self.defaults.timeout
if not isinstance(self.defaults.timeout, DefaultValue)
else effective_timeout
)
return effective_timeout
def _post(
self,
endpoint: str,
data: JSONDict = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> Union[bool, JSONDict, None]:
if data is None:
data = {}
if api_kwargs:
if data:
data.update(api_kwargs)
else:
data = api_kwargs
# Insert is in-place, so no return value for data
if endpoint != 'getUpdates':
effective_timeout = self._insert_defaults(data, timeout)
else:
effective_timeout = cast(float, timeout)
# Drop any None values because Telegram doesn't handle them well
data = {key: value for key, value in data.items() if value is not None}
return self.request.post(
f'{self.base_url}/{endpoint}', data=data, timeout=effective_timeout
)
def _message(
self,
endpoint: str,
data: JSONDict,
reply_to_message_id: int = None,
disable_notification: ODVInput[bool] = DEFAULT_NONE,
reply_markup: ReplyMarkup = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> Union[bool, Message]:
if reply_to_message_id is not None:
data['reply_to_message_id'] = reply_to_message_id
if protect_content:
data['protect_content'] = protect_content
# We don't check if (DEFAULT_)None here, so that _put is able to insert the defaults
# correctly, if necessary
data['disable_notification'] = disable_notification
data['allow_sending_without_reply'] = allow_sending_without_reply
if reply_markup is not None:
if isinstance(reply_markup, ReplyMarkup):
# We need to_json() instead of to_dict() here, because reply_markups may be
# attached to media messages, which aren't json dumped by utils.request
data['reply_markup'] = reply_markup.to_json()
else:
data['reply_markup'] = reply_markup
if data.get('media') and (data['media'].parse_mode == DEFAULT_NONE):
if self.defaults:
data['media'].parse_mode = DefaultValue.get_value(self.defaults.parse_mode)
else:
data['media'].parse_mode = None
result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs)
if result is True:
return result
return Message.de_json(result, self) # type: ignore[return-value, arg-type]
@property
def request(self) -> Request: # skip-cq: PY-D0003
return self._request
@staticmethod
def _validate_token(token: str) -> str:
"""A very basic validation on token."""
if any(x.isspace() for x in token):
raise InvalidToken()
left, sep, _right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise InvalidToken()
return token
@property
def bot(self) -> User:
""":class:`telegram.User`: User instance for the bot as returned by :meth:`get_me`."""
if self._bot is None:
self._bot = self.get_me()
return self._bot
@property
def id(self) -> int: # pylint: disable=C0103
""":obj:`int`: Unique identifier for this bot."""
return self.bot.id
@property
def first_name(self) -> str:
""":obj:`str`: Bot's first name."""
return self.bot.first_name
@property
def last_name(self) -> str:
""":obj:`str`: Optional. Bot's last name."""
return self.bot.last_name # type: ignore
@property
def username(self) -> str:
""":obj:`str`: Bot's username."""
return self.bot.username # type: ignore
@property
def link(self) -> str:
""":obj:`str`: Convenience property. Returns the t.me link of the bot."""
return f"https://t.me/{self.username}"
@property
def can_join_groups(self) -> bool:
""":obj:`bool`: Bot's :attr:`telegram.User.can_join_groups` attribute."""
return self.bot.can_join_groups # type: ignore
@property
def can_read_all_group_messages(self) -> bool:
""":obj:`bool`: Bot's :attr:`telegram.User.can_read_all_group_messages` attribute."""
return self.bot.can_read_all_group_messages # type: ignore
@property
def supports_inline_queries(self) -> bool:
""":obj:`bool`: Bot's :attr:`telegram.User.supports_inline_queries` attribute."""
return self.bot.supports_inline_queries # type: ignore
@property
def commands(self) -> List[BotCommand]:
"""
List[:class:`BotCommand`]: Bot's commands as available in the default scope.
.. deprecated:: 13.7
This property has been deprecated since there can be different commands available for
different scopes.
"""
warnings.warn(
"Bot.commands has been deprecated since there can be different command "
"lists for different scopes.",
TelegramDeprecationWarning,
stacklevel=2,
)
if self._commands is None:
self._commands = self.get_my_commands()
return self._commands
@property
def name(self) -> str:
""":obj:`str`: Bot's @username."""
return f'@{self.username}'
@log
def get_me(self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None) -> User:
"""A simple method for testing your bot's auth token. Requires no parameters.
Args:
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
the read timeout from the server (instead of the one specified during creation of
the connection pool).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.User`: A :class:`telegram.User` instance representing that bot if the
credentials are valid, :obj:`None` otherwise.
Raises:
:class:`telegram.error.TelegramError`
"""
result = self._post('getMe', timeout=timeout, api_kwargs=api_kwargs)
self._bot = User.de_json(result, self) # type: ignore[return-value, arg-type]
return self._bot # type: ignore[return-value]
@log
def send_message(
self,
chat_id: Union[int, str],
text: str,
parse_mode: ODVInput[str] = DEFAULT_NONE,
disable_web_page_preview: ODVInput[bool] = DEFAULT_NONE,
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: int = None,
reply_markup: ReplyMarkup = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
protect_content: bool = None,
) -> Message:
"""Use this method to send text messages.
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
text (:obj:`str`): Text of the message to be sent. Max 4096 characters after entities
parsing. Also found as :attr:`telegram.constants.MAX_MESSAGE_LENGTH`.
parse_mode (:obj:`str`): Send Markdown or HTML, if you want Telegram apps to show bold,
italic, fixed-width text or inline URLs in your bot's message. See the constants in
:class:`telegram.ParseMode` for the available modes.
entities (List[:class:`telegram.MessageEntity`], optional): List of special entities
that appear in message text, which can be specified instead of :attr:`parse_mode`.
disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in
this message.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
protect_content (:obj:`bool`, optional): Protects the contents of sent messages from
forwarding and saving.
.. versionadded:: 13.10
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
allow_sending_without_reply (:obj:`bool`, optional): Pass :obj:`True`, if the message
should be sent even if the specified replied-to message is not found.
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options.
A JSON-serialized object for an inline keyboard, custom reply keyboard,
instructions to remove reply keyboard or to force a reply from the user.
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
the read timeout from the server (instead of the one specified during creation of
the connection pool).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.Message`: On success, the sent message is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {
'chat_id': chat_id,
'text': text,
'parse_mode': parse_mode,
'disable_web_page_preview': disable_web_page_preview,
}
if entities:
data['entities'] = [me.to_dict() for me in entities]
return self._message( # type: ignore[return-value]
'sendMessage',
data,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
allow_sending_without_reply=allow_sending_without_reply,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
@log
def delete_message(
self,
chat_id: Union[str, int],
message_id: int,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""
Use this method to delete a message, including service messages, with the following
limitations:
- A message can only be deleted if it was sent less than 48 hours ago.
- A dice message in a private chat can only be deleted if it was sent more than 24
hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
- Bots can delete incoming messages in private chats.
- Bots granted :attr:`telegram.ChatMember.can_post_messages` permissions can delete
outgoing messages in channels.
- If the bot is an administrator of a group, it can delete any message there.
- If the bot has :attr:`telegram.ChatMember.can_delete_messages` permission in a
supergroup or a channel, it can delete any message there.
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
message_id (:obj:`int`): Identifier of the message to delete.
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
the read timeout from the server (instead of the one specified during creation of
the connection pool).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {'chat_id': chat_id, 'message_id': message_id}
result = self._post('deleteMessage', data, timeout=timeout, api_kwargs=api_kwargs)
return result # type: ignore[return-value]
@log
def forward_message(
self,
chat_id: Union[int, str],
from_chat_id: Union[str, int],
message_id: int,
disable_notification: DVInput[bool] = DEFAULT_NONE,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> Message:
"""Use this method to forward messages of any kind. Service messages can't be forwarded.
Note:
Since the release of Bot API 5.5 it can be impossible to forward messages from
some chats. Use the attributes :attr:`telegram.Message.has_protected_content` and
:attr:`telegram.Chat.has_protected_content` to check this.
As a workaround, it is still possible to use :meth:`copy_message`. However, this
behaviour is undocumented and might be changed by Telegram.
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
from_chat_id (:obj:`int` | :obj:`str`): Unique identifier for the chat where the
original message was sent (or channel username in the format ``@channelusername``).
message_id (:obj:`int`): Message identifier in the chat specified in from_chat_id.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
protect_content (:obj:`bool`, optional): Protects the contents of the sent message from
forwarding and saving.
.. versionadded:: 13.10
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
the read timeout from the server (instead of the one specified during creation of
the connection pool).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {}
if chat_id:
data['chat_id'] = chat_id
if from_chat_id:
data['from_chat_id'] = from_chat_id
if message_id:
data['message_id'] = message_id
return self._message( # type: ignore[return-value]
'forwardMessage',
data,
disable_notification=disable_notification,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
@log
def send_photo(
self,
chat_id: Union[int, str],
photo: Union[FileInput, 'PhotoSize'],
caption: str = None,
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: int = None,
reply_markup: ReplyMarkup = None,
timeout: DVInput[float] = DEFAULT_20,
parse_mode: ODVInput[str] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> Message:
"""Use this method to send photos.
Note:
The photo argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
photo (:obj:`str` | `filelike object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.PhotoSize`): Photo to send.
Pass a file_id as String to send a photo that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a photo from the
Internet, or upload a new photo using multipart/form-data. Lastly you can pass
an existing :class:`telegram.PhotoSize` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the photo, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Photo caption (may also be used when resending photos
by file_id), 0-1024 characters after entities parsing.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
caption_entities (List[:class:`telegram.MessageEntity`], optional): List of special
entities that appear in message text, which can be specified instead of
:attr:`parse_mode`.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
protect_content (:obj:`bool`, optional): Protects the contents of the sent message from
forwarding and saving.
.. versionadded:: 13.10
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
allow_sending_without_reply (:obj:`bool`, optional): Pass :obj:`True`, if the message
should be sent even if the specified replied-to message is not found.
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {
'chat_id': chat_id,
'photo': parse_file_input(photo, PhotoSize, filename=filename),
'parse_mode': parse_mode,
}
if caption:
data['caption'] = caption
if caption_entities:
data['caption_entities'] = [me.to_dict() for me in caption_entities]
return self._message( # type: ignore[return-value]
'sendPhoto',
data,
timeout=timeout,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
allow_sending_without_reply=allow_sending_without_reply,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
@log
def send_audio(
self,
chat_id: Union[int, str],
audio: Union[FileInput, 'Audio'],
duration: int = None,
performer: str = None,
title: str = None,
caption: str = None,
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: int = None,
reply_markup: ReplyMarkup = None,
timeout: DVInput[float] = DEFAULT_20,
parse_mode: ODVInput[str] = DEFAULT_NONE,
thumb: FileInput = None,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> Message:
"""
Use this method to send audio files, if you want Telegram clients to display them in the
music player. Your audio must be in the .mp3 or .m4a format.
Bots can currently send audio files of up to 50 MB in size, this limit may be changed in
the future.
For sending voice messages, use the :meth:`send_voice` method instead.
Note:
The audio argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
audio (:obj:`str` | `filelike object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.Audio`): Audio file to send.
Pass a file_id as String to send an audio file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get an audio file from
the Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Audio` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the audio, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Audio caption, 0-1024 characters after entities
parsing.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
caption_entities (List[:class:`telegram.MessageEntity`], optional): List of special
entities that appear in message text, which can be specified instead of
:attr:`parse_mode`.
duration (:obj:`int`, optional): Duration of sent audio in seconds.
performer (:obj:`str`, optional): Performer.
title (:obj:`str`, optional): Track name.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
protect_content (:obj:`bool`, optional): Protects the contents of the sent message from
forwarding and saving.
.. versionadded:: 13.10
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
allow_sending_without_reply (:obj:`bool`, optional): Pass :obj:`True`, if the message
should be sent even if the specified replied-to message is not found.
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
thumb (`filelike object` | :obj:`bytes` | :class:`pathlib.Path`, optional): Thumbnail
of the file sent; can be ignored if
thumbnail generation for the file is supported server-side. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail's width and height should
not exceed 320. Ignored if the file is not uploaded using multipart/form-data.
Thumbnails can't be reused and can be only uploaded as a new file.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {
'chat_id': chat_id,
'audio': parse_file_input(audio, Audio, filename=filename),
'parse_mode': parse_mode,
}
if duration:
data['duration'] = duration
if performer:
data['performer'] = performer
if title:
data['title'] = title
if caption:
data['caption'] = caption
if caption_entities:
data['caption_entities'] = [me.to_dict() for me in caption_entities]
if thumb:
data['thumb'] = parse_file_input(thumb, attach=True)
return self._message( # type: ignore[return-value]
'sendAudio',
data,
timeout=timeout,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
allow_sending_without_reply=allow_sending_without_reply,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
@log
def send_document(
self,
chat_id: Union[int, str],
document: Union[FileInput, 'Document'],
filename: str = None,
caption: str = None,
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: int = None,
reply_markup: ReplyMarkup = None,
timeout: DVInput[float] = DEFAULT_20,
parse_mode: ODVInput[str] = DEFAULT_NONE,
thumb: FileInput = None,
api_kwargs: JSONDict = None,
disable_content_type_detection: bool = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
protect_content: bool = None,
) -> Message:
"""
Use this method to send general files.
Bots can currently send files of any type of up to 50 MB in size, this limit may be
changed in the future.
Note:
The document argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
document (:obj:`str` | `filelike object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.Document`): File to send.
Pass a file_id as String to send a file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a file from the
Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Document` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the document, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
caption (:obj:`str`, optional): Document caption (may also be used when resending
documents by file_id), 0-1024 characters after entities parsing.
disable_content_type_detection (:obj:`bool`, optional): Disables automatic server-side
content type detection for files uploaded using multipart/form-data.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
caption_entities (List[:class:`telegram.MessageEntity`], optional): List of special
entities that appear in message text, which can be specified instead of
:attr:`parse_mode`.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
protect_content (:obj:`bool`, optional): Protects the contents of the sent message from
forwarding and saving.
.. versionadded:: 13.10
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
allow_sending_without_reply (:obj:`bool`, optional): Pass :obj:`True`, if the message
should be sent even if the specified replied-to message is not found.
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
thumb (`filelike object` | :obj:`bytes` | :class:`pathlib.Path`, optional): Thumbnail
of the file sent; can be ignored if
thumbnail generation for the file is supported server-side. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail's width and height should
not exceed 320. Ignored if the file is not uploaded using multipart/form-data.
Thumbnails can't be reused and can be only uploaded as a new file.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the
Telegram API.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.error.TelegramError`
"""
data: JSONDict = {
'chat_id': chat_id,
'document': parse_file_input(document, Document, filename=filename),
'parse_mode': parse_mode,
}
if caption:
data['caption'] = caption
if caption_entities:
data['caption_entities'] = [me.to_dict() for me in caption_entities]
if disable_content_type_detection is not None:
data['disable_content_type_detection'] = disable_content_type_detection
if thumb:
data['thumb'] = parse_file_input(thumb, attach=True)
return self._message( # type: ignore[return-value]
'sendDocument',
data,
timeout=timeout,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
allow_sending_without_reply=allow_sending_without_reply,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
@log
def send_sticker(
self,
chat_id: Union[int, str],
sticker: Union[FileInput, 'Sticker'],
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: int = None,
reply_markup: ReplyMarkup = None,
timeout: DVInput[float] = DEFAULT_20,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> Message: