forked from python-telegram-bot/python-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
3454 lines (2837 loc) · 147 KB
/
bot.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
#!/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-2018
# Leandro Toledo de Souza <[email protected]>
#
# 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
try:
import ujson as json
except ImportError:
import json
import logging
import warnings
from datetime import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from future.utils import string_types
from telegram import (User, Message, Update, Chat, ChatMember, UserProfilePhotos, File,
ReplyMarkup, TelegramObject, WebhookInfo, GameHighScore, StickerSet,
PhotoSize, Audio, Document, Sticker, Video, Animation, Voice, VideoNote,
Location, Venue, Contact, InputFile)
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)
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)
return decorator
class Bot(TelegramObject):
"""This object represents a Telegram Bot.
Args:
token (:obj:`str`): Bot's unique authentication.
base_url (:obj:`str`, optional): Telegram Bot API service URL.
base_file_url (:obj:`str`, optional): Telegram Bot API file URL.
request (:obj:`telegram.utils.request.Request`, optional): Pre initialized
:obj:`telegram.utils.request.Request`.
private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
private_key_password (:obj:`bytes`, optional): Password for above private key.
"""
def __init__(self, token, base_url=None, base_file_url=None, request=None, private_key=None,
private_key_password=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__)
if private_key:
self.private_key = serialization.load_pem_private_key(private_key,
password=private_key_password,
backend=default_backend())
@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):
""":obj:`int`: Unique identifier for this bot."""
return self.bot.id
@property
@info
def first_name(self):
""":obj:`str`: Bot's first name."""
return self.bot.first_name
@property
@info
def last_name(self):
""":obj:`str`: Optional. Bot's last name."""
return self.bot.last_name
@property
@info
def username(self):
""":obj:`str`: Bot's username."""
return self.bot.username
@property
def name(self):
""":obj:`str`: Bot's @username."""
return '@{0}'.format(self.username)
@log
def get_me(self, timeout=None, **kwargs):
"""A simple method for testing your bot's auth token. Requires no parameters.
Args:
timeout (:obj:`int` | :obj:`float`, optional): 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, :obj:`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 (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
text (:obj:`str`): Text of the message to be sent. Max 4096 characters. Also found as
:attr:`telegram.constants.MAX_MESSAGE_LENGTH`.
parse_mode (:obj:`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. See the constants in
:class:`telegram.ParseMode` for the available modes.
disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in
this message.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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 (:obj:`int` | :obj:`float`, optional): 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 (:obj:`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 (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
message_id (:obj:`int`): Identifier of the message to delete.
timeout (:obj:`int` | :obj:`float`, optional): 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 (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:obj:`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 (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
from_chat_id (:obj:`int` | :obj:`str`): Unique identifier for the chat where the
original message was sent (or channel username in the format @channelusername).
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
message_id (:obj:`int`): Message identifier in the chat specified in from_chat_id.
timeout (:obj:`int` | :obj:`float`, optional): 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 (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
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,
parse_mode=None,
**kwargs):
"""Use this method to send photos.
Note:
The photo argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
photo (:obj:`str` | `filelike object` | :class:`telegram.PhotoSize`): Photo to send.
Pass a file_id as String to send a photo that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a photo from the
Internet, or upload a new photo using multipart/form-data. Lastly you can pass
an existing :class:`telegram.PhotoSize` object to send.
caption (:obj:`str`, optional): Photo caption (may also be used when resending photos
by file_id), 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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 (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendPhoto'.format(self.base_url)
if isinstance(photo, PhotoSize):
photo = photo.file_id
elif InputFile.is_file(photo):
photo = InputFile(photo)
data = {'chat_id': chat_id, 'photo': photo}
if caption:
data['caption'] = caption
if parse_mode:
data['parse_mode'] = parse_mode
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,
parse_mode=None,
thumb=None,
**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 the .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 sending voice messages, use the sendVoice method instead.
Note:
The audio argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
audio (:obj:`str` | `filelike object` | :class:`telegram.Audio`): Audio file to send.
Pass a file_id as String to send an audio file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get an audio file from
the Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Audio` object to send.
caption (:obj:`str`, optional): Audio caption, 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
duration (:obj:`int`, optional): Duration of sent audio in seconds.
performer (:obj:`str`, optional): Performer.
title (:obj:`str`, optional): Track name.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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.
thumb (`filelike object`, optional): Thumbnail of the
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
A thumbnail's width and height should not exceed 90. Ignored if the file is not
is passed as a string or file_id.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendAudio'.format(self.base_url)
if isinstance(audio, Audio):
audio = audio.file_id
elif InputFile.is_file(audio):
audio = InputFile(audio)
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
if parse_mode:
data['parse_mode'] = parse_mode
if thumb:
if InputFile.is_file(thumb):
thumb = InputFile(thumb, attach=True)
data['thumb'] = thumb
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,
parse_mode=None,
thumb=None,
**kwargs):
"""Use this method to send general files.
Note:
The document argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
document (:obj:`str` | `filelike object` | :class:`telegram.Document`): File to send.
Pass a file_id as String to send a file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a file from the
Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Document` object to send.
filename (:obj:`str`, optional): File name that shows in telegram message (it is useful
when you send file generated by temp module, for example). Undocumented.
caption (:obj:`str`, optional): Document caption (may also be used when resending
documents by file_id), 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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.
thumb (`filelike object`, optional): Thumbnail of the
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
A thumbnail's width and height should not exceed 90. Ignored if the file is not
is passed as a string or file_id.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendDocument'.format(self.base_url)
if isinstance(document, Document):
document = document.file_id
elif InputFile.is_file(document):
document = InputFile(document, filename=filename)
data = {'chat_id': chat_id, 'document': document}
if caption:
data['caption'] = caption
if parse_mode:
data['parse_mode'] = parse_mode
if thumb:
if InputFile.is_file(thumb):
thumb = InputFile(thumb, attach=True)
data['thumb'] = thumb
return url, data
@log
@message
def send_sticker(self,
chat_id,
sticker,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20,
**kwargs):
"""Use this method to send .webp stickers.
Note:
The sticker argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
sticker (:obj:`str` | `filelike object` :class:`telegram.Sticker`): Sticker to send.
Pass a file_id as String to send a file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a .webp file from
the Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Sticker` object to send.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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 (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendSticker'.format(self.base_url)
if isinstance(sticker, Sticker):
sticker = sticker.file_id
elif InputFile.is_file(sticker):
sticker = InputFile(sticker)
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,
parse_mode=None,
supports_streaming=None,
thumb=None,
**kwargs):
"""
Use this method to send video files, Telegram clients support mp4 videos
(other formats may be sent as Document).
Note:
The video argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
video (:obj:`str` | `filelike object` | :class:`telegram.Video`): Video file to send.
Pass a file_id as String to send an video file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get an video file from
the Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Video` object to send.
duration (:obj:`int`, optional): Duration of sent video in seconds.
width (:obj:`int`, optional): Video width.
height (:obj:`int`, optional): Video height.
caption (:obj:`str`, optional): Video caption (may also be used when resending videos
by file_id), 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
supports_streaming (:obj:`bool`, optional): Pass True, if the uploaded video is
suitable for streaming.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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.
thumb (`filelike object`, optional): Thumbnail of the
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
A thumbnail's width and height should not exceed 90. Ignored if the file is not
is passed as a string or file_id.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVideo'.format(self.base_url)
if isinstance(video, Video):
video = video.file_id
elif InputFile.is_file(video):
video = InputFile(video)
data = {'chat_id': chat_id, 'video': video}
if duration:
data['duration'] = duration
if caption:
data['caption'] = caption
if parse_mode:
data['parse_mode'] = parse_mode
if supports_streaming:
data['supports_streaming'] = supports_streaming
if width:
data['width'] = width
if height:
data['height'] = height
if thumb:
if InputFile.is_file(thumb):
thumb = InputFile(thumb, attach=True)
data['thumb'] = thumb
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,
thumb=None,
**kwargs):
"""Use this method to send video messages.
Note:
The video_note argument can be either a file_id or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
video_note (:obj:`str` | `filelike object` | :class:`telegram.VideoNote`): 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 using multipart/form-data. Or you can
pass an existing :class:`telegram.VideoNote` object to send. Sending video notes by
a URL is currently unsupported.
duration (:obj:`int`, optional): Duration of sent video in seconds.
length (:obj:`int`, optional): Video width and height
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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.
thumb (`filelike object`, optional): Thumbnail of the
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
A thumbnail's width and height should not exceed 90. Ignored if the file is not
is passed as a string or file_id.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVideoNote'.format(self.base_url)
if isinstance(video_note, VideoNote):
video_note = video_note.file_id
elif InputFile.is_file(video_note):
video_note = InputFile(video_note)
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
if thumb:
if InputFile.is_file(thumb):
thumb = InputFile(thumb, attach=True)
data['thumb'] = thumb
return url, data
@log
@message
def send_animation(self,
chat_id,
animation,
duration=None,
width=None,
height=None,
thumb=None,
caption=None,
parse_mode=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=20,
**kwargs):
"""
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
animation (:obj:`str` | `filelike object` | :class:`telegram.Animation`): Animation to
send. Pass a file_id as String to send an animation that exists on the Telegram
servers (recommended), pass an HTTP URL as a String for Telegram to get an
animation from the Internet, or upload a new animation using multipart/form-data.
Lastly you can pass an existing :class:`telegram.Animation` object to send.
duration (:obj:`int`, optional): Duration of sent animation in seconds.
width (:obj:`int`, optional): Animation width.
height (:obj:`int`, optional): Animation height.
thumb (`filelike object`, optional): Thumbnail of the
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
A thumbnail's width and height should not exceed 90. Ignored if the file is not
is passed as a string or file_id.
caption (:obj:`str`, optional): Animation caption (may also be used when resending
animations by file_id), 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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 (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendAnimation'.format(self.base_url)
if isinstance(animation, Animation):
animation = animation.file_id
elif InputFile.is_file(animation):
animation = InputFile(animation)
data = {'chat_id': chat_id, 'animation': animation}
if duration:
data['duration'] = duration
if width:
data['width'] = width
if height:
data['height'] = height
if thumb:
if InputFile.is_file(thumb):
thumb = InputFile(thumb, attach=True)
data['thumb'] = thumb
if caption:
data['caption'] = caption
if parse_mode:
data['parse_mode'] = parse_mode
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,
parse_mode=None,
**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).
Note:
The voice argument can be either a file_id, an URL or a file from disk
``open(filename, 'rb')``
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
voice (:obj:`str` | `filelike object` | :class:`telegram.Voice`): Voice file to send.
Pass a file_id as String to send an voice file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get an voice file from
the Internet, or upload a new one using multipart/form-data. Lastly you can pass
an existing :class:`telegram.Voice` object to send.
caption (:obj:`str`, optional): Voice message caption, 0-200 characters.
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in :class:`telegram.ParseMode` for the available modes.
duration (:obj:`int`, optional): Duration of the voice message in seconds.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
reply_markup (:class:`telegram.ReplyMarkup`, optional): 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 (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, the sent Message is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendVoice'.format(self.base_url)
if isinstance(voice, Voice):
voice = voice.file_id
elif InputFile.is_file(voice):
voice = InputFile(voice)
data = {'chat_id': chat_id, 'voice': voice}
if duration:
data['duration'] = duration
if caption:
data['caption'] = caption
if parse_mode:
data['parse_mode'] = parse_mode
return url, data
@log
def send_media_group(self,
chat_id,
media,
disable_notification=None,
reply_to_message_id=None,
timeout=20,
**kwargs):
"""Use this method to send a group of photos or videos as an album.
Args:
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format @channelusername).
media (List[:class:`telegram.InputMedia`]): An array describing photos and videos to be
sent, must include 2–10 items.
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
receive a notification with no sound.
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
original message.
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Returns:
List[:class:`telegram.Message`]: An array of the sent Messages.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendMediaGroup'.format(self.base_url)
data = {'chat_id': chat_id, 'media': media}
if reply_to_message_id:
data['reply_to_message_id'] = reply_to_message_id
if disable_notification:
data['disable_notification'] = disable_notification
result = self._request.post(url, data, timeout=timeout)
return [Message.de_json(res, self) for res in result]
@log
@message
def send_location(self,
chat_id,
latitude=None,
longitude=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
location=None,
live_period=None,
**kwargs):
"""Use this method to send point on the map.
Note:
You can either supply a :obj:`latitude` and :obj:`longitude` or a :obj:`location`.