forked from eternnoir/pyTelegramBotAPI
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
10525 lines (7931 loc) · 487 KB
/
__init__.py
File metadata and controls
10525 lines (7931 loc) · 487 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 sys
import threading
import time
import traceback
from typing import Any, Callable, List, Optional, Union, Dict
# these imports are used to avoid circular import error
import telebot.util
import telebot.types
import telebot.formatting
# storage
from telebot.storage import StatePickleStorage, StateMemoryStorage, StateStorageBase
# random module to generate random string
import random
import string
import ssl
logger = logging.getLogger('TeleBot')
formatter = logging.Formatter(
'%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
)
import inspect
console_output_handler = logging.StreamHandler(sys.stderr)
console_output_handler.setFormatter(formatter)
logger.addHandler(console_output_handler)
logger.setLevel(logging.ERROR)
from telebot import apihelper, util, types
from telebot.handler_backends import (
HandlerBackend, MemoryHandlerBackend, FileHandlerBackend, BaseMiddleware,
CancelUpdate, SkipHandler, State, ContinueHandling
)
from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter
REPLY_MARKUP_TYPES = Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup,
types.ReplyKeyboardRemove, types.ForceReply]
"""
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
def handle(self, exception):
return False
class TeleBot:
"""
This is the main synchronous class for Bot.
It allows you to add handlers for different kind of updates.
Usage:
.. code-block:: python3
:caption: Creating instance of TeleBot
from telebot import TeleBot
bot = TeleBot('token') # get token from @BotFather
# now you can register other handlers/update listeners,
# and use bot methods.
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, should be obtained from @BotFather
:type token: :obj:`str`
:param parse_mode: Default parse mode, defaults to None
:type parse_mode: :obj:`str`, optional
:param threaded: Threaded or not, defaults to True
:type threaded: :obj:`bool`, optional
:param skip_pending: Skips pending updates, defaults to False
:type skip_pending: :obj:`bool`, optional
:param num_threads: Number of maximum parallel threads, defaults to 2
:type num_threads: :obj:`int`, optional
:param next_step_backend: Next step backend class, defaults to None
:type next_step_backend: :class:`telebot.handler_backends.HandlerBackend`, optional
:param reply_backend: Reply step handler class, defaults to None
:type reply_backend: :class:`telebot.handler_backends.HandlerBackend`, optional
:param exception_handler: Exception handler to handle errors, defaults to None
:type exception_handler: :class:`telebot.ExceptionHandler`, optional
:param last_update_id: Last update's id, defaults to 0
:type last_update_id: :obj:`int`, optional
:param suppress_middleware_excepions: Supress middleware exceptions, defaults to False
:type suppress_middleware_excepions: :obj:`bool`, optional
:param state_storage: Storage for states, defaults to StateMemoryStorage()
:type state_storage: :class:`telebot.storage.StateStorageBase`, optional
:param use_class_middlewares: Use class middlewares, defaults to False
:type use_class_middlewares: :obj:`bool`, 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: 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, threaded: Optional[bool]=True,
skip_pending: Optional[bool]=False, num_threads: Optional[int]=2,
next_step_backend: Optional[HandlerBackend]=None, reply_backend: Optional[HandlerBackend]=None,
exception_handler: Optional[ExceptionHandler]=None, last_update_id: Optional[int]=0,
suppress_middleware_excepions: Optional[bool]=False, state_storage: Optional[StateStorageBase]=StateMemoryStorage(),
use_class_middlewares: Optional[bool]=False,
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
):
# update-related
self.token = token
self.skip_pending = skip_pending # backward compatibility
self.last_update_id = last_update_id
# properties
self.suppress_middleware_excepions = suppress_middleware_excepions
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
self.webhook_listener = None
self._user = None
if validate_token:
util.validate_token(self.token)
self.bot_id: Union[int, None] = util.extract_bot_id(self.token) # subject to change in future, unspecified
# logs-related
if colorful_logs:
try:
# noinspection PyPackageRequirements
import coloredlogs
coloredlogs.install(logger=logger, level=logger.level)
except ImportError:
raise ImportError(
'Install coloredlogs module to use colorful_logs option.'
)
# threading-related
self.__stop_polling = threading.Event()
self.exc_info = None
# states & register_next_step_handler
self.current_states = state_storage
self.next_step_backend = next_step_backend
if not self.next_step_backend:
self.next_step_backend = MemoryHandlerBackend()
self.reply_backend = reply_backend
if not self.reply_backend:
self.reply_backend = MemoryHandlerBackend()
# handlers
self.exception_handler = exception_handler
self.update_listener = []
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.chat_boost_handlers = []
self.removed_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 = []
# middlewares
self.use_class_middlewares = use_class_middlewares
if apihelper.ENABLE_MIDDLEWARE and not use_class_middlewares:
self.typed_middleware_handlers = {
'message': [],
'edited_message': [],
'channel_post': [],
'edited_channel_post': [],
'message_reaction': [],
'message_reaction_count': [],
'inline_query': [],
'chosen_inline_result': [],
'callback_query': [],
'shipping_query': [],
'pre_checkout_query': [],
'poll': [],
'poll_answer': [],
'my_chat_member': [],
'chat_member': [],
'chat_join_request': [],
'chat_boost': [],
'removed_chat_boost': [],
'business_connection': [],
'business_message': [],
'edited_business_message': [],
'deleted_business_messages': [],
}
self.default_middleware_handlers = []
if apihelper.ENABLE_MIDDLEWARE and use_class_middlewares:
self.typed_middleware_handlers = None
logger.error(
'You are using class based middlewares while having ENABLE_MIDDLEWARE set to True. This is not recommended.'
)
self.middlewares = [] if use_class_middlewares else None
# threads
self.threaded = threaded
if self.threaded:
self.worker_pool = util.ThreadPool(self, num_threads=num_threads)
@property
def user(self) -> types.User:
"""
The User object representing this bot.
Equivalent to bot.get_me() but the result is cached so only one API call is needed.
:return: Bot's info.
:rtype: :class:`telebot.types.User`
"""
if not self._user:
self._user = self.get_me()
return self._user
def enable_save_next_step_handlers(self, delay: Optional[int]=120, filename: Optional[str]="./.handler-saves/step.save"):
"""
Enable saving next step handlers (by default saving disabled)
This function explicitly assigns FileHandlerBackend (instead of Saver) just to keep backward
compatibility whose purpose was to enable file saving capability for handlers. And the same
implementation is now available with FileHandlerBackend
:param delay: Delay between changes in handlers and saving, defaults to 120
:type delay: :obj:`int`, optional
:param filename: Filename of save file, defaults to "./.handler-saves/step.save"
:type filename: :obj:`str`, optional
:return: None
"""
self.next_step_backend = FileHandlerBackend(self.next_step_backend.handlers, filename, delay)
def enable_saving_states(self, filename: Optional[str]="./.state-save/states.pkl"):
"""
Enable saving states (by default saving disabled)
.. note::
It is recommended to pass a :class:`~telebot.storage.StatePickleStorage` instance as state_storage
to TeleBot class.
:param filename: Filename of saving file, defaults to "./.state-save/states.pkl"
:type filename: :obj:`str`, optional
"""
self.current_states = StatePickleStorage(file_path=filename)
self.current_states.create_dir()
def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"):
"""
Enable saving reply handlers (by default saving disable)
This function explicitly assigns FileHandlerBackend (instead of Saver) just to keep backward
compatibility whose purpose was to enable file saving capability for handlers. And the same
implementation is now available with FileHandlerBackend
:param delay: Delay between changes in handlers and saving, defaults to 120
:type delay: :obj:`int`, optional
:param filename: Filename of save file, defaults to "./.handler-saves/reply.save"
:type filename: :obj:`str`, optional
"""
self.reply_backend = FileHandlerBackend(self.reply_backend.handlers, filename, delay)
def disable_save_next_step_handlers(self):
"""
Disable saving next step handlers (by default saving disable)
This function is left to keep backward compatibility whose purpose was to disable file saving capability
for handlers. For the same purpose, MemoryHandlerBackend is reassigned as a new next_step_backend backend
instead of FileHandlerBackend.
"""
self.next_step_backend = MemoryHandlerBackend(self.next_step_backend.handlers)
def disable_save_reply_handlers(self):
"""
Disable saving next step handlers (by default saving disable)
This function is left to keep backward compatibility whose purpose was to disable file saving capability
for handlers. For the same purpose, MemoryHandlerBackend is reassigned as a new reply_backend backend
instead of FileHandlerBackend.
"""
self.reply_backend = MemoryHandlerBackend(self.reply_backend.handlers)
def load_next_step_handlers(self, filename="./.handler-saves/step.save", del_file_after_loading=True):
"""
Load next step handlers from save file
This function is left to keep backward compatibility whose purpose was to load handlers from file with the
help of FileHandlerBackend and is only recommended to use if next_step_backend was assigned as
FileHandlerBackend before entering this function
:param filename: Filename of the file where handlers was saved, defaults to "./.handler-saves/step.save"
:type filename: :obj:`str`, optional
:param del_file_after_loading: If True is passed, after the loading file will be deleted, defaults to True
:type del_file_after_loading: :obj:`bool`, optional
"""
self.next_step_backend.load_handlers(filename, del_file_after_loading)
def load_reply_handlers(self, filename="./.handler-saves/reply.save", del_file_after_loading=True):
"""
Load reply handlers from save file
This function is left to keep backward compatibility whose purpose was to load handlers from file with the
help of FileHandlerBackend and is only recommended to use if reply_backend was assigned as
FileHandlerBackend before entering this function
:param filename: Filename of the file where handlers was saved, defaults to "./.handler-saves/reply.save"
:type filename: :obj:`str`, optional
:param del_file_after_loading: If True is passed, after the loading file will be deleted, defaults to True, defaults to True
:type del_file_after_loading: :obj:`bool`, optional
"""
self.reply_backend.load_handlers(filename, del_file_after_loading)
def set_webhook(self, url: Optional[str]=None, certificate: Optional[Union[str, Any]]=None, max_connections: Optional[int]=None,
allowed_updates: Optional[List[str]]=None, ip_address: Optional[str]=None,
drop_pending_updates: Optional[bool] = None, timeout: Optional[int]=None, secret_token: Optional[str]=None) -> bool:
"""
Use this method to specify a URL and receive incoming updates via an outgoing webhook.
Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL,
containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after
a reasonable amount of attempts. Returns True on success.
If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token.
If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.
Telegram Documentation: https://core.telegram.org/bots/api#setwebhook
:param url: HTTPS URL to send updates to. Use an empty string to remove webhook integration, defaults to None
:type url: :obj:`str`, optional
:param certificate: Upload your public key certificate so that the root certificate in use can be checked, defaults to None
:type certificate: :class:`str`, optional
:param max_connections: The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100.
Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput,
defaults to None
:type max_connections: :obj:`int`, optional
:param allowed_updates: A JSON-serialized 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 Update
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 setWebhook, so unwanted updates may be received
for a short period of time. Defaults to None
:type allowed_updates: :obj:`list`, optional
:param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address
resolved through DNS, defaults to None
:type ip_address: :obj:`str`, optional
:param drop_pending_updates: Pass True to drop all pending updates, defaults to None
:type drop_pending_updates: :obj:`bool`, optional
:param timeout: Timeout of a request, defaults to None
:type timeout: :obj:`int`, optional
:param secret_token: A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters.
Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. Defaults to None
:type secret_token: :obj:`str`, optional
:return: True on success.
:rtype: :obj:`bool` if the request was successful.
"""
return apihelper.set_webhook(
self.token, url = url, certificate = certificate, max_connections = max_connections,
allowed_updates = allowed_updates, ip_address = ip_address, drop_pending_updates = drop_pending_updates,
timeout = timeout, secret_token = secret_token)
def run_webhooks(self,
listen: Optional[str]="127.0.0.1",
port: Optional[int]=443,
url_path: Optional[str]=None,
certificate: Optional[str]=None,
certificate_key: Optional[str]=None,
webhook_url: Optional[str]=None,
max_connections: Optional[int]=None,
allowed_updates: Optional[List]=None,
ip_address: Optional[str]=None,
drop_pending_updates: Optional[bool] = None,
timeout: Optional[int]=None,
secret_token: Optional[str]=None,
secret_token_length: Optional[int]=20):
"""
This class sets webhooks and listens to a given url and port.
Requires fastapi, uvicorn, and latest version of starlette.
:param listen: IP address to listen to, defaults to "127.0.0.1"
:type listen: :obj:`str`, optional
:param port: A port which will be used to listen to webhooks., defaults to 443
:type port: :obj:`int`, optional
:param url_path: Path to the webhook. Defaults to /token, defaults to None
:type url_path: :obj:`str`, optional
:param certificate: Path to the certificate file, defaults to None
:type certificate: :obj:`str`, optional
:param certificate_key: Path to the certificate key file, defaults to None
:type certificate_key: :obj:`str`, optional
:param webhook_url: Webhook URL to be set, defaults to None
:type webhook_url: :obj:`str`, optional
:param max_connections: Maximum allowed number of simultaneous HTTPS connections
to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server,
and higher values to increase your bot's throughput., defaults to None
:type max_connections: :obj:`int`, optional
:param allowed_updates: A JSON-serialized 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 Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default).
If not specified, the previous setting will be used. defaults to None
:type allowed_updates: :obj:`list`, optional
:param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS, defaults to None
:type ip_address: :obj:`str`, optional
:param drop_pending_updates: Pass True to drop all pending updates, defaults to None
:type drop_pending_updates: :obj:`bool`, optional
:param timeout: Request connection timeout, defaults to None
:type timeout: :obj:`int`, optional
:param secret_token: Secret token to be used to verify the webhook request, defaults to None
:type secret_token: :obj:`str`, optional
:param secret_token_length: Length of a secret token, defaults to 20
:type secret_token_length: :obj:`int`, optional
:raises ImportError: If necessary libraries were not installed.
"""
# generate secret token if not set
if not secret_token:
secret_token = ''.join(random.choices(string.ascii_uppercase + string.digits, k=secret_token_length))
if not url_path:
url_path = self.token + '/'
if url_path[-1] != '/': url_path += '/'
protocol = "https" if certificate else "http"
if not webhook_url:
webhook_url = "{}://{}:{}/{}".format(protocol, listen, port, url_path)
if certificate and certificate_key:
# noinspection PyTypeChecker
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(certificate, certificate_key)
# open certificate if it exists
cert_file = open(certificate, 'rb') if certificate else None
self.set_webhook(
url=webhook_url,
certificate=cert_file,
max_connections=max_connections,
allowed_updates=allowed_updates,
ip_address=ip_address,
drop_pending_updates=drop_pending_updates,
timeout=timeout,
secret_token=secret_token
)
if cert_file: cert_file.close()
ssl_context = (certificate, certificate_key) if certificate else (None, None)
# webhooks module
try:
from telebot.ext.sync import SyncWebhookListener
except (NameError, ImportError):
raise ImportError("Please install uvicorn and fastapi in order to use `run_webhooks` method.")
self.webhook_listener = SyncWebhookListener(bot=self, secret_token=secret_token, host=listen, port=port, ssl_context=ssl_context, url_path='/'+url_path)
self.webhook_listener.run_app()
def delete_webhook(self, drop_pending_updates: Optional[bool]=None, timeout: Optional[int]=None) -> bool:
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates.
Returns True on success.
Telegram documentation: https://core.telegram.org/bots/api#deletewebhook
:param drop_pending_updates: Pass True to drop all pending updates, defaults to None
:type drop_pending_updates: :obj: `bool`, optional
:param timeout: Request connection timeout, defaults to None
:type timeout: :obj:`int`, optional
:return: Returns True on success.
:rtype: :obj:`bool`
"""
return apihelper.delete_webhook(
self.token, drop_pending_updates=drop_pending_updates, timeout=timeout)
def get_webhook_info(self, timeout: Optional[int]=None) -> types.WebhookInfo:
"""
Use this method to get current webhook status. Requires no parameters.
On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
Telegram documentation: https://core.telegram.org/bots/api#getwebhookinfo
:param timeout: Request connection timeout
:type timeout: :obj:`int`, optional
:return: On success, returns a WebhookInfo object.
:rtype: :class:`telebot.types.WebhookInfo`
"""
return types.WebhookInfo.de_json(
apihelper.get_webhook_info(self.token, timeout=timeout)
)
def remove_webhook(self) -> bool:
"""
Deletes webhooks using set_webhook() function.
:return: True on success.
:rtype: :obj:`bool`
"""
return self.set_webhook() # No params resets webhook
def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None,
timeout: Optional[int]=20, allowed_updates: Optional[List[str]]=None,
long_polling_timeout: int=20) -> 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 long_polling_timeout: Timeout in seconds for long polling.
:type long_polling_timeout: :obj:`int`, optional
:return: An Array of Update objects is returned.
:rtype: :obj:`list` of :class:`telebot.types.Update`
"""
json_updates = apihelper.get_updates(
self.token, offset=offset, limit=limit, timeout=timeout, allowed_updates=allowed_updates,
long_polling_timeout=long_polling_timeout)
return [types.Update.de_json(ju) for ju in json_updates]
def __skip_updates(self):
"""
Get and discard all pending updates before first poll of the bot.
:meta private:
:return:
"""
self.get_updates(offset=-1)
def __retrieve_updates(self, timeout=20, long_polling_timeout=20, allowed_updates=None):
"""
Retrieves any updates from the Telegram API.
Registered listeners and applicable message handlers will be notified when a new message arrives.
:meta private:
:raises ApiException when a call has failed.
"""
if self.skip_pending:
self.__skip_updates()
logger.debug('Skipped all pending messages')
self.skip_pending = False
updates = self.get_updates(offset=(self.last_update_id + 1),
allowed_updates=allowed_updates,
timeout=timeout, long_polling_timeout=long_polling_timeout)
self.process_new_updates(updates)
def process_new_updates(self, updates: List[types.Update]):
"""
Processes new updates. Just pass list of subclasses of Update to this method.
:param updates: List of :class:`telebot.types.Update` objects.
:type updates: :obj:`list` of :class:`telebot.types.Update`
:return None:
"""
upd_count = len(updates)
logger.debug('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_counts = 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
new_chat_join_request = None
new_chat_boosts = None
new_removed_chat_boosts = 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:
if apihelper.ENABLE_MIDDLEWARE and not self.use_class_middlewares:
try:
self.process_middlewares(update)
except Exception as e:
logger.error(str(e))
if not self.suppress_middleware_excepions:
raise
else:
if update.update_id > self.last_update_id: self.last_update_id = update.update_id
continue
if update.update_id > self.last_update_id:
self.last_update_id = update.update_id
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 new_chat_join_request is None: new_chat_join_request = []
new_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_counts is None: new_message_reaction_counts = []
new_message_reaction_counts.append(update.message_reaction_count)
if update.chat_boost:
if new_chat_boosts is None: new_chat_boosts = []
new_chat_boosts.append(update.chat_boost)
if update.removed_chat_boost:
if new_removed_chat_boosts is None: new_removed_chat_boosts = []
new_removed_chat_boosts.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:
self.process_new_messages(new_messages)
if new_edited_messages:
self.process_new_edited_messages(new_edited_messages)
if new_channel_posts:
self.process_new_channel_posts(new_channel_posts)
if new_edited_channel_posts:
self.process_new_edited_channel_posts(new_edited_channel_posts)
if new_inline_queries:
self.process_new_inline_query(new_inline_queries)
if new_chosen_inline_results:
self.process_new_chosen_inline_query(new_chosen_inline_results)
if new_callback_queries:
self.process_new_callback_query(new_callback_queries)
if new_shipping_queries:
self.process_new_shipping_query(new_shipping_queries)
if new_pre_checkout_queries:
self.process_new_pre_checkout_query(new_pre_checkout_queries)
if new_polls:
self.process_new_poll(new_polls)
if new_poll_answers:
self.process_new_poll_answer(new_poll_answers)
if new_my_chat_members:
self.process_new_my_chat_member(new_my_chat_members)
if new_chat_members:
self.process_new_chat_member(new_chat_members)
if new_chat_join_request:
self.process_new_chat_join_request(new_chat_join_request)
if new_message_reactions:
self.process_new_message_reaction(new_message_reactions)
if new_message_reaction_counts:
self.process_new_message_reaction_count(new_message_reaction_counts)
if new_chat_boosts:
self.process_new_chat_boost(new_chat_boosts)
if new_removed_chat_boosts:
self.process_new_removed_chat_boost(new_removed_chat_boosts)
if new_business_connections:
self.process_new_business_connection(new_business_connections)
if new_business_messages:
self.process_new_business_message(new_business_messages)
if new_edited_business_messages:
self.process_new_edited_business_message(new_edited_business_messages)
if new_deleted_business_messages:
self.process_new_deleted_business_messages(new_deleted_business_messages)
if new_purchased_paid_media:
self.process_new_purchased_paid_media(new_purchased_paid_media)
def process_new_messages(self, new_messages):
"""
:meta private:
"""
self._notify_next_handlers(new_messages)
self._notify_reply_handlers(new_messages)
self.__notify_update(new_messages)
self._notify_command_handlers(self.message_handlers, new_messages, 'message')
def process_new_edited_messages(self, new_edited_message):
"""
:meta private:
"""
self._notify_command_handlers(self.edited_message_handlers, new_edited_message, 'edited_message')
def process_new_channel_posts(self, new_channel_post):
"""
:meta private:
"""
self._notify_command_handlers(self.channel_post_handlers, new_channel_post, 'channel_post')
def process_new_edited_channel_posts(self, new_edited_channel_post):
"""
:meta private:
"""
self._notify_command_handlers(self.edited_channel_post_handlers, new_edited_channel_post, 'edited_channel_post')
def process_new_message_reaction(self, new_message_reactions):
"""
:meta private:
"""
self._notify_command_handlers(self.message_reaction_handlers, new_message_reactions, 'message_reaction')
def process_new_message_reaction_count(self, new_message_reaction_counts):
"""
:meta private:
"""
self._notify_command_handlers(self.message_reaction_count_handlers, new_message_reaction_counts, 'message_reaction_count')
def process_new_inline_query(self, new_inline_queries):
"""
:meta private:
"""
self._notify_command_handlers(self.inline_handlers, new_inline_queries, 'inline_query')
def process_new_chosen_inline_query(self, new_chosen_inline_queries):
"""
:meta private:
"""
self._notify_command_handlers(self.chosen_inline_handlers, new_chosen_inline_queries, 'chosen_inline_query')
def process_new_callback_query(self, new_callback_queries):
"""
:meta private:
"""
self._notify_command_handlers(self.callback_query_handlers, new_callback_queries, 'callback_query')
def process_new_shipping_query(self, new_shipping_queries):
"""
:meta private:
"""
self._notify_command_handlers(self.shipping_query_handlers, new_shipping_queries, 'shipping_query')
def process_new_pre_checkout_query(self, new_pre_checkout_queries):
"""
:meta private:
"""
self._notify_command_handlers(self.pre_checkout_query_handlers, new_pre_checkout_queries, 'pre_checkout_query')
def process_new_poll(self, new_polls):
"""
:meta private:
"""
self._notify_command_handlers(self.poll_handlers, new_polls, 'poll')
def process_new_poll_answer(self, new_poll_answers):
"""
:meta private:
"""
self._notify_command_handlers(self.poll_answer_handlers, new_poll_answers, 'poll_answer')
def process_new_my_chat_member(self, new_my_chat_members):
"""
:meta private:
"""
self._notify_command_handlers(self.my_chat_member_handlers, new_my_chat_members, 'my_chat_member')
def process_new_chat_member(self, new_chat_members):
"""
:meta private:
"""
self._notify_command_handlers(self.chat_member_handlers, new_chat_members, 'chat_member')
def process_new_chat_join_request(self, new_chat_join_request):
"""
:meta private:
"""
self._notify_command_handlers(self.chat_join_request_handlers, new_chat_join_request, 'chat_join_request')
def process_new_chat_boost(self, new_chat_boosts):
"""
:meta private:
"""
self._notify_command_handlers(self.chat_boost_handlers, new_chat_boosts, 'chat_boost')
def process_new_removed_chat_boost(self, new_removed_chat_boosts):
"""
:meta private:
"""
self._notify_command_handlers(self.removed_chat_boost_handlers, new_removed_chat_boosts, 'removed_chat_boost')
def process_new_business_connection(self, new_business_connections):
"""
:meta private:
"""
self._notify_command_handlers(self.business_connection_handlers, new_business_connections, 'business_connection')
def process_new_business_message(self, new_business_messages):
"""
:meta private:
"""
self._notify_command_handlers(self.business_message_handlers, new_business_messages, 'business_message')
def process_new_edited_business_message(self, new_edited_business_messages):
"""
:meta private:
"""
self._notify_command_handlers(self.edited_business_message_handlers, new_edited_business_messages, 'edited_business_message')
def process_new_deleted_business_messages(self, new_deleted_business_messages):
"""
:meta private:
"""
self._notify_command_handlers(self.deleted_business_messages_handlers, new_deleted_business_messages, 'deleted_business_messages')
def process_new_purchased_paid_media(self, new_purchased_paid_media):
"""
:meta private:
"""
self._notify_command_handlers(self.purchased_paid_media_handlers, new_purchased_paid_media, 'purchased_paid_media')