forked from eternnoir/pyTelegramBotAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
3354 lines (2972 loc) · 146 KB
/
__init__.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
# -*- 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
# this imports are used to avoid circular import error
import telebot.util
import telebot.types
logger = logging.getLogger('TeleBot')
formatter = logging.Formatter(
'%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
)
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 MemoryHandlerBackend, FileHandlerBackend, StateMemory, StateFile
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 TeleBot Class
Methods:
getMe
logOut
close
sendMessage
forwardMessage
copyMessage
deleteMessage
sendPhoto
sendAudio
sendDocument
sendSticker
sendVideo
sendVenue
sendAnimation
sendVideoNote
sendLocation
sendChatAction
sendDice
sendContact
sendInvoice
sendMediaGroup
getUserProfilePhotos
getUpdates
getFile
sendPoll
stopPoll
sendGame
setGameScore
getGameHighScores
editMessageText
editMessageCaption
editMessageMedia
editMessageReplyMarkup
editMessageLiveLocation
stopMessageLiveLocation
banChatMember
unbanChatMember
restrictChatMember
promoteChatMember
setChatAdministratorCustomTitle
setChatPermissions
createChatInviteLink
editChatInviteLink
revokeChatInviteLink
exportChatInviteLink
setChatStickerSet
deleteChatStickerSet
createNewStickerSet
addStickerToSet
deleteStickerFromSet
setStickerPositionInSet
uploadStickerFile
setStickerSetThumb
getStickerSet
setChatPhoto
deleteChatPhoto
setChatTitle
setChatDescription
pinChatMessage
unpinChatMessage
leaveChat
getChat
getChatAdministrators
getChatMemberCount
getChatMember
answerCallbackQuery
getMyCommands
setMyCommands
deleteMyCommands
answerInlineQuery
answerShippingQuery
answerPreCheckoutQuery
"""
def __init__(
self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2,
next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0,
suppress_middleware_excepions=False
):
"""
:param token: bot API token
:param parse_mode: default parse_mode
:return: Telebot object.
"""
self.token = token
self.parse_mode = parse_mode
self.update_listener = []
self.skip_pending = skip_pending
self.suppress_middleware_excepions = suppress_middleware_excepions
self.__stop_polling = threading.Event()
self.last_update_id = last_update_id
self.exc_info = None
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()
self.exception_handler = exception_handler
self.message_handlers = []
self.edited_message_handlers = []
self.channel_post_handlers = []
self.edited_channel_post_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.custom_filters = {}
self.state_handlers = []
self.current_states = StateMemory()
if apihelper.ENABLE_MIDDLEWARE:
self.typed_middleware_handlers = {
'message': [],
'edited_message': [],
'channel_post': [],
'edited_channel_post': [],
'inline_query': [],
'chosen_inline_result': [],
'callback_query': [],
'shipping_query': [],
'pre_checkout_query': [],
'poll': [],
'poll_answer': [],
'my_chat_member': [],
'chat_member': [],
'chat_join_request': []
}
self.default_middleware_handlers = []
self.threaded = threaded
if self.threaded:
self.worker_pool = util.ThreadPool(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
"""
if not hasattr(self, "_user"):
self._user = types.User.de_json(self.get_me())
return self._user
def enable_save_next_step_handlers(self, delay=120, filename="./.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
Most probably this function should be deprecated in future major releases
:param delay: Delay between changes in handlers and saving
:param filename: Filename of save file
"""
self.next_step_backend = FileHandlerBackend(self.next_step_backend.handlers, filename, delay)
def enable_saving_states(self, filename="./.state-save/states.pkl"):
"""
Enable saving states (by default saving disabled)
:param filename: Filename of saving file
"""
self.current_states = StateFile(filename=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
Most probably this function should be deprecated in future major releases
:param delay: Delay between changes in handlers and saving
:param filename: Filename of save file
"""
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.
Most probably this function should be deprecated in future major releases
"""
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.
Most probably this function should be deprecated in future major releases
"""
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
Most probably this function should be deprecated in future major releases
:param filename: Filename of the file where handlers was saved
:param del_file_after_loading: Is passed True, after loading save file will be deleted
"""
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
Most probably this function should be deprecated in future major releases
:param filename: Filename of the file where handlers was saved
:param del_file_after_loading: Is passed True, after loading save file will be deleted
"""
self.reply_backend.load_handlers(filename, del_file_after_loading)
def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None,
drop_pending_updates = None, timeout=None):
"""
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.
:param url: HTTPS url to send updates to. Use an empty string to remove webhook integration
:param certificate: Upload your public key certificate so that the root certificate in use can be checked.
See our self-signed guide for details.
: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.
: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.
:param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address
resolved through DNS
:param drop_pending_updates: Pass True to drop all pending updates
:param timeout: Integer. Request connection timeout
:return:
"""
return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address,
drop_pending_updates, timeout)
def delete_webhook(self, drop_pending_updates=None, timeout=None):
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates.
:param drop_pending_updates: Pass True to drop all pending updates
:param timeout: Integer. Request connection timeout
:return: bool
"""
return apihelper.delete_webhook(self.token, drop_pending_updates, timeout)
def get_webhook_info(self, timeout: Optional[int]=None):
"""
Use this method to get current webhook status. Requires no parameters.
If the bot is using getUpdates, will return an object with the url field empty.
:param timeout: Integer. Request connection timeout
:return: On success, returns a WebhookInfo object.
"""
result = apihelper.get_webhook_info(self.token, timeout)
return types.WebhookInfo.de_json(result)
def remove_webhook(self):
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.
:param allowed_updates: Array of string. List the types of updates you want your bot to receive.
:param offset: Integer. Identifier of the first update to be returned.
:param limit: Integer. Limits the number of updates to be retrieved.
:param timeout: Integer. Request connection timeout
:param long_polling_timeout. Timeout in seconds for long polling.
:return: array of Updates
"""
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, 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
: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.
: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):
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_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
for update in updates:
if apihelper.ENABLE_MIDDLEWARE:
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 chat_join_request is None: chat_join_request = []
chat_join_request.append(update.chat_join_request)
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 chat_join_request:
self.process_new_chat_join_request(chat_join_request)
def process_new_messages(self, new_messages):
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)
def process_new_edited_messages(self, edited_message):
self._notify_command_handlers(self.edited_message_handlers, edited_message)
def process_new_channel_posts(self, channel_post):
self._notify_command_handlers(self.channel_post_handlers, channel_post)
def process_new_edited_channel_posts(self, edited_channel_post):
self._notify_command_handlers(self.edited_channel_post_handlers, edited_channel_post)
def process_new_inline_query(self, new_inline_querys):
self._notify_command_handlers(self.inline_handlers, new_inline_querys)
def process_new_chosen_inline_query(self, new_chosen_inline_querys):
self._notify_command_handlers(self.chosen_inline_handlers, new_chosen_inline_querys)
def process_new_callback_query(self, new_callback_querys):
self._notify_command_handlers(self.callback_query_handlers, new_callback_querys)
def process_new_shipping_query(self, new_shipping_querys):
self._notify_command_handlers(self.shipping_query_handlers, new_shipping_querys)
def process_new_pre_checkout_query(self, pre_checkout_querys):
self._notify_command_handlers(self.pre_checkout_query_handlers, pre_checkout_querys)
def process_new_poll(self, polls):
self._notify_command_handlers(self.poll_handlers, polls)
def process_new_poll_answer(self, poll_answers):
self._notify_command_handlers(self.poll_answer_handlers, poll_answers)
def process_new_my_chat_member(self, my_chat_members):
self._notify_command_handlers(self.my_chat_member_handlers, my_chat_members)
def process_new_chat_member(self, chat_members):
self._notify_command_handlers(self.chat_member_handlers, chat_members)
def process_new_chat_join_request(self, chat_join_request):
self._notify_command_handlers(self.chat_join_request_handlers, chat_join_request)
def process_middlewares(self, update):
for update_type, middlewares in self.typed_middleware_handlers.items():
if getattr(update, update_type) is not None:
for typed_middleware_handler in middlewares:
try:
typed_middleware_handler(self, getattr(update, update_type))
except Exception as e:
e.args = e.args + (f'Typed middleware handler "{typed_middleware_handler.__qualname__}"',)
raise
if len(self.default_middleware_handlers) > 0:
for default_middleware_handler in self.default_middleware_handlers:
try:
default_middleware_handler(self, update)
except Exception as e:
e.args = e.args + (f'Default middleware handler "{default_middleware_handler.__qualname__}"',)
raise
def __notify_update(self, new_messages):
if len(self.update_listener) == 0:
return
for listener in self.update_listener:
self._exec_task(listener, new_messages)
def infinity_polling(self, timeout: int=20, skip_pending: bool=False, long_polling_timeout: int=20, logger_level=logging.ERROR,
allowed_updates: Optional[List[str]]=None, *args, **kwargs):
"""
Wrap polling with infinite loop and exception handling to avoid bot stops polling.
:param timeout: Request connection timeout
:param long_polling_timeout: Timeout in seconds for long polling (see API docs)
:param skip_pending: skip old updates
:param logger_level: Custom logging level for infinity_polling logging.
Use logger levels from logging as a value. None/NOTSET = no error logging
: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.
"""
if skip_pending:
self.__skip_updates()
while not self.__stop_polling.is_set():
try:
self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_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", str(e))
if logger_level and logger_level >= logging.DEBUG:
logger.error("Exception traceback:\n%s", traceback.format_exc())
time.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")
def polling(self, non_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20,
long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None,
none_stop: Optional[bool]=None):
"""
This function creates a new Thread that calls an internal __retrieve_updates function.
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 get updates.
:param interval: Delay between two update retrivals
:param non_stop: Do not stop polling when an ApiException occurs.
:param timeout: Request connection timeout
:param skip_pending: skip old updates
:param long_polling_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.
:param none_stop: Deprecated, use non_stop. Old typo f***up compatibility
:return:
"""
if none_stop is not None:
non_stop = none_stop
if skip_pending:
self.__skip_updates()
if self.threaded:
self.__threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates)
else:
self.__non_threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates)
def __threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None, allowed_updates=None):
logger.info('Started polling.')
self.__stop_polling.clear()
error_interval = 0.25
polling_thread = util.WorkerThread(name="PollingThread")
or_event = util.OrEvent(
polling_thread.done_event,
polling_thread.exception_event,
self.worker_pool.exception_event
)
while not self.__stop_polling.wait(interval):
or_event.clear()
try:
polling_thread.put(self.__retrieve_updates, timeout, long_polling_timeout, allowed_updates=allowed_updates)
or_event.wait() # wait for polling thread finish, polling thread error or thread pool error
polling_thread.raise_exceptions()
self.worker_pool.raise_exceptions()
error_interval = 0.25
except apihelper.ApiException as e:
if self.exception_handler is not None:
handled = self.exception_handler.handle(e)
else:
handled = False
if not handled:
logger.error(e)
if not non_stop:
self.__stop_polling.set()
logger.info("Exception occurred. Stopping.")
else:
# polling_thread.clear_exceptions()
# self.worker_pool.clear_exceptions()
logger.info("Waiting for {0} seconds until retry".format(error_interval))
time.sleep(error_interval)
if error_interval * 2 < 60:
error_interval *= 2
else:
error_interval = 60
else:
# polling_thread.clear_exceptions()
# self.worker_pool.clear_exceptions()
time.sleep(error_interval)
polling_thread.clear_exceptions() #*
self.worker_pool.clear_exceptions() #*
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received.")
self.__stop_polling.set()
break
except Exception as e:
if self.exception_handler is not None:
handled = self.exception_handler.handle(e)
else:
handled = False
if not handled:
polling_thread.stop()
polling_thread.clear_exceptions() #*
self.worker_pool.clear_exceptions() #*
raise e
else:
polling_thread.clear_exceptions()
self.worker_pool.clear_exceptions()
time.sleep(error_interval)
polling_thread.stop()
polling_thread.clear_exceptions() #*
self.worker_pool.clear_exceptions() #*
logger.info('Stopped polling.')
def __non_threaded_polling(self, non_stop=False, interval=0, timeout=None, long_polling_timeout=None, allowed_updates=None):
logger.info('Started polling.')
self.__stop_polling.clear()
error_interval = 0.25
while not self.__stop_polling.wait(interval):
try:
self.__retrieve_updates(timeout, long_polling_timeout, allowed_updates=allowed_updates)
error_interval = 0.25
except apihelper.ApiException as e:
if self.exception_handler is not None:
handled = self.exception_handler.handle(e)
else:
handled = False
if not handled:
logger.error(e)
if not non_stop:
self.__stop_polling.set()
logger.info("Exception occurred. Stopping.")
else:
logger.info("Waiting for {0} seconds until retry".format(error_interval))
time.sleep(error_interval)
error_interval *= 2
else:
time.sleep(error_interval)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received.")
self.__stop_polling.set()
break
except Exception as e:
if self.exception_handler is not None:
handled = self.exception_handler.handle(e)
else:
handled = False
if not handled:
raise e
else:
time.sleep(error_interval)
logger.info('Stopped polling.')
def _exec_task(self, task, *args, **kwargs):
if self.threaded:
self.worker_pool.put(task, *args, **kwargs)
else:
task(*args, **kwargs)
def stop_polling(self):
self.__stop_polling.set()
def stop_bot(self):
self.stop_polling()
if self.threaded and self.worker_pool:
self.worker_pool.close()
def set_update_listener(self, listener):
self.update_listener.append(listener)
def get_me(self) -> types.User:
"""
Returns basic information about the bot in form of a User object.
"""
result = apihelper.get_me(self.token)
return types.User.de_json(result)
def get_file(self, file_id: str) -> types.File:
"""
Use this method to get basic info about a file and prepare it for downloading.
For the moment, bots can download files of up to 20MB in size.
On success, a File object is returned.
It is guaranteed that the link will be valid for at least 1 hour.
When the link expires, a new one can be requested by calling get_file again.
"""
return types.File.de_json(apihelper.get_file(self.token, file_id))
def get_file_url(self, file_id: str) -> str:
return apihelper.get_file_url(self.token, file_id)
def download_file(self, file_path: str) -> bytes:
return apihelper.download_file(self.token, file_path)
def log_out(self) -> bool:
"""
Use this method to log out from the cloud Bot API server before launching the bot locally.
You MUST log out the bot before running it locally, otherwise there is no guarantee
that the bot will receive updates.
After a successful call, you can immediately log in on a local server,
but will not be able to log in back to the cloud Bot API server for 10 minutes.
Returns True on success.
"""
return apihelper.log_out(self.token)
def close(self) -> bool:
"""
Use this method to close the bot instance before moving it from one local server to another.
You need to delete the webhook before calling this method to ensure that the bot isn't launched again
after server restart.
The method will return error 429 in the first 10 minutes after the bot is launched.
Returns True on success.
"""
return apihelper.close(self.token)
def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None,
limit: Optional[int]=None) -> types.UserProfilePhotos:
"""
Retrieves the user profile photos of the person with 'user_id'
See https://core.telegram.org/bots/api#getuserprofilephotos
:param user_id:
:param offset:
:param limit:
:return: API reply.
"""
result = apihelper.get_user_profile_photos(self.token, user_id, offset, limit)
return types.UserProfilePhotos.de_json(result)
def get_chat(self, chat_id: Union[int, str]) -> types.Chat:
"""
Use this method to get up to date information about the chat (current name of the user for one-on-one
conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
:param chat_id:
:return:
"""
result = apihelper.get_chat(self.token, chat_id)
return types.Chat.de_json(result)
def leave_chat(self, chat_id: Union[int, str]) -> bool:
"""
Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
:param chat_id:
:return:
"""
result = apihelper.leave_chat(self.token, chat_id)
return result
def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]:
"""
Use this method to get a list of administrators in a chat.
On success, returns an Array of ChatMember objects that contains
information about all chat administrators except other bots.
:param chat_id: Unique identifier for the target chat or username
of the target supergroup or channel (in the format @channelusername)
:return:
"""
result = apihelper.get_chat_administrators(self.token, chat_id)
return [types.ChatMember.de_json(r) for r in result]
def get_chat_members_count(self, chat_id: Union[int, str]) -> int:
"""
This function is deprecated. Use `get_chat_member_count` instead
"""
logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.')
result = apihelper.get_chat_member_count(self.token, chat_id)
return result
def get_chat_member_count(self, chat_id: Union[int, str]) -> int:
"""
Use this method to get the number of members in a chat. Returns Int on success.
:param chat_id:
:return:
"""
result = apihelper.get_chat_member_count(self.token, chat_id)
return result
def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet:
"""
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests to check
if the bot can use this method. Returns True on success.
:param chat_id: Unique identifier for the target chat or username of the target supergroup
(in the format @supergroupusername)
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:return:
"""
result = apihelper.set_chat_sticker_set(self.token, chat_id, sticker_set_name)
return result
def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool:
"""
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat
for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set
optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
:param chat_id: Unique identifier for the target chat or username of the target supergroup
(in the format @supergroupusername)
:return:
"""
result = apihelper.delete_chat_sticker_set(self.token, chat_id)
return result
def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember:
"""
Use this method to get information about a member of a chat. Returns a ChatMember object on success.
:param chat_id:
:param user_id:
:return:
"""
result = apihelper.get_chat_member(self.token, chat_id, user_id)
return types.ChatMember.de_json(result)
def send_message(
self, chat_id: Union[int, str], text: str,
disable_web_page_preview: Optional[bool]=None,
reply_to_message_id: Optional[int]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
parse_mode: Optional[str]=None,
disable_notification: Optional[bool]=None,
timeout: Optional[int]=None,
entities: Optional[List[types.MessageEntity]]=None,
allow_sending_without_reply: Optional[bool]=None) -> types.Message:
"""
Use this method to send text messages.
Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error.
If you must send more than 4000 characters,
use the `split_string` or `smart_split` function in util.py.
:param chat_id:
:param text:
:param disable_web_page_preview:
:param reply_to_message_id:
:param reply_markup:
:param parse_mode:
:param disable_notification: Boolean, Optional. Sends the message silently.
:param timeout:
:param entities:
:param allow_sending_without_reply:
:return: API reply.
"""
parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
return types.Message.de_json(
apihelper.send_message(
self.token, chat_id, text, disable_web_page_preview, reply_to_message_id,
reply_markup, parse_mode, disable_notification, timeout,
entities, allow_sending_without_reply))
def forward_message(
self, chat_id: Union[int, str], from_chat_id: Union[int, str],
message_id: int, disable_notification: Optional[bool]=None,
timeout: Optional[int]=None) -> types.Message:
"""
Use this method to forward messages of any kind.
:param disable_notification:
:param chat_id: which chat to forward
:param from_chat_id: which chat message from
:param message_id: message id
:param timeout:
:return: API reply.
"""
return types.Message.de_json(
apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout))
def copy_message(
self, chat_id: Union[int, str],
from_chat_id: Union[int, str],
message_id: int,
caption: Optional[str]=None,
parse_mode: Optional[str]=None,
caption_entities: Optional[List[types.MessageEntity]]=None,
disable_notification: Optional[bool]=None,
reply_to_message_id: Optional[int]=None,
allow_sending_without_reply: Optional[bool]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,