forked from eternnoir/pyTelegramBotAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.py
2885 lines (2481 loc) · 114 KB
/
types.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 -*-
import logging
from typing import Dict, List, Optional, Union
from abc import ABC
try:
import ujson as json
except ImportError:
import json
from telebot import util
DISABLE_KEYLEN_ERROR = False
logger = logging.getLogger('TeleBot')
class JsonSerializable(object):
"""
Subclasses of this class are guaranteed to be able to be converted to JSON format.
All subclasses of this class must override to_json.
"""
def to_json(self):
"""
Returns a JSON string representation of this class.
This function must be overridden by subclasses.
:return: a JSON formatted string.
"""
raise NotImplementedError
class Dictionaryable(object):
"""
Subclasses of this class are guaranteed to be able to be converted to dictionary.
All subclasses of this class must override to_dict.
"""
def to_dict(self):
"""
Returns a DICT with class field values
This function must be overridden by subclasses.
:return: a DICT
"""
raise NotImplementedError
class JsonDeserializable(object):
"""
Subclasses of this class are guaranteed to be able to be created from a json-style dict or json formatted string.
All subclasses of this class must override de_json.
"""
@classmethod
def de_json(cls, json_string):
"""
Returns an instance of this class from the given json dict or string.
This function must be overridden by subclasses.
:return: an instance of this class created from the given json dict or string.
"""
raise NotImplementedError
@staticmethod
def check_json(json_type, dict_copy = True):
"""
Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is.
If it is not, it is converted to a dict by means of json.loads(json_type)
:param json_type: input json or parsed dict
:param dict_copy: if dict is passed and it is changed outside - should be True!
:return: Dictionary parsed from json or original dict
"""
if util.is_dict(json_type):
return json_type.copy() if dict_copy else json_type
elif util.is_string(json_type):
return json.loads(json_type)
else:
raise ValueError("json_type should be a json dict or string.")
def __str__(self):
d = {
x: y.__dict__ if hasattr(y, '__dict__') else y
for x, y in self.__dict__.items()
}
return str(d)
class Update(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
update_id = obj['update_id']
message = Message.de_json(obj.get('message'))
edited_message = Message.de_json(obj.get('edited_message'))
channel_post = Message.de_json(obj.get('channel_post'))
edited_channel_post = Message.de_json(obj.get('edited_channel_post'))
inline_query = InlineQuery.de_json(obj.get('inline_query'))
chosen_inline_result = ChosenInlineResult.de_json(obj.get('chosen_inline_result'))
callback_query = CallbackQuery.de_json(obj.get('callback_query'))
shipping_query = ShippingQuery.de_json(obj.get('shipping_query'))
pre_checkout_query = PreCheckoutQuery.de_json(obj.get('pre_checkout_query'))
poll = Poll.de_json(obj.get('poll'))
poll_answer = PollAnswer.de_json(obj.get('poll_answer'))
my_chat_member = ChatMemberUpdated.de_json(obj.get('my_chat_member'))
chat_member = ChatMemberUpdated.de_json(obj.get('chat_member'))
chat_join_request = ChatJoinRequest.de_json(obj.get('chat_join_request'))
return cls(update_id, 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)
def __init__(self, update_id, 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.update_id = update_id
self.message = message
self.edited_message = edited_message
self.channel_post = channel_post
self.edited_channel_post = edited_channel_post
self.inline_query = inline_query
self.chosen_inline_result = chosen_inline_result
self.callback_query = callback_query
self.shipping_query = shipping_query
self.pre_checkout_query = pre_checkout_query
self.poll = poll
self.poll_answer = poll_answer
self.my_chat_member = my_chat_member
self.chat_member = chat_member
self.chat_join_request = chat_join_request
class ChatMemberUpdated(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
obj['chat'] = Chat.de_json(obj['chat'])
obj['from_user'] = User.de_json(obj.pop('from'))
obj['old_chat_member'] = ChatMember.de_json(obj['old_chat_member'])
obj['new_chat_member'] = ChatMember.de_json(obj['new_chat_member'])
obj['invite_link'] = ChatInviteLink.de_json(obj.get('invite_link'))
return cls(**obj)
def __init__(self, chat, from_user, date, old_chat_member, new_chat_member, invite_link=None, **kwargs):
self.chat: Chat = chat
self.from_user: User = from_user
self.date: int = date
self.old_chat_member: ChatMember = old_chat_member
self.new_chat_member: ChatMember = new_chat_member
self.invite_link: Optional[ChatInviteLink] = invite_link
@property
def difference(self) -> Dict[str, List]:
"""
Get the difference between `old_chat_member` and `new_chat_member`
as a dict in the following format {'parameter': [old_value, new_value]}
E.g {'status': ['member', 'kicked'], 'until_date': [None, 1625055092]}
"""
old: Dict = self.old_chat_member.__dict__
new: Dict = self.new_chat_member.__dict__
dif = {}
for key in new:
if key == 'user': continue
if new[key] != old[key]:
dif[key] = [old[key], new[key]]
return dif
class ChatJoinRequest(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
obj['chat'] = Chat.de_json(obj['chat'])
obj['from_user'] = User.de_json(obj['from'])
obj['invite_link'] = ChatInviteLink.de_json(obj.get('invite_link'))
return cls(**obj)
def __init__(self, chat, from_user, date, bio=None, invite_link=None, **kwargs):
self.chat = chat
self.from_user = from_user
self.date = date
self.bio = bio
self.invite_link = invite_link
class WebhookInfo(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, url, has_custom_certificate, pending_update_count, ip_address=None,
last_error_date=None, last_error_message=None, max_connections=None,
allowed_updates=None, **kwargs):
self.url = url
self.has_custom_certificate = has_custom_certificate
self.pending_update_count = pending_update_count
self.ip_address = ip_address
self.last_error_date = last_error_date
self.last_error_message = last_error_message
self.max_connections = max_connections
self.allowed_updates = allowed_updates
class User(JsonDeserializable, Dictionaryable, JsonSerializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None,
can_join_groups=None, can_read_all_group_messages=None, supports_inline_queries=None, **kwargs):
self.id: int = id
self.is_bot: bool = is_bot
self.first_name: str = first_name
self.username: str = username
self.last_name: str = last_name
self.language_code: str = language_code
self.can_join_groups: bool = can_join_groups
self.can_read_all_group_messages: bool = can_read_all_group_messages
self.supports_inline_queries: bool = supports_inline_queries
@property
def full_name(self):
full_name = self.first_name
if self.last_name:
full_name += ' {0}'.format(self.last_name)
return full_name
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
return {'id': self.id,
'is_bot': self.is_bot,
'first_name': self.first_name,
'last_name': self.last_name,
'username': self.username,
'language_code': self.language_code,
'can_join_groups': self.can_join_groups,
'can_read_all_group_messages': self.can_read_all_group_messages,
'supports_inline_queries': self.supports_inline_queries}
class GroupChat(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, id, title, **kwargs):
self.id: int = id
self.title: str = title
class Chat(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'photo' in obj:
obj['photo'] = ChatPhoto.de_json(obj['photo'])
if 'pinned_message' in obj:
obj['pinned_message'] = Message.de_json(obj['pinned_message'])
if 'permissions' in obj:
obj['permissions'] = ChatPermissions.de_json(obj['permissions'])
if 'location' in obj:
obj['location'] = ChatLocation.de_json(obj['location'])
return cls(**obj)
def __init__(self, id, type, title=None, username=None, first_name=None,
last_name=None, photo=None, bio=None, has_private_forwards=None,
description=None, invite_link=None, pinned_message=None,
permissions=None, slow_mode_delay=None,
message_auto_delete_time=None, has_protected_content=None, sticker_set_name=None,
can_set_sticker_set=None, linked_chat_id=None, location=None, **kwargs):
self.id: int = id
self.type: str = type
self.title: str = title
self.username: str = username
self.first_name: str = first_name
self.last_name: str = last_name
self.photo: ChatPhoto = photo
self.bio: str = bio
self.has_private_forwards: bool = has_private_forwards
self.description: str = description
self.invite_link: str = invite_link
self.pinned_message: Message = pinned_message
self.permissions: ChatPermissions = permissions
self.slow_mode_delay: int = slow_mode_delay
self.message_auto_delete_time: int = message_auto_delete_time
self.has_protected_content: bool = has_protected_content
self.sticker_set_name: str = sticker_set_name
self.can_set_sticker_set: bool = can_set_sticker_set
self.linked_chat_id: int = linked_chat_id
self.location: ChatLocation = location
class MessageID(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, message_id, **kwargs):
self.message_id = message_id
class Message(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
message_id = obj['message_id']
from_user = User.de_json(obj.get('from'))
date = obj['date']
chat = Chat.de_json(obj['chat'])
content_type = None
opts = {}
if 'sender_chat' in obj:
opts['sender_chat'] = Chat.de_json(obj['sender_chat'])
if 'forward_from' in obj:
opts['forward_from'] = User.de_json(obj['forward_from'])
if 'forward_from_chat' in obj:
opts['forward_from_chat'] = Chat.de_json(obj['forward_from_chat'])
if 'forward_from_message_id' in obj:
opts['forward_from_message_id'] = obj.get('forward_from_message_id')
if 'forward_signature' in obj:
opts['forward_signature'] = obj.get('forward_signature')
if 'forward_sender_name' in obj:
opts['forward_sender_name'] = obj.get('forward_sender_name')
if 'forward_date' in obj:
opts['forward_date'] = obj.get('forward_date')
if 'is_automatic_forward' in obj:
opts['is_automatic_forward'] = obj.get('is_automatic_forward')
if 'reply_to_message' in obj:
opts['reply_to_message'] = Message.de_json(obj['reply_to_message'])
if 'via_bot' in obj:
opts['via_bot'] = User.de_json(obj['via_bot'])
if 'edit_date' in obj:
opts['edit_date'] = obj.get('edit_date')
if 'has_protected_content' in obj:
opts['has_protected_content'] = obj.get('has_protected_content')
if 'media_group_id' in obj:
opts['media_group_id'] = obj.get('media_group_id')
if 'author_signature' in obj:
opts['author_signature'] = obj.get('author_signature')
if 'text' in obj:
opts['text'] = obj['text']
content_type = 'text'
if 'entities' in obj:
opts['entities'] = Message.parse_entities(obj['entities'])
if 'caption_entities' in obj:
opts['caption_entities'] = Message.parse_entities(obj['caption_entities'])
if 'audio' in obj:
opts['audio'] = Audio.de_json(obj['audio'])
content_type = 'audio'
if 'document' in obj:
opts['document'] = Document.de_json(obj['document'])
content_type = 'document'
if 'animation' in obj:
# Document content type accompanies "animation",
# so "animation" should be checked below "document" to override it
opts['animation'] = Animation.de_json(obj['animation'])
content_type = 'animation'
if 'game' in obj:
opts['game'] = Game.de_json(obj['game'])
content_type = 'game'
if 'photo' in obj:
opts['photo'] = Message.parse_photo(obj['photo'])
content_type = 'photo'
if 'sticker' in obj:
opts['sticker'] = Sticker.de_json(obj['sticker'])
content_type = 'sticker'
if 'video' in obj:
opts['video'] = Video.de_json(obj['video'])
content_type = 'video'
if 'video_note' in obj:
opts['video_note'] = VideoNote.de_json(obj['video_note'])
content_type = 'video_note'
if 'voice' in obj:
opts['voice'] = Audio.de_json(obj['voice'])
content_type = 'voice'
if 'caption' in obj:
opts['caption'] = obj['caption']
if 'contact' in obj:
opts['contact'] = Contact.de_json(json.dumps(obj['contact']))
content_type = 'contact'
if 'location' in obj:
opts['location'] = Location.de_json(obj['location'])
content_type = 'location'
if 'venue' in obj:
opts['venue'] = Venue.de_json(obj['venue'])
content_type = 'venue'
if 'dice' in obj:
opts['dice'] = Dice.de_json(obj['dice'])
content_type = 'dice'
if 'new_chat_members' in obj:
new_chat_members = []
for member in obj['new_chat_members']:
new_chat_members.append(User.de_json(member))
opts['new_chat_members'] = new_chat_members
content_type = 'new_chat_members'
if 'left_chat_member' in obj:
opts['left_chat_member'] = User.de_json(obj['left_chat_member'])
content_type = 'left_chat_member'
if 'new_chat_title' in obj:
opts['new_chat_title'] = obj['new_chat_title']
content_type = 'new_chat_title'
if 'new_chat_photo' in obj:
opts['new_chat_photo'] = Message.parse_photo(obj['new_chat_photo'])
content_type = 'new_chat_photo'
if 'delete_chat_photo' in obj:
opts['delete_chat_photo'] = obj['delete_chat_photo']
content_type = 'delete_chat_photo'
if 'group_chat_created' in obj:
opts['group_chat_created'] = obj['group_chat_created']
content_type = 'group_chat_created'
if 'supergroup_chat_created' in obj:
opts['supergroup_chat_created'] = obj['supergroup_chat_created']
content_type = 'supergroup_chat_created'
if 'channel_chat_created' in obj:
opts['channel_chat_created'] = obj['channel_chat_created']
content_type = 'channel_chat_created'
if 'migrate_to_chat_id' in obj:
opts['migrate_to_chat_id'] = obj['migrate_to_chat_id']
content_type = 'migrate_to_chat_id'
if 'migrate_from_chat_id' in obj:
opts['migrate_from_chat_id'] = obj['migrate_from_chat_id']
content_type = 'migrate_from_chat_id'
if 'pinned_message' in obj:
opts['pinned_message'] = Message.de_json(obj['pinned_message'])
content_type = 'pinned_message'
if 'invoice' in obj:
opts['invoice'] = Invoice.de_json(obj['invoice'])
content_type = 'invoice'
if 'successful_payment' in obj:
opts['successful_payment'] = SuccessfulPayment.de_json(obj['successful_payment'])
content_type = 'successful_payment'
if 'connected_website' in obj:
opts['connected_website'] = obj['connected_website']
content_type = 'connected_website'
if 'poll' in obj:
opts['poll'] = Poll.de_json(obj['poll'])
content_type = 'poll'
if 'passport_data' in obj:
opts['passport_data'] = obj['passport_data']
content_type = 'passport_data'
if 'proximity_alert_triggered' in obj:
opts['proximity_alert_triggered'] = ProximityAlertTriggered.de_json(obj[
'proximity_alert_triggered'])
content_type = 'proximity_alert_triggered'
if 'voice_chat_scheduled' in obj:
opts['voice_chat_scheduled'] = VoiceChatScheduled.de_json(obj['voice_chat_scheduled'])
content_type = 'voice_chat_scheduled'
if 'voice_chat_started' in obj:
opts['voice_chat_started'] = VoiceChatStarted.de_json(obj['voice_chat_started'])
content_type = 'voice_chat_started'
if 'voice_chat_ended' in obj:
opts['voice_chat_ended'] = VoiceChatEnded.de_json(obj['voice_chat_ended'])
content_type = 'voice_chat_ended'
if 'voice_chat_participants_invited' in obj:
opts['voice_chat_participants_invited'] = VoiceChatParticipantsInvited.de_json(obj['voice_chat_participants_invited'])
content_type = 'voice_chat_participants_invited'
if 'message_auto_delete_timer_changed' in obj:
opts['message_auto_delete_timer_changed'] = MessageAutoDeleteTimerChanged.de_json(obj['message_auto_delete_timer_changed'])
content_type = 'message_auto_delete_timer_changed'
if 'reply_markup' in obj:
opts['reply_markup'] = InlineKeyboardMarkup.de_json(obj['reply_markup'])
return cls(message_id, from_user, date, chat, content_type, opts, json_string)
@classmethod
def parse_chat(cls, chat):
if 'first_name' not in chat:
return GroupChat.de_json(chat)
else:
return User.de_json(chat)
@classmethod
def parse_photo(cls, photo_size_array):
ret = []
for ps in photo_size_array:
ret.append(PhotoSize.de_json(ps))
return ret
@classmethod
def parse_entities(cls, message_entity_array):
ret = []
for me in message_entity_array:
ret.append(MessageEntity.de_json(me))
return ret
def __init__(self, message_id, from_user, date, chat, content_type, options, json_string):
self.content_type: str = content_type
self.id: int = message_id # Lets fix the telegram usability ####up with ID in Message :)
self.message_id: int = message_id
self.from_user: User = from_user
self.date: int = date
self.chat: Chat = chat
self.sender_chat: Optional[Chat] = None
self.forward_from: Optional[User] = None
self.forward_from_chat: Optional[Chat] = None
self.forward_from_message_id: Optional[int] = None
self.forward_signature: Optional[str] = None
self.forward_sender_name: Optional[str] = None
self.forward_date: Optional[int] = None
self.is_automatic_forward: Optional[bool] = None
self.reply_to_message: Optional[Message] = None
self.via_bot: Optional[User] = None
self.edit_date: Optional[int] = None
self.has_protected_content: Optional[bool] = None
self.media_group_id: Optional[str] = None
self.author_signature: Optional[str] = None
self.text: Optional[str] = None
self.entities: Optional[List[MessageEntity]] = None
self.caption_entities: Optional[List[MessageEntity]] = None
self.audio: Optional[Audio] = None
self.document: Optional[Document] = None
self.photo: Optional[List[PhotoSize]] = None
self.sticker: Optional[Sticker] = None
self.video: Optional[Video] = None
self.video_note: Optional[VideoNote] = None
self.voice: Optional[Voice] = None
self.caption: Optional[str] = None
self.contact: Optional[Contact] = None
self.location: Optional[Location] = None
self.venue: Optional[Venue] = None
self.animation: Optional[Animation] = None
self.dice: Optional[Dice] = None
self.new_chat_member: Optional[User] = None # Deprecated since Bot API 3.0. Not processed anymore
self.new_chat_members: Optional[List[User]] = None
self.left_chat_member: Optional[User] = None
self.new_chat_title: Optional[str] = None
self.new_chat_photo: Optional[List[PhotoSize]] = None
self.delete_chat_photo: Optional[bool] = None
self.group_chat_created: Optional[bool] = None
self.supergroup_chat_created: Optional[bool] = None
self.channel_chat_created: Optional[bool] = None
self.migrate_to_chat_id: Optional[int] = None
self.migrate_from_chat_id: Optional[int] = None
self.pinned_message: Optional[Message] = None
self.invoice: Optional[Invoice] = None
self.successful_payment: Optional[SuccessfulPayment] = None
self.connected_website: Optional[str] = None
self.reply_markup: Optional[InlineKeyboardMarkup] = None
for key in options:
setattr(self, key, options[key])
self.json = json_string
def __html_text(self, text, entities):
"""
Author: @sviat9440
Updaters: @badiboy
Message: "*Test* parse _formatting_, [url](https://example.com), [text_mention](tg://user?id=123456) and mention @username"
Example:
message.html_text
>> "<b>Test</b> parse <i>formatting</i>, <a href=\"https://example.com\">url</a>, <a href=\"tg://user?id=123456\">text_mention</a> and mention @username"
Custom subs:
You can customize the substitutes. By default, there is no substitute for the entities: hashtag, bot_command, email. You can add or modify substitute an existing entity.
Example:
message.custom_subs = {"bold": "<strong class=\"example\">{text}</strong>", "italic": "<i class=\"example\">{text}</i>", "mention": "<a href={url}>{text}</a>"}
message.html_text
>> "<strong class=\"example\">Test</strong> parse <i class=\"example\">formatting</i>, <a href=\"https://example.com\">url</a> and <a href=\"tg://user?id=123456\">text_mention</a> and mention <a href=\"https://t.me/username\">@username</a>"
"""
if not entities:
return text
_subs = {
"bold": "<b>{text}</b>",
"italic": "<i>{text}</i>",
"pre": "<pre>{text}</pre>",
"code": "<code>{text}</code>",
# "url": "<a href=\"{url}\">{text}</a>", # @badiboy plain URLs have no text and do not need tags
"text_link": "<a href=\"{url}\">{text}</a>",
"strikethrough": "<s>{text}</s>",
"underline": "<u>{text}</u>"
}
if hasattr(self, "custom_subs"):
for key, value in self.custom_subs.items():
_subs[key] = value
utf16_text = text.encode("utf-16-le")
html_text = ""
def func(upd_text, subst_type=None, url=None, user=None):
upd_text = upd_text.decode("utf-16-le")
if subst_type == "text_mention":
subst_type = "text_link"
url = "tg://user?id={0}".format(user.id)
elif subst_type == "mention":
url = "https://t.me/{0}".format(upd_text[1:])
upd_text = upd_text.replace("&", "&").replace("<", "<").replace(">", ">")
if not subst_type or not _subs.get(subst_type):
return upd_text
subs = _subs.get(subst_type)
return subs.format(text=upd_text, url=url)
offset = 0
for entity in entities:
if entity.offset > offset:
html_text += func(utf16_text[offset * 2 : entity.offset * 2])
offset = entity.offset
html_text += func(utf16_text[offset * 2 : (offset + entity.length) * 2], entity.type, entity.url, entity.user)
offset += entity.length
elif entity.offset == offset:
html_text += func(utf16_text[offset * 2 : (offset + entity.length) * 2], entity.type, entity.url, entity.user)
offset += entity.length
else:
# TODO: process nested entities from Bot API 4.5
# Now ignoring them
pass
if offset * 2 < len(utf16_text):
html_text += func(utf16_text[offset * 2:])
return html_text
@property
def html_text(self):
return self.__html_text(self.text, self.entities)
@property
def html_caption(self):
return self.__html_text(self.caption, self.caption_entities)
class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable):
@staticmethod
def to_list_of_dicts(entity_list) -> Union[List[Dict], None]:
res = []
for e in entity_list:
res.append(MessageEntity.to_dict(e))
return res or None
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'user' in obj:
obj['user'] = User.de_json(obj['user'])
return cls(**obj)
def __init__(self, type, offset, length, url=None, user=None, language=None, **kwargs):
self.type: str = type
self.offset: int = offset
self.length: int = length
self.url: str = url
self.user: User = user
self.language: str = language
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
return {"type": self.type,
"offset": self.offset,
"length": self.length,
"url": self.url,
"user": self.user,
"language": self.language}
class Dice(JsonSerializable, Dictionaryable, JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, value, emoji, **kwargs):
self.value: int = value
self.emoji: str = emoji
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
return {'value': self.value,
'emoji': self.emoji}
class PhotoSize(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, file_id, file_unique_id, width, height, file_size=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.width: int = width
self.height: int = height
self.file_size: int = file_size
class Audio(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'thumb' in obj and 'file_id' in obj['thumb']:
obj['thumb'] = PhotoSize.de_json(obj['thumb'])
else:
obj['thumb'] = None
return cls(**obj)
def __init__(self, file_id, file_unique_id, duration, performer=None, title=None, file_name=None, mime_type=None,
file_size=None, thumb=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.duration: int = duration
self.performer: str = performer
self.title: str = title
self.file_name: str = file_name
self.mime_type: str = mime_type
self.file_size: int = file_size
self.thumb: PhotoSize = thumb
class Voice(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.duration: int = duration
self.mime_type: str = mime_type
self.file_size: int = file_size
class Document(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'thumb' in obj and 'file_id' in obj['thumb']:
obj['thumb'] = PhotoSize.de_json(obj['thumb'])
else:
obj['thumb'] = None
return cls(**obj)
def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.thumb: PhotoSize = thumb
self.file_name: str = file_name
self.mime_type: str = mime_type
self.file_size: int = file_size
class Video(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'thumb' in obj and 'file_id' in obj['thumb']:
obj['thumb'] = PhotoSize.de_json(obj['thumb'])
return cls(**obj)
def __init__(self, file_id, file_unique_id, width, height, duration, thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.width: int = width
self.height: int = height
self.duration: int = duration
self.thumb: PhotoSize = thumb
self.file_name: str = file_name
self.mime_type: str = mime_type
self.file_size: int = file_size
class VideoNote(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'thumb' in obj and 'file_id' in obj['thumb']:
obj['thumb'] = PhotoSize.de_json(obj['thumb'])
return cls(**obj)
def __init__(self, file_id, file_unique_id, length, duration, thumb=None, file_size=None, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.length: int = length
self.duration: int = duration
self.thumb: PhotoSize = thumb
self.file_size: int = file_size
class Contact(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None, **kwargs):
self.phone_number: str = phone_number
self.first_name: str = first_name
self.last_name: str = last_name
self.user_id: int = user_id
self.vcard: str = vcard
class Location(JsonDeserializable, JsonSerializable, Dictionaryable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, longitude, latitude, horizontal_accuracy=None,
live_period=None, heading=None, proximity_alert_radius=None, **kwargs):
self.longitude: float = longitude
self.latitude: float = latitude
self.horizontal_accuracy: float = horizontal_accuracy
self.live_period: int = live_period
self.heading: int = heading
self.proximity_alert_radius: int = proximity_alert_radius
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
return {
"longitude": self.longitude,
"latitude": self.latitude,
"horizontal_accuracy": self.horizontal_accuracy,
"live_period": self.live_period,
"heading": self.heading,
"proximity_alert_radius": self.proximity_alert_radius,
}
class Venue(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
obj['location'] = Location.de_json(obj['location'])
return cls(**obj)
def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None,
google_place_id=None, google_place_type=None, **kwargs):
self.location: Location = location
self.title: str = title
self.address: str = address
self.foursquare_id: str = foursquare_id
self.foursquare_type: str = foursquare_type
self.google_place_id: str = google_place_id
self.google_place_type: str = google_place_type
class UserProfilePhotos(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string)
if 'photos' in obj:
photos = [[PhotoSize.de_json(y) for y in x] for x in obj['photos']]
obj['photos'] = photos
return cls(**obj)
def __init__(self, total_count, photos=None, **kwargs):
self.total_count: int = total_count
self.photos: List[PhotoSize] = photos
class File(JsonDeserializable):
@classmethod
def de_json(cls, json_string):
if json_string is None: return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, file_id, file_unique_id, file_size, file_path, **kwargs):
self.file_id: str = file_id
self.file_unique_id: str = file_unique_id
self.file_size: int = file_size
self.file_path: str = file_path
class ForceReply(JsonSerializable):
def __init__(self, selective: Optional[bool]=None, input_field_placeholder: Optional[str]=None):
self.selective: bool = selective
self.input_field_placeholder: str = input_field_placeholder
def to_json(self):
json_dict = {'force_reply': True}
if self.selective is not None:
json_dict['selective'] = self.selective
if self.input_field_placeholder:
json_dict['input_field_placeholder'] = self.input_field_placeholder
return json.dumps(json_dict)
class ReplyKeyboardRemove(JsonSerializable):
def __init__(self, selective=None):
self.selective: bool = selective
def to_json(self):
json_dict = {'remove_keyboard': True}
if self.selective:
json_dict['selective'] = self.selective
return json.dumps(json_dict)
class ReplyKeyboardMarkup(JsonSerializable):
max_row_keys = 12
def __init__(self, resize_keyboard: Optional[bool]=None, one_time_keyboard: Optional[bool]=None,
selective: Optional[bool]=None, row_width: int=3, input_field_placeholder: Optional[str]=None):
if row_width > self.max_row_keys:
# Todo: Will be replaced with Exception in future releases
if not DISABLE_KEYLEN_ERROR:
logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys)
row_width = self.max_row_keys
self.resize_keyboard: bool = resize_keyboard
self.one_time_keyboard: bool = one_time_keyboard
self.selective: bool = selective
self.row_width: int = row_width
self.input_field_placeholder: str = input_field_placeholder
self.keyboard: List[List[KeyboardButton]] = []
def add(self, *args, row_width=None):
"""
This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the result of this function: {keyboard: [["A", "B"], ["C"]]}
See https://core.telegram.org/bots/api#replykeyboardmarkup
:param args: KeyboardButton to append to the keyboard
:param row_width: width of row
:return: self, to allow function chaining.
"""
if row_width is None:
row_width = self.row_width
if row_width > self.max_row_keys:
# Todo: Will be replaced with Exception in future releases
if not DISABLE_KEYLEN_ERROR:
logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys)
row_width = self.max_row_keys
for row in util.chunks(args, row_width):
button_array = []
for button in row:
if util.is_string(button):
button_array.append({'text': button})
elif util.is_bytes(button):
button_array.append({'text': button.decode('utf-8')})
else:
button_array.append(button.to_dict())
self.keyboard.append(button_array)
return self
def row(self, *args):
"""
Adds a list of KeyboardButton to the keyboard. This function does not consider row_width.
ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}'
See https://core.telegram.org/bots/api#replykeyboardmarkup
:param args: strings
:return: self, to allow function chaining.
"""
return self.add(*args, row_width=self.max_row_keys)
def to_json(self):
"""
Converts this object to its json representation following the Telegram API guidelines described here:
https://core.telegram.org/bots/api#replykeyboardmarkup
:return:
"""
json_dict = {'keyboard': self.keyboard}
if self.one_time_keyboard is not None:
json_dict['one_time_keyboard'] = self.one_time_keyboard
if self.resize_keyboard is not None:
json_dict['resize_keyboard'] = self.resize_keyboard
if self.selective is not None:
json_dict['selective'] = self.selective
if self.input_field_placeholder:
json_dict['input_field_placeholder'] = self.input_field_placeholder
return json.dumps(json_dict)
class KeyboardButtonPollType(Dictionaryable):