forked from python-telegram-bot/python-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2438 lines (1971 loc) · 99.3 KB
/
bot.py
File metadata and controls
2438 lines (1971 loc) · 99.3 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Bot."""
import functools
import logging
import warnings
from datetime import datetime
from telegram import (User, Message, Update, Chat, ChatMember, UserProfilePhotos, File,
ReplyMarkup, TelegramObject, WebhookInfo, GameHighScore)
from telegram.error import InvalidToken, TelegramError
from telegram.utils.helpers import to_timestamp
from telegram.utils.request import Request
logging.getLogger(__name__).addHandler(logging.NullHandler())
def info(func):
@functools.wraps(func)
def decorator(self, *args, **kwargs):
if not self.bot:
self.get_me()
result = func(self, *args, **kwargs)
return result
return decorator
def log(func):
logger = logging.getLogger(func.__module__)
@functools.wraps(func)
def decorator(self, *args, **kwargs):
logger.debug('Entering: %s', func.__name__)
result = func(self, *args, **kwargs)
logger.debug(result)
logger.debug('Exiting: %s', func.__name__)
return result
return decorator
def message(func):
@functools.wraps(func)
def decorator(self, *args, **kwargs):
url, data = func(self, *args, **kwargs)
return self._message_wrapper(url, data, *args, **kwargs)
return decorator
class Bot(TelegramObject):
"""This object represents a Telegram Bot.
Properties:
id (int): Unique identifier for this bot.
first_name (str): Bot's first name.
last_name (str): Bot's last name.
username (str): Bot's username.
name (str): Bot's @username.
Args:
token (str): Bot's unique authentication.
base_url (Optional[str]): Telegram Bot API service URL.
base_file_url (Optional[str]): Telegram Bot API file URL.
request (Optional[Request]): Pre initialized `Request` class.
"""
def __init__(self, token, base_url=None, base_file_url=None, request=None):
self.token = self._validate_token(token)
if base_url is None:
base_url = 'https://api.telegram.org/bot'
if base_file_url is None:
base_file_url = 'https://api.telegram.org/file/bot'
self.base_url = str(base_url) + str(self.token)
self.base_file_url = str(base_file_url) + str(self.token)
self.bot = None
self._request = request or Request()
self.logger = logging.getLogger(__name__)
@property
def request(self):
return self._request
@staticmethod
def _validate_token(token):
"""a very basic validation on token"""
if any(x.isspace() for x in token):
raise InvalidToken()
left, sep, _right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise InvalidToken()
return token
@property
@info
def id(self):
return self.bot.id
@property
@info
def first_name(self):
return self.bot.first_name
@property
@info
def last_name(self):
return self.bot.last_name
@property
@info
def username(self):
return self.bot.username
@property
def name(self):
return '@{0}'.format(self.username)
def _message_wrapper(self, url, data, *args, **kwargs):
if kwargs.get('reply_to_message_id'):
data['reply_to_message_id'] = kwargs.get('reply_to_message_id')
if kwargs.get('disable_notification'):
data['disable_notification'] = kwargs.get('disable_notification')
if kwargs.get('reply_markup'):
reply_markup = kwargs.get('reply_markup')
if isinstance(reply_markup, ReplyMarkup):
data['reply_markup'] = reply_markup.to_json()
else:
data['reply_markup'] = reply_markup
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
if result is True:
return result
return Message.de_json(result, self)
@log
def get_me(self, timeout=None, **kwargs):
"""A simple method for testing your bot's auth token.
Args:
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
Returns:
:class:`telegram.User`: A :class:`telegram.User` instance representing that bot if the
credentials are valid, `None` otherwise.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/getMe'.format(self.base_url)
result = self._request.get(url, timeout=timeout)
self.bot = User.de_json(result, self)
return self.bot
@log
@message
def send_message(self,
chat_id,
text,
parse_mode=None,
disable_web_page_preview=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""Use this method to send text messages.
Args:
chat_id (int|str): Unique identifier for the target chat or
username of the target channel (in the format
@channelusername).
text (str): Text of the message to be sent. The current maximum
length is 4096 UTF-8 characters.
parse_mode (Optional[str]): Send Markdown or HTML, if you want
Telegram apps to show bold, italic, fixed-width text or inline
URLs in your bot's message.
disable_web_page_preview (Optional[bool]): Disables link previews
for links in this message.
disable_notification (Optional[bool]): Sends the message silently.
iOS users will not receive a notification, Android users will
receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply,
ID of the original message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional
interface options. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to remove reply
keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendMessage'.format(self.base_url)
data = {'chat_id': chat_id, 'text': text}
if parse_mode:
data['parse_mode'] = parse_mode
if disable_web_page_preview:
data['disable_web_page_preview'] = disable_web_page_preview
return url, data
@log
def delete_message(self, chat_id, message_id, timeout=None, **kwargs):
"""Use this method to delete a message. A message can only be deleted if it was sent less
than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally,
if the bot is an administrator in a group chat, it can delete any message. If the bot is
an administrator in a supergroup, it can delete messages from any other user and service
messages about people joining or leaving the group (other types of service messages may
only be removed by the group creator). In channels, bots can only remove their own
messages.
Args:
chat_id (int|str): Unique identifier for the target chat or
username of the target channel (in the format
@channelusername).
message_id (int): Unique message identifier.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/deleteMessage'.format(self.base_url)
data = {'chat_id': chat_id, 'message_id': message_id}
result = self._request.post(url, data, timeout=timeout)
return result
@log
@message
def forward_message(self,
chat_id,
from_chat_id,
message_id,
disable_notification=False,
timeout=None,
**kwargs):
"""Use this method to forward messages of any kind.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
from_chat_id (int|str): Unique identifier for the chat where the original message was
sent - Chat id.
message_id (int): Unique message identifier.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message forwarded.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/forwardMessage'.format(self.base_url)
data = {}
if chat_id:
data['chat_id'] = chat_id
if from_chat_id:
data['from_chat_id'] = from_chat_id
if message_id:
data['message_id'] = message_id
return url, data
@log
@message
def send_photo(self,
chat_id,
photo,
caption=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
**kwargs):
"""Use this method to send photos.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
photo: Photo to send. You can either pass a file_id as String to resend a photo that is
already on the Telegram servers, or upload a new photo using multipart/form-data.
caption (Optional[str]): Photo caption (may also be used when resending photos by
file_id).
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendPhoto'.format(self.base_url)
data = {'chat_id': chat_id, 'photo': photo}
if caption:
data['caption'] = caption
return url, data
@log
@message
def send_audio(self,
chat_id,
audio,
duration=None,
performer=None,
title=None,
caption=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
**kwargs):
"""Use this method to send audio files, if you want Telegram clients to
display them in the music player. Your audio must be in an .mp3 format.
On success, the sent Message is returned. Bots can currently send audio
files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when both fields title and description are
empty and mime-type of the sent file is not "audio/mpeg", file is sent
as playable voice message. In this case, your audio must be in an .ogg
file encoded with OPUS. This will be removed in the future. You need to
use sendVoice method instead.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
audio: Audio file to send. You can either pass a file_id as String to resend an audio
that is already on the Telegram servers, or upload a new audio file using
multipart/form-data.
duration (Optional[int]): Duration of sent audio in seconds.
performer (Optional[str]): Performer of sent audio.
title (Optional[str]): Title of sent audio.
caption (Optional[str]): Audio caption
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendAudio'.format(self.base_url)
data = {'chat_id': chat_id, 'audio': audio}
if duration:
data['duration'] = duration
if performer:
data['performer'] = performer
if title:
data['title'] = title
if caption:
data['caption'] = caption
return url, data
@log
@message
def send_document(self,
chat_id,
document,
filename=None,
caption=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
**kwargs):
"""Use this method to send general files.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
document: File to send. You can either pass a file_id as String to resend a file that
is already on the Telegram servers, or upload a new file using multipart/form-data.
filename (Optional[str]): File name that shows in telegram message (it is useful when
you send file generated by temp module, for example).
caption (Optional[str]): Document caption (may also be used when resending documents by
file_id), 0-200 characters.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendDocument'.format(self.base_url)
data = {'chat_id': chat_id, 'document': document}
if filename:
data['filename'] = filename
if caption:
data['caption'] = caption
return url, data
@log
@message
def send_sticker(self,
chat_id,
sticker,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""Use this method to send .webp stickers.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
sticker: Sticker to send. You can either pass a file_id as String to resend a sticker
that is already on the Telegram servers, or upload a new sticker using
multipart/form-data.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendSticker'.format(self.base_url)
data = {'chat_id': chat_id, 'sticker': sticker}
return url, data
@log
@message
def send_video(self,
chat_id,
video,
duration=None,
caption=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
width=None,
height=None,
**kwargs):
"""Use this method to send video files, Telegram clients support mp4
videos (other formats may be sent as telegram.Document).
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
video: Video to send. You can either pass a file_id as String to resend a video that is
already on the Telegram servers, or upload a new video file using
multipart/form-data.
duration (Optional[int]): Duration of sent video in seconds.
width (Optional[int)): Video width.
height (Optional[int]): Video height.
caption (Optional[str]): Video caption (may also be used when resending videos by
file_id).
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVideo'.format(self.base_url)
data = {'chat_id': chat_id, 'video': video}
if duration:
data['duration'] = duration
if caption:
data['caption'] = caption
if width:
data['width'] = width
if height:
data['height'] = height
return url, data
@log
@message
def send_voice(self,
chat_id,
voice,
duration=None,
caption=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
**kwargs):
"""Use this method to send audio files, if you want Telegram clients to display the file as
a playable voice message. For this to work, your audio must be in an .ogg file encoded with
OPUS (other formats may be sent as Audio or Document). On success, the sent Message is
returned. Bots can currently send audio files of up to 50 MB in size, this limit may be
changed in the future.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
voice: Audio file to send. You can either pass a file_id as String to resend an audio
that is already on the Telegram servers, or upload a new audio file using
multipart/form-data.
duration (Optional[int]): Duration of sent audio in seconds.
caption (Optional[str]): Voice caption
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVoice'.format(self.base_url)
data = {'chat_id': chat_id, 'voice': voice}
if duration:
data['duration'] = duration
if caption:
data['caption'] = caption
return url, data
@log
@message
def send_video_note(self,
chat_id,
video_note,
duration=None,
length=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20.,
**kwargs):
"""As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute
long. Use this method to send video messages
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
video_note (InputFile|str): Video note to send. Pass a file_id as String to send a
video note that exists on the Telegram servers (recommended) or upload a new video.
Sending video notes by a URL is currently unsupported
duration (Optional[int]): Duration of sent audio in seconds.
length (Optional[int]): Video width and height
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): Send file timeout (default: 20 seconds).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVideoNote'.format(self.base_url)
data = {'chat_id': chat_id, 'video_note': video_note}
if duration is not None:
data['duration'] = duration
if length is not None:
data['length'] = length
return url, data
@log
@message
def send_location(self,
chat_id,
latitude,
longitude,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""Use this method to send point on the map.
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
latitude (float): Latitude of location.
longitude (float): Longitude of location.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendLocation'.format(self.base_url)
data = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
return url, data
@log
@message
def send_venue(self,
chat_id,
latitude,
longitude,
title,
address,
foursquare_id=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""
Use this method to send information about a venue.
Args:
chat_id (int|str): Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
latitude (float): Latitude of the venue.
longitude (float): Longitude of the venue.
title (str): Name of the venue.
address (str): Address of the venue.
foursquare_id (Optional[str]): Foursquare identifier of the venue.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVenue'.format(self.base_url)
data = {
'chat_id': chat_id,
'latitude': latitude,
'longitude': longitude,
'address': address,
'title': title
}
if foursquare_id:
data['foursquare_id'] = foursquare_id
return url, data
@log
@message
def send_contact(self,
chat_id,
phone_number,
first_name,
last_name=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""
Use this method to send phone contacts.
Args:
chat_id (int|str): Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
phone_number (str): Contact's phone number.
first_name (str): Contact's first name.
last_name (Optional[str]): Contact's last name.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options. A
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendContact'.format(self.base_url)
data = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
if last_name:
data['last_name'] = last_name
return url, data
@log
@message
def send_game(self,
chat_id,
game_short_name,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""Use this method to send a game.
Args:
chat_id (int|str): Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
game_short_name (str): Short name of the game, serves as the unique identifier for the
game.
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply,
ID of the original message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options.
A JSON-serialized object for an inline keyboard, custom reply keyboard,
instructions to remove reply keyboard or to force a reply from the user.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendGame'.format(self.base_url)
data = {'chat_id': chat_id, 'game_short_name': game_short_name}
return url, data
@log
def send_chat_action(self, chat_id, action, timeout=None, **kwargs):
"""Use this method when you need to tell the user that something is happening on the bot's
side. The status is set for 5 seconds or less (when a message arrives from your bot,
Telegram clients clear its typing status).
Args:
chat_id (int|str): Unique identifier for the message recipient - Chat id.
action(:class:`telegram.ChatAction`|str): Type of action to broadcast. Choose one,
depending on what the user is about to receive:
- ChatAction.TYPING for text messages,
- ChatAction.UPLOAD_PHOTO for photos,
- ChatAction.UPLOAD_VIDEO for videos,
- ChatAction.UPLOAD_AUDIO for audio files,
- ChatAction.UPLOAD_DOCUMENT for general files,
- ChatAction.FIND_LOCATION for location data.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
"""
url = '{0}/sendChatAction'.format(self.base_url)
data = {'chat_id': chat_id, 'action': action}
result = self._request.post(url, data, timeout=timeout)
return result
@log
def answer_inline_query(self,
inline_query_id,
results,
cache_time=300,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None,
timeout=None,
**kwargs):
"""Use this method to send answers to an inline query. No more than 50 results per query
are allowed.
Args:
inline_query_id (str): Unique identifier for the answered query.
results (list[:class:`telegram.InlineQueryResult`]): A list of results for the inline
query.
cache_time (Optional[int]): The maximum amount of time the result of the inline query
may be cached on the server.
is_personal (Optional[bool]): Pass `True`, if results may be cached on the server side
only for the user that sent the query. By default, results may be returned to any
user who sends the same query.
next_offset (Optional[str]): Pass the offset that a client should send in the next
query with the same text to receive more results. Pass an empty string if there are
no more results or if you don't support pagination. Offset length can't exceed 64
bytes.
switch_pm_text (Optional[str]): If passed, clients will display a button with specified
text that switches the user to a private chat with the bot and sends the bot a
start message with the parameter switch_pm_parameter.
switch_pm_parameter (Optional[str]): Parameter for the start message sent to the bot
when user presses the switch button.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/answerInlineQuery'.format(self.base_url)
results = [res.to_dict() for res in results]
data = {'inline_query_id': inline_query_id, 'results': results}
if cache_time or cache_time == 0:
data['cache_time'] = cache_time
if is_personal:
data['is_personal'] = is_personal
if next_offset is not None:
data['next_offset'] = next_offset
if switch_pm_text:
data['switch_pm_text'] = switch_pm_text
if switch_pm_parameter:
data['switch_pm_parameter'] = switch_pm_parameter
result = self._request.post(url, data, timeout=timeout)
return result
@log
def get_user_profile_photos(self, user_id, offset=None, limit=100, timeout=None, **kwargs):
"""Use this method to get a list of profile pictures for a user.
Args:
user_id (int): Unique identifier of the target user.
offset (Optional[int]): Sequential number of the first photo to be returned. By
default, all photos are returned.
limit (Optional[int]): Limits the number of photos to be retrieved. Values between
1-100 are accepted. Defaults to 100.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
list[:class:`telegram.UserProfilePhotos`]: A list of user profile photos objects is
returned.
Raises:
:class:`telegram.TelegramError`
"""