forked from eternnoir/pyTelegramBotAPI
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync_telebot.py
More file actions
9668 lines (7374 loc) · 461 KB
/
async_telebot.py
File metadata and controls
9668 lines (7374 loc) · 461 KB
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
# -*- coding: utf-8 -*-
from datetime import datetime
import logging
import re
import traceback
from typing import Any, Awaitable, Callable, List, Optional, Union, Dict
import sys
# this imports are used to avoid circular import error
# noinspection PyUnresolvedReferences
import telebot.util
import telebot.types
# storages
from telebot.asyncio_storage import StateMemoryStorage, StatePickleStorage, StateStorageBase
from telebot.asyncio_handler_backends import BaseMiddleware, CancelUpdate, SkipHandler, State, ContinueHandling
from inspect import signature, iscoroutinefunction
from telebot import util, types, asyncio_helper
import asyncio
from telebot import asyncio_filters
logger = logging.getLogger('TeleBot')
REPLY_MARKUP_TYPES = Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup,
types.ReplyKeyboardRemove, types.ForceReply]
import string
import random
import ssl
"""
Module : telebot
"""
class Handler:
"""
Class for (next step|reply) handlers
"""
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
def __getitem__(self, item):
return getattr(self, item)
class ExceptionHandler:
"""
Class for handling exceptions while Polling
"""
# noinspection PyMethodMayBeStatic,PyUnusedLocal
async def handle(self, exception):
return False
class AsyncTeleBot:
"""
This is the main asynchronous class for Bot.
It allows you to add handlers for different kind of updates.
Usage:
.. code-block:: python3
:caption: Using asynchronous implementation of TeleBot.
from telebot.async_telebot import AsyncTeleBot
bot = AsyncTeleBot('token') # get token from @BotFather
# now you can register other handlers/update listeners,
# and use bot methods.
# Remember to use async/await keywords when necessary.
See more examples in examples/ directory:
https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples
.. note::
Install coloredlogs module to specify colorful_logs=True
:param token: Token of a bot, obtained from @BotFather
:type token: :obj:`str`
:param parse_mode: Default parse mode, defaults to None
:type parse_mode: :obj:`str`, optional
:param offset: Offset used in get_updates, defaults to None
:type offset: :obj:`int`, optional
:param exception_handler: Exception handler, which will handle the exception occured, defaults to None
:type exception_handler: Optional[ExceptionHandler], optional
:param state_storage: Storage for states, defaults to StateMemoryStorage()
:type state_storage: :class:`telebot.asyncio_storage.StateMemoryStorage`, optional
:param disable_web_page_preview: Default value for disable_web_page_preview, defaults to None
:type disable_web_page_preview: :obj:`bool`, optional
:param disable_notification: Default value for disable_notification, defaults to None
:type disable_notification: :obj:`bool`, optional
:param protect_content: Default value for protect_content, defaults to None
:type protect_content: :obj:`bool`, optional
:param allow_sending_without_reply: Deprecated - Use reply_parameters instead. Default value for allow_sending_without_reply, defaults to None
:type allow_sending_without_reply: :obj:`bool`, optional
:param colorful_logs: Outputs colorful logs
:type colorful_logs: :obj:`bool`, optional
:param validate_token: Validate token, defaults to True;
:type validate_token: :obj:`bool`, optional
:raises ImportError: If coloredlogs module is not installed and colorful_logs is True
:raises ValueError: If token is invalid
"""
def __init__(self, token: str, parse_mode: Optional[str]=None, offset: Optional[int]=None,
exception_handler: Optional[ExceptionHandler]=None,
state_storage: Optional[StateStorageBase]=StateMemoryStorage(),
disable_web_page_preview: Optional[bool]=None,
disable_notification: Optional[bool]=None,
protect_content: Optional[bool]=None,
allow_sending_without_reply: Optional[bool]=None,
colorful_logs: Optional[bool]=False,
validate_token: Optional[bool]=True) -> None:
# update-related
self.token = token
self.offset = offset
# logs-related
if colorful_logs:
try:
import coloredlogs
coloredlogs.install(logger=logger, level=logger.level)
except ImportError:
raise ImportError(
'Install coloredlogs module to use colorful_logs option.'
)
# properties
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
self.disable_notification = disable_notification
self.protect_content = protect_content
self.allow_sending_without_reply = allow_sending_without_reply
# states
self.current_states = state_storage
# handlers
self.update_listener = []
self.exception_handler = exception_handler
self.message_handlers = []
self.edited_message_handlers = []
self.channel_post_handlers = []
self.edited_channel_post_handlers = []
self.message_reaction_handlers = []
self.message_reaction_count_handlers = []
self.inline_handlers = []
self.chosen_inline_handlers = []
self.callback_query_handlers = []
self.shipping_query_handlers = []
self.pre_checkout_query_handlers = []
self.poll_handlers = []
self.poll_answer_handlers = []
self.my_chat_member_handlers = []
self.chat_member_handlers = []
self.chat_join_request_handlers = []
self.removed_chat_boost_handlers = []
self.chat_boost_handlers = []
self.business_connection_handlers = []
self.business_message_handlers = []
self.edited_business_message_handlers = []
self.deleted_business_messages_handlers = []
self.purchased_paid_media_handlers = []
self.custom_filters = {}
self.state_handlers = []
self.middlewares = []
self._user = None # set during polling
if validate_token:
util.validate_token(self.token)
self.bot_id: Union[int, None] = util.extract_bot_id(self.token) # subject to change, unspecified
@property
def user(self):
return self._user
async def close_session(self):
"""
Closes existing session of aiohttp.
Use this function if you stop polling/webhooks.
"""
await asyncio_helper.session_manager.session.close()
async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None,
timeout: Optional[int]=20, allowed_updates: Optional[List]=None, request_timeout: Optional[int]=None) -> List[types.Update]:
"""
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Telegram documentation: https://core.telegram.org/bots/api#getupdates
:param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates.
By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset
higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue.
All previous updates will forgotten.
:type offset: :obj:`int`, optional
:param limit: Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.
:type limit: :obj:`int`, optional
:param timeout: Request connection timeout
:type timeout: :obj:`int`, optional
:param allowed_updates: Array of string. List the types of updates you want your bot to receive.
:type allowed_updates: :obj:`list`, optional
:param request_timeout: Timeout in seconds for request.
:type request_timeout: :obj:`int`, optional
:return: An Array of Update objects is returned.
:rtype: :obj:`list` of :class:`telebot.types.Update`
"""
json_updates = await asyncio_helper.get_updates(self.token, offset, limit, timeout, allowed_updates, request_timeout)
return [types.Update.de_json(ju) for ju in json_updates]
def _setup_change_detector(self, path_to_watch: str) -> None:
try:
from watchdog.observers import Observer
from telebot.ext.reloader import EventHandler
except ImportError:
raise ImportError(
'Please install watchdog and psutil before using restart_on_change option.'
)
self.event_handler = EventHandler()
path = path_to_watch if path_to_watch else None
if path is None:
# Make it possible to specify --path argument to the script
path = sys.argv[sys.argv.index('--path') + 1] if '--path' in sys.argv else '.'
self.event_observer = Observer()
self.event_observer.schedule(self.event_handler, path, recursive=True)
self.event_observer.start()
async def polling(self, non_stop: bool=True, skip_pending=False, interval: int=0, timeout: int=20,
request_timeout: Optional[int]=None, allowed_updates: Optional[List[str]]=None,
none_stop: Optional[bool]=None, restart_on_change: Optional[bool]=False, path_to_watch: Optional[str]=None):
"""
Runs bot in long-polling mode in a main loop.
This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.
Warning: Do not call this function more than once!
Always gets updates.
.. note::
Install watchdog and psutil before using restart_on_change option.
:param non_stop: Do not stop polling when an ApiException occurs.
:type non_stop: :obj:`bool`
:param skip_pending: skip old updates
:type skip_pending: :obj:`bool`
:param interval: Delay between two update retrivals
:type interval: :obj:`int`
:param timeout: Request connection timeout
:type timeout: :obj:`int`
:param request_timeout: Timeout in seconds for get_updates(Defaults to None)
:type request_timeout: :obj:`int`
:param allowed_updates: A list of the update types you want your bot to receive.
For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
See util.update_types for a complete list of available update types.
Specify an empty list to receive all update types except chat_member (default).
If not specified, the previous setting will be used.
Please note that this parameter doesn't affect updates created before the call to the get_updates,
so unwanted updates may be received for a short period of time.
:type allowed_updates: :obj:`list` of :obj:`str`
:param none_stop: Deprecated, use non_stop. Old typo, kept for backward compatibility.
:type none_stop: :obj:`bool`
:param restart_on_change: Restart a file on file(s) change. Defaults to False.
:type restart_on_change: :obj:`bool`
:param path_to_watch: Path to watch for changes. Defaults to current directory
:type path_to_watch: :obj:`str`
:return:
"""
if none_stop is not None:
logger.warning('The parameter "none_stop" is deprecated. Use "non_stop" instead.')
non_stop = none_stop
if skip_pending:
await self.skip_updates()
if restart_on_change:
self._setup_change_detector(path_to_watch)
await self._process_polling(non_stop, interval, timeout, request_timeout, allowed_updates)
async def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Optional[bool]=False, request_timeout: Optional[int]=None,
logger_level: Optional[int]=logging.ERROR, allowed_updates: Optional[List[str]]=None,
restart_on_change: Optional[bool]=False, path_to_watch: Optional[str]=None, *args, **kwargs):
"""
Wrap polling with infinite loop and exception handling to avoid bot stops polling.
.. note::
Install watchdog and psutil before using restart_on_change option.
:param timeout: Timeout in seconds for get_updates(Defaults to None)
:type timeout: :obj:`int`
:param skip_pending: skip old updates
:type skip_pending: :obj:`bool`
:param request_timeout: Aiohttp's request timeout. Defaults to 5 minutes(aiohttp.ClientTimeout).
:type request_timeout: :obj:`int`
:param logger_level: Custom logging level for infinity_polling logging.
Use logger levels from logging as a value. None/NOTSET = no error logging
:type logger_level: :obj:`int`
:param allowed_updates: A list of the update types you want your bot to receive.
For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
See util.update_types for a complete list of available update types.
Specify an empty list to receive all update types except chat_member (default).
If not specified, the previous setting will be used.
Please note that this parameter doesn't affect updates created before the call to the get_updates,
so unwanted updates may be received for a short period of time.
:type allowed_updates: :obj:`list` of :obj:`str`
:param restart_on_change: Restart a file on file(s) change. Defaults to False
:type restart_on_change: :obj:`bool`
:param path_to_watch: Path to watch for changes. Defaults to current directory
:type path_to_watch: :obj:`str`
:return: None
"""
if skip_pending:
await self.skip_updates()
self._polling = True
if restart_on_change:
self._setup_change_detector(path_to_watch)
while self._polling:
try:
await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout,
allowed_updates=allowed_updates, *args, **kwargs)
except Exception as e:
if logger_level and logger_level >= logging.ERROR:
logger.error("Infinity polling exception: %s", self.__hide_token(str(e)))
if logger_level and logger_level >= logging.DEBUG:
logger.error("Exception traceback:\n%s", self.__hide_token(traceback.format_exc()))
await asyncio.sleep(3)
continue
if logger_level and logger_level >= logging.INFO:
logger.error("Infinity polling: polling exited")
if logger_level and logger_level >= logging.INFO:
logger.error("Break infinity polling")
async def _handle_exception(self, exception: Exception) -> bool:
if self.exception_handler is None:
return False
if iscoroutinefunction(self.exception_handler.handle):
handled = await self.exception_handler.handle(exception)
else:
handled = self.exception_handler.handle(exception) # noqa
return handled
def __hide_token(self, message: str) -> str:
if self.token in message:
code = self.token.split(':')[1]
return message.replace(code, "*" * len(code))
else:
return message
async def _handle_error_interval(self, error_interval: float):
logger.debug('Waiting for %s seconds before retrying', error_interval)
await asyncio.sleep(error_interval)
if error_interval * 2 < 60: # same logic as sync
error_interval *= 2
else:
error_interval = 60
return error_interval
async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20,
request_timeout: int=None, allowed_updates: Optional[List[str]]=None):
"""
Function to process polling.
:param non_stop: Do not stop polling when an ApiException occurs.
:param interval: Delay between two update retrivals
:param timeout: Request connection timeout
:param request_timeout: Timeout in seconds for long polling (see API docs)
:param allowed_updates: A list of the update types you want your bot to receive.
For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
See util.update_types for a complete list of available update types.
Specify an empty list to receive all update types except chat_member (default).
If not specified, the previous setting will be used.
Please note that this parameter doesn't affect updates created before the call to the get_updates,
so unwanted updates may be received for a short period of time.
:return:
"""
if not non_stop:
# show warning
logger.warning("Setting non_stop to False will stop polling on API and system exceptions.")
self._user = await self.get_me()
logger.info('Starting your bot with username: [@%s]', self.user.username)
self._polling = True
error_interval = 0.25
try:
while self._polling:
try:
updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout, request_timeout=request_timeout)
if updates:
self.offset = updates[-1].update_id + 1
# noinspection PyAsyncCall
asyncio.create_task(self.process_new_updates(updates)) # Seperate task for processing updates
if interval: await asyncio.sleep(interval)
error_interval = 0.25 # drop error_interval if no errors
except KeyboardInterrupt:
return
except asyncio.CancelledError:
return
except asyncio_helper.RequestTimeout as e:
handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', self.__hide_token(str(e)))
logger.debug(self.__hide_token(traceback.format_exc()))
if non_stop:
error_interval = await self._handle_error_interval(error_interval)
if non_stop or handled:
continue
else:
return
except asyncio_helper.ApiException as e:
handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', self.__hide_token(str(e)))
logger.debug(self.__hide_token(traceback.format_exc()))
if non_stop:
error_interval = await self._handle_error_interval(error_interval)
if non_stop or handled:
continue
else:
break
except Exception as e:
handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', str(e))
logger.debug(traceback.format_exc())
if non_stop:
error_interval = await self._handle_error_interval(error_interval)
if non_stop or handled:
continue
else:
break
finally:
self._polling = False
await self.close_session()
logger.warning('Polling is stopped.')
@staticmethod
def _loop_create_task(coro):
return asyncio.create_task(coro)
async def _process_updates(self, handlers, messages, update_type):
"""
Process updates.
:param handlers:
:param messages:
:return:
"""
tasks = []
middlewares = await self._get_middlewares(update_type)
for message in messages:
tasks.append(self._run_middlewares_and_handlers(message, handlers, middlewares, update_type))
await asyncio.gather(*tasks)
async def _run_middlewares_and_handlers(self, message, handlers, middlewares, update_type):
"""
This method is made to run handlers and middlewares in queue.
:param message: received message (update part) to process with handlers and/or middlewares
:param handlers: all created handlers (not filtered)
:param middlewares: middlewares that should be executed (already filtered)
:param update_type: handler/update type (Update field name)
:return:
"""
handler_error = None
data = {}
skip_handlers = False
if middlewares:
for middleware in middlewares:
if middleware.update_sensitive:
if hasattr(middleware, f'pre_process_{update_type}'):
middleware_result = await getattr(middleware, f'pre_process_{update_type}')(message, data)
else:
logger.error('Middleware {} does not have pre_process_{} method. pre_process function execution was skipped.'.format(middleware.__class__.__name__, update_type))
middleware_result = None
else:
middleware_result = await middleware.pre_process(message, data)
if isinstance(middleware_result, CancelUpdate):
return
elif isinstance(middleware_result, SkipHandler):
skip_handlers = True
if handlers and not(skip_handlers):
try:
for handler in handlers:
params = []
process_update = await self._test_message_handler(handler, message)
if not process_update: continue
for i in signature(handler['function']).parameters:
params.append(i)
if len(params) == 1:
result = await handler['function'](message)
elif "data" in params:
if len(params) == 2:
result = await handler['function'](message, data)
elif len(params) == 3:
result = await handler['function'](message, data=data, bot=self)
else:
logger.error("It is not allowed to pass data and values inside data to the handler. Check your handler: {}".format(handler['function']))
return
else:
data_copy = data.copy()
for key in list(data_copy):
# remove data from data_copy if handler does not accept it
if key not in params:
del data_copy[key]
if handler.get('pass_bot'):
data_copy["bot"] = self
if len(data_copy) > len(params) - 1: # remove the message parameter
logger.error("You are passing more data than the handler needs. Check your handler: {}".format(handler['function']))
return
result = await handler["function"](message, **data_copy)
if not isinstance(result, ContinueHandling):
break
except Exception as e:
handler_error = e
handled = await self._handle_exception(e)
if not handled:
logger.error(str(e))
logger.debug("Exception traceback:\n%s", traceback.format_exc())
if middlewares:
for middleware in middlewares:
if middleware.update_sensitive:
if hasattr(middleware, f'post_process_{update_type}'):
await getattr(middleware, f'post_process_{update_type}')(message, data, handler_error)
else:
logger.error('Middleware {} does not have post_process_{} method. post_process function execution was skipped.'.format(middleware.__class__.__name__, update_type))
else: await middleware.post_process(message, data, handler_error)
async def process_new_updates(self, updates: List[types.Update]):
"""
Process new updates.
Just pass list of updates - each update should be
instance of Update object.
:param updates: list of updates
:type updates: :obj:`list` of :obj:`telebot.types.Update`
:return: None
"""
upd_count = len(updates)
logger.info('Received {0} new updates'.format(upd_count))
if upd_count == 0: return
new_messages = None
new_edited_messages = None
new_channel_posts = None
new_edited_channel_posts = None
new_message_reactions = None
new_message_reaction_count_handlers = None
new_inline_queries = None
new_chosen_inline_results = None
new_callback_queries = None
new_shipping_queries = None
new_pre_checkout_queries = None
new_polls = None
new_poll_answers = None
new_my_chat_members = None
new_chat_members = None
chat_join_request = None
removed_chat_boost_handlers = None
chat_boost_handlers = None
new_business_connections = None
new_business_messages = None
new_edited_business_messages = None
new_deleted_business_messages = None
new_purchased_paid_media = None
for update in updates:
logger.debug('Processing updates: {0}'.format(update))
if update.message:
if new_messages is None: new_messages = []
new_messages.append(update.message)
if update.edited_message:
if new_edited_messages is None: new_edited_messages = []
new_edited_messages.append(update.edited_message)
if update.channel_post:
if new_channel_posts is None: new_channel_posts = []
new_channel_posts.append(update.channel_post)
if update.edited_channel_post:
if new_edited_channel_posts is None: new_edited_channel_posts = []
new_edited_channel_posts.append(update.edited_channel_post)
if update.inline_query:
if new_inline_queries is None: new_inline_queries = []
new_inline_queries.append(update.inline_query)
if update.chosen_inline_result:
if new_chosen_inline_results is None: new_chosen_inline_results = []
new_chosen_inline_results.append(update.chosen_inline_result)
if update.callback_query:
if new_callback_queries is None: new_callback_queries = []
new_callback_queries.append(update.callback_query)
if update.shipping_query:
if new_shipping_queries is None: new_shipping_queries = []
new_shipping_queries.append(update.shipping_query)
if update.pre_checkout_query:
if new_pre_checkout_queries is None: new_pre_checkout_queries = []
new_pre_checkout_queries.append(update.pre_checkout_query)
if update.poll:
if new_polls is None: new_polls = []
new_polls.append(update.poll)
if update.poll_answer:
if new_poll_answers is None: new_poll_answers = []
new_poll_answers.append(update.poll_answer)
if update.my_chat_member:
if new_my_chat_members is None: new_my_chat_members = []
new_my_chat_members.append(update.my_chat_member)
if update.chat_member:
if new_chat_members is None: new_chat_members = []
new_chat_members.append(update.chat_member)
if update.chat_join_request:
if chat_join_request is None: chat_join_request = []
chat_join_request.append(update.chat_join_request)
if update.message_reaction:
if new_message_reactions is None: new_message_reactions = []
new_message_reactions.append(update.message_reaction)
if update.message_reaction_count:
if new_message_reaction_count_handlers is None: new_message_reaction_count_handlers = []
new_message_reaction_count_handlers.append(update.message_reaction_count)
if update.chat_boost:
if chat_boost_handlers is None: chat_boost_handlers = []
chat_boost_handlers.append(update.chat_boost)
if update.removed_chat_boost:
if removed_chat_boost_handlers is None: removed_chat_boost_handlers = []
removed_chat_boost_handlers.append(update.removed_chat_boost)
if update.business_connection:
if new_business_connections is None: new_business_connections = []
new_business_connections.append(update.business_connection)
if update.business_message:
if new_business_messages is None: new_business_messages = []
new_business_messages.append(update.business_message)
if update.edited_business_message:
if new_edited_business_messages is None: new_edited_business_messages = []
new_edited_business_messages.append(update.edited_business_message)
if update.deleted_business_messages:
if new_deleted_business_messages is None: new_deleted_business_messages = []
new_deleted_business_messages.append(update.deleted_business_messages)
if update.purchased_paid_media:
if new_purchased_paid_media is None: new_purchased_paid_media = []
new_purchased_paid_media.append(update.purchased_paid_media)
if new_messages:
await self.process_new_messages(new_messages)
if new_edited_messages:
await self.process_new_edited_messages(new_edited_messages)
if new_channel_posts:
await self.process_new_channel_posts(new_channel_posts)
if new_edited_channel_posts:
await self.process_new_edited_channel_posts(new_edited_channel_posts)
if new_inline_queries:
await self.process_new_inline_query(new_inline_queries)
if new_chosen_inline_results:
await self.process_new_chosen_inline_query(new_chosen_inline_results)
if new_callback_queries:
await self.process_new_callback_query(new_callback_queries)
if new_shipping_queries:
await self.process_new_shipping_query(new_shipping_queries)
if new_pre_checkout_queries:
await self.process_new_pre_checkout_query(new_pre_checkout_queries)
if new_polls:
await self.process_new_poll(new_polls)
if new_poll_answers:
await self.process_new_poll_answer(new_poll_answers)
if new_my_chat_members:
await self.process_new_my_chat_member(new_my_chat_members)
if new_chat_members:
await self.process_new_chat_member(new_chat_members)
if chat_join_request:
await self.process_chat_join_request(chat_join_request)
if new_message_reactions:
await self.process_new_message_reaction(new_message_reactions)
if new_message_reaction_count_handlers:
await self.process_new_message_reaction_count(new_message_reaction_count_handlers)
if chat_boost_handlers:
await self.process_new_chat_boost(chat_boost_handlers)
if new_business_connections:
await self.process_new_business_connection(new_business_connections)
if new_business_messages:
await self.process_new_business_message(new_business_messages)
if new_edited_business_messages:
await self.process_new_edited_business_message(new_edited_business_messages)
if new_deleted_business_messages:
await self.process_new_deleted_business_messages(new_deleted_business_messages)
if new_purchased_paid_media:
await self.process_new_purchased_paid_media(new_purchased_paid_media)
async def process_new_messages(self, new_messages):
"""
:meta private:
"""
await self.__notify_update(new_messages)
await self._process_updates(self.message_handlers, new_messages, 'message')
async def process_new_edited_messages(self, edited_message):
"""
:meta private:
"""
await self._process_updates(self.edited_message_handlers, edited_message, 'edited_message')
async def process_new_channel_posts(self, channel_post):
"""
:meta private:
"""
await self._process_updates(self.channel_post_handlers, channel_post , 'channel_post')
async def process_new_edited_channel_posts(self, edited_channel_post):
"""
:meta private:
"""
await self._process_updates(self.edited_channel_post_handlers, edited_channel_post, 'edited_channel_post')
async def process_new_message_reaction(self, message_reaction):
"""
:meta private:
"""
await self._process_updates(self.message_reaction_handlers, message_reaction, 'message_reaction')
async def process_new_message_reaction_count(self, message_reaction_count):
"""
:meta private:
"""
await self._process_updates(self.message_reaction_count_handlers, message_reaction_count, 'message_reaction_count')
async def process_new_inline_query(self, new_inline_queries):
"""
:meta private:
"""
await self._process_updates(self.inline_handlers, new_inline_queries, 'inline_query')
async def process_new_chosen_inline_query(self, new_chosen_inline_queries):
"""
:meta private:
"""
await self._process_updates(self.chosen_inline_handlers, new_chosen_inline_queries, 'chosen_inline_query')
async def process_new_callback_query(self, new_callback_queries):
"""
:meta private:
"""
await self._process_updates(self.callback_query_handlers, new_callback_queries, 'callback_query')
async def process_new_shipping_query(self, new_shipping_queries):
"""
:meta private:
"""
await self._process_updates(self.shipping_query_handlers, new_shipping_queries, 'shipping_query')
async def process_new_pre_checkout_query(self, pre_checkout_queries):
"""
:meta private:
"""
await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_queries, 'pre_checkout_query')
async def process_new_poll(self, polls):
"""
:meta private:
"""
await self._process_updates(self.poll_handlers, polls, 'poll')
async def process_new_poll_answer(self, poll_answers):
"""
:meta private:
"""
await self._process_updates(self.poll_answer_handlers, poll_answers, 'poll_answer')
async def process_new_my_chat_member(self, my_chat_members):
"""
:meta private:
"""
await self._process_updates(self.my_chat_member_handlers, my_chat_members, 'my_chat_member')
async def process_new_chat_member(self, chat_members):
"""
:meta private:
"""
await self._process_updates(self.chat_member_handlers, chat_members, 'chat_member')
async def process_chat_join_request(self, chat_join_request):
"""
:meta private:
"""
await self._process_updates(self.chat_join_request_handlers, chat_join_request, 'chat_join_request')
async def process_new_chat_boost(self, chat_boost):
"""
:meta private:
"""
await self._process_updates(self.chat_boost_handlers, chat_boost, 'chat_boost')
async def process_new_removed_chat_boost(self, removed_chat_boost):
"""
:meta private:
"""
await self._process_updates(self.removed_chat_boost_handlers, removed_chat_boost, 'removed_chat_boost')
async def process_new_business_connection(self, new_business_connections):
"""
:meta private:
"""
await self._process_updates(self.business_connection_handlers, new_business_connections, 'business_connection')
async def process_new_business_message(self, new_business_messages):
"""
:meta private:
"""
await self._process_updates(self.business_message_handlers, new_business_messages, 'business_message')
async def process_new_edited_business_message(self, new_edited_business_messages):
"""
:meta private:
"""
await self._process_updates(self.edited_business_message_handlers, new_edited_business_messages, 'edited_business_message')
async def process_new_deleted_business_messages(self, new_deleted_business_messages):
"""
:meta private:
"""
await self._process_updates(self.deleted_business_messages_handlers, new_deleted_business_messages, 'deleted_business_messages')
async def process_new_purchased_paid_media(self, new_purchased_paid_media):
"""
:meta private:
"""
await self._process_updates(self.purchased_paid_media_handlers, new_purchased_paid_media, 'purchased_paid_media')
async def _get_middlewares(self, update_type):
"""
:meta private:
"""
if self.middlewares:
middlewares = [middleware for middleware in self.middlewares if update_type in middleware.update_types]
return middlewares
return None
async def __notify_update(self, new_messages):
if len(self.update_listener) == 0:
return
for listener in self.update_listener:
self._loop_create_task(listener(new_messages))
async def _test_message_handler(self, message_handler, message):
"""
Test message handler.
:param message_handler:
:param message:
:return:
"""
for message_filter, filter_value in message_handler['filters'].items():
if filter_value is None:
continue
if not await self._test_filter(message_filter, filter_value, message):
return False
return True
def set_update_listener(self, func: Awaitable):
"""
Update listener is a function that gets any update.
:param func: function that should get update.
:type func: :obj:`Awaitable`
.. code-block:: python3
:caption: Example on asynchronous update listeners.
async def update_listener(new_messages):
for message in new_messages:
print(message.text) # Prints message text
bot.set_update_listener(update_listener)
:return: None
"""
self.update_listener.append(func)
def add_custom_filter(self, custom_filter: Union[asyncio_filters.SimpleCustomFilter, asyncio_filters.AdvancedCustomFilter]):
"""
Create custom filter.
.. code-block:: python3
:caption: Example on checking the text of a message
class TextMatchFilter(AdvancedCustomFilter):
key = 'text'
async def check(self, message, text):
return text == message.text
:param custom_filter: Class with check(message) method.
:type custom_filter: :class:`telebot.asyncio_filters.SimpleCustomFilter` or :class:`telebot.asyncio_filters.AdvancedCustomFilter`
:return: None
"""
self.custom_filters[custom_filter.key] = custom_filter
async def _test_filter(self, message_filter, filter_value, message):
"""
Test filters.
:param message_filter: Filter type passed in handler
:param filter_value: Filter value passed in handler
:param message: Message to test
:return: True if filter conforms
"""
# test_cases = {
# 'content_types': lambda msg: msg.content_type in filter_value,
# 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE),
# 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value,
# 'func': lambda msg: filter_value(msg)
# }
# return test_cases.get(message_filter, lambda msg: False)(message)
if message_filter == 'content_types':
return message.content_type in filter_value
elif message_filter == 'regexp':
return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE)
elif message_filter == 'commands':
return message.content_type == 'text' and util.extract_command(message.text) in filter_value
elif message_filter == 'chat_types':
return message.chat.type in filter_value
elif message_filter == 'func':
if iscoroutinefunction(filter_value):
return await filter_value(message)
return filter_value(message)