-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
_extbot.py
3879 lines (3695 loc) · 151 KB
/
_extbot.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=too-many-arguments
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2023
# 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 with convenience extensions."""
from copy import copy
from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
no_type_check,
overload,
)
from uuid import uuid4
from telegram import (
Animation,
Audio,
Bot,
BotCommand,
BotCommandScope,
BotDescription,
BotName,
BotShortDescription,
CallbackQuery,
Chat,
ChatAdministratorRights,
ChatInviteLink,
ChatMember,
ChatPermissions,
ChatPhoto,
Contact,
Document,
File,
ForumTopic,
GameHighScore,
InlineKeyboardMarkup,
InlineQueryResultsButton,
InputMedia,
InputSticker,
Location,
MaskPosition,
MenuButton,
Message,
MessageId,
PassportElementError,
PhotoSize,
Poll,
SentWebAppMessage,
ShippingOption,
Sticker,
StickerSet,
Update,
User,
UserProfilePhotos,
Venue,
Video,
VideoNote,
Voice,
WebhookInfo,
)
from telegram._utils.datetime import to_timestamp
from telegram._utils.defaultvalue import DEFAULT_NONE, DefaultValue
from telegram._utils.logging import get_logger
from telegram._utils.types import DVInput, FileInput, JSONDict, ODVInput, ReplyMarkup
from telegram.ext._callbackdatacache import CallbackDataCache
from telegram.ext._utils.types import RLARGS
from telegram.request import BaseRequest
from telegram.warnings import PTBUserWarning
if TYPE_CHECKING:
from telegram import (
InlineQueryResult,
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
LabeledPrice,
MessageEntity,
)
from telegram.ext import BaseRateLimiter, Defaults
HandledTypes = TypeVar("HandledTypes", bound=Union[Message, CallbackQuery, Chat])
class ExtBot(Bot, Generic[RLARGS]):
"""This object represents a Telegram Bot with convenience extensions.
Warning:
Not to be confused with :class:`telegram.Bot`.
For the documentation of the arguments, methods and attributes, please see
:class:`telegram.Bot`.
All API methods of this class have an additional keyword argument ``rate_limit_args``.
This can be used to pass additional information to the rate limiter, specifically to
:paramref:`telegram.ext.BaseRateLimiter.process_request.rate_limit_args`.
Warning:
* The keyword argument ``rate_limit_args`` can `not` be used, if :attr:`rate_limiter`
is :obj:`None`.
* The method :meth:`~telegram.Bot.get_updates` is the only method that does not have the
additional argument, as this method will never be rate limited.
Examples:
:any:`Arbitrary Callback Data Bot <examples.arbitrarycallbackdatabot>`
.. seealso:: :wiki:`Arbitrary callback_data <Arbitrary-callback_data>`
.. versionadded:: 13.6
.. versionchanged:: 20.0
Removed the attribute ``arbitrary_callback_data``. You can instead use
:attr:`bot.callback_data_cache.maxsize <telegram.ext.CallbackDataCache.maxsize>` to
access the size of the cache.
Args:
defaults (:class:`telegram.ext.Defaults`, optional): An object containing default values to
be used if not set explicitly in the bot methods.
arbitrary_callback_data (:obj:`bool` | :obj:`int`, optional): Whether to
allow arbitrary objects as callback data for :class:`telegram.InlineKeyboardButton`.
Pass an integer to specify the maximum number of objects cached in memory.
Defaults to :obj:`False`.
.. seealso:: :wiki:`Arbitrary callback_data <Arbitrary-callback_data>`
rate_limiter (:class:`telegram.ext.BaseRateLimiter`, optional): A rate limiter to use for
limiting the number of requests made by the bot per time interval.
.. versionadded:: 20.0
"""
__slots__ = ("_callback_data_cache", "_defaults", "_rate_limiter")
_LOGGER = get_logger(__name__, class_name="ExtBot")
# using object() would be a tiny bit safer, but a string plays better with the typing setup
__RL_KEY = uuid4().hex
@overload
def __init__(
self: "ExtBot[None]",
token: str,
base_url: str = "https://api.telegram.org/bot",
base_file_url: str = "https://api.telegram.org/file/bot",
request: Optional[BaseRequest] = None,
get_updates_request: Optional[BaseRequest] = None,
private_key: Optional[bytes] = None,
private_key_password: Optional[bytes] = None,
defaults: Optional["Defaults"] = None,
arbitrary_callback_data: Union[bool, int] = False,
local_mode: bool = False,
):
...
@overload
def __init__(
self: "ExtBot[RLARGS]",
token: str,
base_url: str = "https://api.telegram.org/bot",
base_file_url: str = "https://api.telegram.org/file/bot",
request: Optional[BaseRequest] = None,
get_updates_request: Optional[BaseRequest] = None,
private_key: Optional[bytes] = None,
private_key_password: Optional[bytes] = None,
defaults: Optional["Defaults"] = None,
arbitrary_callback_data: Union[bool, int] = False,
local_mode: bool = False,
rate_limiter: Optional["BaseRateLimiter[RLARGS]"] = None,
):
...
def __init__(
self,
token: str,
base_url: str = "https://api.telegram.org/bot",
base_file_url: str = "https://api.telegram.org/file/bot",
request: Optional[BaseRequest] = None,
get_updates_request: Optional[BaseRequest] = None,
private_key: Optional[bytes] = None,
private_key_password: Optional[bytes] = None,
defaults: Optional["Defaults"] = None,
arbitrary_callback_data: Union[bool, int] = False,
local_mode: bool = False,
rate_limiter: Optional["BaseRateLimiter[RLARGS]"] = None,
):
super().__init__(
token=token,
base_url=base_url,
base_file_url=base_file_url,
request=request,
get_updates_request=get_updates_request,
private_key=private_key,
private_key_password=private_key_password,
local_mode=local_mode,
)
with self._unfrozen():
self._defaults: Optional[Defaults] = defaults
self._rate_limiter: Optional[BaseRateLimiter] = rate_limiter
self._callback_data_cache: Optional[CallbackDataCache] = None
# set up callback_data
if arbitrary_callback_data is False:
return
if not isinstance(arbitrary_callback_data, bool):
maxsize = cast(int, arbitrary_callback_data)
else:
maxsize = 1024
self._callback_data_cache = CallbackDataCache(bot=self, maxsize=maxsize)
@classmethod
def _warn(
cls, message: str, category: Type[Warning] = PTBUserWarning, stacklevel: int = 0
) -> None:
"""We override this method to add one more level to the stacklevel, so that the warning
points to the user's code, not to the PTB code.
"""
super()._warn(message=message, category=category, stacklevel=stacklevel + 2)
@property
def callback_data_cache(self) -> Optional[CallbackDataCache]:
""":class:`telegram.ext.CallbackDataCache`: Optional. The cache for
objects passed as callback data for :class:`telegram.InlineKeyboardButton`.
Examples:
:any:`Arbitrary Callback Data Bot <examples.arbitrarycallbackdatabot>`
.. versionchanged:: 20.0
* This property is now read-only.
* This property is now optional and can be :obj:`None` if
:paramref:`~telegram.ext.ExtBot.arbitrary_callback_data` is set to :obj:`False`.
"""
return self._callback_data_cache
async def initialize(self) -> None:
"""See :meth:`telegram.Bot.initialize`. Also initializes the
:paramref:`ExtBot.rate_limiter` (if set)
by calling :meth:`telegram.ext.BaseRateLimiter.initialize`.
"""
# Initialize before calling super, because super calls get_me
if self.rate_limiter:
await self.rate_limiter.initialize()
await super().initialize()
async def shutdown(self) -> None:
"""See :meth:`telegram.Bot.shutdown`. Also shuts down the
:paramref:`ExtBot.rate_limiter` (if set) by
calling :meth:`telegram.ext.BaseRateLimiter.shutdown`.
"""
# Shut down the rate limiter before shutting down the request objects!
if self.rate_limiter:
await self.rate_limiter.shutdown()
await super().shutdown()
@classmethod
def _merge_api_rl_kwargs(
cls, api_kwargs: Optional[JSONDict], rate_limit_args: Optional[RLARGS]
) -> Optional[JSONDict]:
"""Inserts the `rate_limit_args` into `api_kwargs` with the special key `__RL_KEY` so
that we can extract them later without having to modify the `telegram.Bot` class.
"""
if not rate_limit_args:
return api_kwargs
if api_kwargs is None:
api_kwargs = {}
api_kwargs[cls.__RL_KEY] = rate_limit_args
return api_kwargs
@classmethod
def _extract_rl_kwargs(cls, data: Optional[JSONDict]) -> Optional[RLARGS]:
"""Extracts the `rate_limit_args` from `data` if it exists."""
if not data:
return None
return data.pop(cls.__RL_KEY, None)
async def _do_post(
self,
endpoint: str,
data: JSONDict,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
) -> Union[bool, JSONDict, List[JSONDict]]:
"""Order of method calls is: Bot.some_method -> Bot._post -> Bot._do_post.
So we can override Bot._do_post to add rate limiting.
"""
rate_limit_args = self._extract_rl_kwargs(data)
if not self.rate_limiter and rate_limit_args is not None:
raise ValueError(
"`rate_limit_args` can only be used if a `ExtBot.rate_limiter` is set."
)
# getting updates should not be rate limited!
if endpoint == "getUpdates" or not self.rate_limiter:
return await super()._do_post(
endpoint=endpoint,
data=data,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
read_timeout=read_timeout,
)
kwargs = {
"read_timeout": read_timeout,
"write_timeout": write_timeout,
"connect_timeout": connect_timeout,
"pool_timeout": pool_timeout,
}
self._LOGGER.debug(
"Passing request through rate limiter of type %s with rate_limit_args %s",
type(self.rate_limiter),
rate_limit_args,
)
return await self.rate_limiter.process_request(
callback=super()._do_post,
args=(endpoint, data),
kwargs=kwargs,
endpoint=endpoint,
data=data,
rate_limit_args=rate_limit_args,
)
@property
def defaults(self) -> Optional["Defaults"]:
"""The :class:`telegram.ext.Defaults` used by this bot, if any."""
# This is a property because defaults shouldn't be changed at runtime
return self._defaults
@property
def rate_limiter(self) -> Optional["BaseRateLimiter[RLARGS]"]:
"""The :class:`telegram.ext.BaseRateLimiter` used by this bot, if any.
.. versionadded:: 20.0
"""
# This is a property because the rate limiter shouldn't be changed at runtime
return self._rate_limiter
def _insert_defaults(self, data: Dict[str, object]) -> None:
"""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!
"""
# if we have Defaults, we
# 1) replace all DefaultValue instances with the relevant Defaults value. If there is none,
# we fall back to the default value of the bot method
# 2) convert all datetime.datetime objects to timestamps wrt the correct default timezone
# 3) set the correct parse_mode for all InputMedia objects
for key, val in data.items():
# 1)
if isinstance(val, DefaultValue):
data[key] = (
self.defaults.api_defaults.get(key, val.value)
if self.defaults
else DefaultValue.get_value(val)
)
# 2)
elif isinstance(val, datetime):
data[key] = to_timestamp(
val, tzinfo=self.defaults.tzinfo if self.defaults else None
)
# 3)
elif isinstance(val, InputMedia) and val.parse_mode is DEFAULT_NONE:
# Copy object as not to edit it in-place
copied_val = copy(val)
with copied_val._unfrozen():
copied_val.parse_mode = self.defaults.parse_mode if self.defaults else None
data[key] = copied_val
elif key == "media" and isinstance(val, Sequence):
# Copy objects as not to edit them in-place
copy_list = [copy(media) for media in val]
for media in copy_list:
if media.parse_mode is DEFAULT_NONE:
with media._unfrozen():
media.parse_mode = self.defaults.parse_mode if self.defaults else None
data[key] = copy_list
def _replace_keyboard(self, reply_markup: Optional[ReplyMarkup]) -> Optional[ReplyMarkup]:
# If the reply_markup is an inline keyboard and we allow arbitrary callback data, let the
# CallbackDataCache build a new keyboard with the data replaced. Otherwise return the input
if isinstance(reply_markup, InlineKeyboardMarkup) and self.callback_data_cache is not None:
return self.callback_data_cache.process_keyboard(reply_markup)
return reply_markup
def insert_callback_data(self, update: Update) -> None:
"""If this bot allows for arbitrary callback data, this inserts the cached data into all
corresponding buttons within this update.
Note:
Checks :attr:`telegram.Message.via_bot` and :attr:`telegram.Message.from_user`
to figure out if a) a reply markup exists and b) it was actually sent by this
bot. If not, the message will be returned unchanged.
Note that this will fail for channel posts, as :attr:`telegram.Message.from_user` is
:obj:`None` for those! In the corresponding reply markups, the callback data will be
replaced by :class:`telegram.ext.InvalidCallbackData`.
Warning:
*In place*, i.e. the passed :class:`telegram.Message` will be changed!
Args:
update (:class:`telegram.Update`): The update.
"""
# The only incoming updates that can directly contain a message sent by the bot itself are:
# * CallbackQueries
# * Messages where the pinned_message is sent by the bot
# * Messages where the reply_to_message is sent by the bot
# * Messages where via_bot is the bot
# Finally there is effective_chat.pinned message, but that's only returned in get_chat
if update.callback_query:
self._insert_callback_data(update.callback_query)
# elif instead of if, as effective_message includes callback_query.message
# and that has already been processed
elif update.effective_message:
self._insert_callback_data(update.effective_message)
def _insert_callback_data(self, obj: HandledTypes) -> HandledTypes:
if self.callback_data_cache is None:
return obj
if isinstance(obj, CallbackQuery):
self.callback_data_cache.process_callback_query(obj)
return obj # type: ignore[return-value]
if isinstance(obj, Message):
if obj.reply_to_message:
# reply_to_message can't contain further reply_to_messages, so no need to check
self.callback_data_cache.process_message(obj.reply_to_message)
if obj.reply_to_message.pinned_message:
# pinned messages can't contain reply_to_message, no need to check
self.callback_data_cache.process_message(obj.reply_to_message.pinned_message)
if obj.pinned_message:
# pinned messages can't contain reply_to_message, no need to check
self.callback_data_cache.process_message(obj.pinned_message)
# Finally, handle the message itself
self.callback_data_cache.process_message(message=obj)
return obj # type: ignore[return-value]
if isinstance(obj, Chat) and obj.pinned_message:
self.callback_data_cache.process_message(obj.pinned_message)
return obj
async def _send_message(
self,
endpoint: str,
data: JSONDict,
reply_to_message_id: Optional[int] = None,
disable_notification: ODVInput[bool] = DEFAULT_NONE,
reply_markup: Optional[ReplyMarkup] = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: ODVInput[bool] = DEFAULT_NONE,
message_thread_id: Optional[int] = None,
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence["MessageEntity"]] = None,
disable_web_page_preview: ODVInput[bool] = DEFAULT_NONE,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Any:
# We override this method to call self._replace_keyboard and self._insert_callback_data.
# This covers most methods that have a reply_markup
result = await super()._send_message(
endpoint=endpoint,
data=data,
reply_to_message_id=reply_to_message_id,
disable_notification=disable_notification,
reply_markup=self._replace_keyboard(reply_markup),
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
message_thread_id=message_thread_id,
caption=caption,
parse_mode=parse_mode,
caption_entities=caption_entities,
disable_web_page_preview=disable_web_page_preview,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
if isinstance(result, Message):
self._insert_callback_data(result)
return result
async def get_updates(
self,
offset: Optional[int] = None,
limit: Optional[int] = None,
timeout: Optional[int] = None,
allowed_updates: Optional[Sequence[str]] = None,
*,
read_timeout: float = 2,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Tuple[Update, ...]:
updates = await super().get_updates(
offset=offset,
limit=limit,
timeout=timeout,
allowed_updates=allowed_updates,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
for update in updates:
self.insert_callback_data(update)
return updates
def _effective_inline_results(
self,
results: Union[
Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]]
],
next_offset: Optional[str] = None,
current_offset: Optional[str] = None,
) -> Tuple[Sequence["InlineQueryResult"], Optional[str]]:
"""This method is called by Bot.answer_inline_query to build the actual results list.
Overriding this to call self._replace_keyboard suffices
"""
effective_results, next_offset = super()._effective_inline_results(
results=results, next_offset=next_offset, current_offset=current_offset
)
# Process arbitrary callback
if self.callback_data_cache is None:
return effective_results, next_offset
results = []
for result in effective_results:
# All currently existingInlineQueryResults have a reply_markup, but future ones
# might not have. Better be save than sorry
if not hasattr(result, "reply_markup"):
results.append(result)
else:
# We build a new result in case the user wants to use the same object in
# different places
new_result = copy(result)
with new_result._unfrozen():
markup = self._replace_keyboard(result.reply_markup)
new_result.reply_markup = markup
results.append(new_result)
return results, next_offset
@no_type_check # mypy doesn't play too well with hasattr
def _insert_defaults_for_ilq_results(self, res: "InlineQueryResult") -> "InlineQueryResult":
"""This method is called by Bot.answer_inline_query to replace `DefaultValue(obj)` with
`obj`.
Overriding this to call insert the actual desired default values.
"""
# Copy the objects that need modification to avoid modifying the original object
copied = False
if hasattr(res, "parse_mode") and res.parse_mode is DEFAULT_NONE:
res = copy(res)
with res._unfrozen():
copied = True
res.parse_mode = self.defaults.parse_mode if self.defaults else None
if hasattr(res, "input_message_content") and res.input_message_content:
if (
hasattr(res.input_message_content, "parse_mode")
and res.input_message_content.parse_mode is DEFAULT_NONE
):
if not copied:
res = copy(res)
copied = True
with res.input_message_content._unfrozen():
res.input_message_content.parse_mode = (
self.defaults.parse_mode if self.defaults else None
)
if (
hasattr(res.input_message_content, "disable_web_page_preview")
and res.input_message_content.disable_web_page_preview is DEFAULT_NONE
):
if not copied:
res = copy(res)
with res.input_message_content._unfrozen():
res.input_message_content.disable_web_page_preview = (
self.defaults.disable_web_page_preview if self.defaults else None
)
return res
async def stop_poll(
self,
chat_id: Union[int, str],
message_id: int,
reply_markup: Optional[InlineKeyboardMarkup] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> Poll:
# We override this method to call self._replace_keyboard
return await super().stop_poll(
chat_id=chat_id,
message_id=message_id,
reply_markup=self._replace_keyboard(reply_markup),
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def copy_message(
self,
chat_id: Union[int, str],
from_chat_id: Union[str, int],
message_id: int,
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence["MessageEntity"]] = None,
disable_notification: DVInput[bool] = DEFAULT_NONE,
reply_to_message_id: Optional[int] = None,
allow_sending_without_reply: DVInput[bool] = DEFAULT_NONE,
reply_markup: Optional[ReplyMarkup] = None,
protect_content: ODVInput[bool] = DEFAULT_NONE,
message_thread_id: Optional[int] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> MessageId:
# We override this method to call self._replace_keyboard
return await super().copy_message(
chat_id=chat_id,
from_chat_id=from_chat_id,
message_id=message_id,
caption=caption,
parse_mode=parse_mode,
caption_entities=caption_entities,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
allow_sending_without_reply=allow_sending_without_reply,
reply_markup=self._replace_keyboard(reply_markup),
protect_content=protect_content,
message_thread_id=message_thread_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def get_chat(
self,
chat_id: Union[str, int],
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> Chat:
# We override this method to call self._insert_callback_data
result = await super().get_chat(
chat_id=chat_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
return self._insert_callback_data(result)
async def add_sticker_to_set(
self,
user_id: Union[str, int],
name: str,
emojis: Optional[str] = None, # Was made optional for compatibility reasons
png_sticker: Optional[FileInput] = None,
mask_position: Optional[MaskPosition] = None,
tgs_sticker: Optional[FileInput] = None,
webm_sticker: Optional[FileInput] = None,
sticker: Optional[
InputSticker
] = None, # Actually a required param, but is optional for compat.
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = 20,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().add_sticker_to_set(
user_id=user_id,
name=name,
sticker=sticker,
emojis=emojis,
png_sticker=png_sticker,
mask_position=mask_position,
tgs_sticker=tgs_sticker,
webm_sticker=webm_sticker,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def answer_callback_query(
self,
callback_query_id: str,
text: Optional[str] = None,
show_alert: Optional[bool] = None,
url: Optional[str] = None,
cache_time: Optional[int] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().answer_callback_query(
callback_query_id=callback_query_id,
text=text,
show_alert=show_alert,
url=url,
cache_time=cache_time,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def answer_inline_query(
self,
inline_query_id: str,
results: Union[
Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]]
],
cache_time: Optional[int] = None,
is_personal: Optional[bool] = None,
next_offset: Optional[str] = None,
switch_pm_text: Optional[str] = None,
switch_pm_parameter: Optional[str] = None,
button: Optional[InlineQueryResultsButton] = None,
*,
current_offset: Optional[str] = None,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().answer_inline_query(
inline_query_id=inline_query_id,
results=results,
cache_time=cache_time,
is_personal=is_personal,
next_offset=next_offset,
switch_pm_text=switch_pm_text,
switch_pm_parameter=switch_pm_parameter,
current_offset=current_offset,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
button=button,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def answer_pre_checkout_query(
self,
pre_checkout_query_id: str,
ok: bool,
error_message: Optional[str] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().answer_pre_checkout_query(
pre_checkout_query_id=pre_checkout_query_id,
ok=ok,
error_message=error_message,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def answer_shipping_query(
self,
shipping_query_id: str,
ok: bool,
shipping_options: Optional[Sequence[ShippingOption]] = None,
error_message: Optional[str] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().answer_shipping_query(
shipping_query_id=shipping_query_id,
ok=ok,
shipping_options=shipping_options,
error_message=error_message,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def answer_web_app_query(
self,
web_app_query_id: str,
result: "InlineQueryResult",
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> SentWebAppMessage:
return await super().answer_web_app_query(
web_app_query_id=web_app_query_id,
result=result,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def approve_chat_join_request(
self,
chat_id: Union[str, int],
user_id: int,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().approve_chat_join_request(
chat_id=chat_id,
user_id=user_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def ban_chat_member(
self,
chat_id: Union[str, int],
user_id: Union[str, int],
until_date: Optional[Union[int, datetime]] = None,
revoke_messages: Optional[bool] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().ban_chat_member(
chat_id=chat_id,
user_id=user_id,
until_date=until_date,
revoke_messages=revoke_messages,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def ban_chat_sender_chat(
self,
chat_id: Union[str, int],
sender_chat_id: int,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> bool:
return await super().ban_chat_sender_chat(
chat_id=chat_id,
sender_chat_id=sender_chat_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def create_chat_invite_link(
self,
chat_id: Union[str, int],
expire_date: Optional[Union[int, datetime]] = None,
member_limit: Optional[int] = None,
name: Optional[str] = None,
creates_join_request: Optional[bool] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
rate_limit_args: Optional[RLARGS] = None,
) -> ChatInviteLink:
return await super().create_chat_invite_link(
chat_id=chat_id,
expire_date=expire_date,
member_limit=member_limit,
name=name,
creates_join_request=creates_join_request,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
)
async def create_invoice_link(
self,
title: str,
description: str,
payload: str,