/
webhook.py
2363 lines (1994 loc) · 96 KB
/
webhook.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
import asyncio
import asyncio.tasks
import datetime
import functools
import ipaddress
import itertools
import typing
import logging
from typing import Dict, List, Optional, Union
from aiohttp import web
from aiohttp.web_exceptions import HTTPGone
from .. import types
from ..bot import api
from ..types import ParseMode
from ..types.base import Boolean, Float, Integer, String
from ..utils import helper, markdown
from ..utils import json
from ..utils.deprecated import warn_deprecated as warn
from ..utils.exceptions import TimeoutWarning
from ..utils.payload import prepare_arg
DEFAULT_WEB_PATH = '/webhook'
DEFAULT_ROUTE_NAME = 'webhook_handler'
BOT_DISPATCHER_KEY = 'BOT_DISPATCHER'
RESPONSE_TIMEOUT = 55
WEBHOOK = 'webhook'
WEBHOOK_CONNECTION = 'WEBHOOK_CONNECTION'
WEBHOOK_REQUEST = 'WEBHOOK_REQUEST'
TELEGRAM_SUBNET_1 = ipaddress.IPv4Network('149.154.160.0/20')
TELEGRAM_SUBNET_2 = ipaddress.IPv4Network('91.108.4.0/22')
allowed_ips = set()
log = logging.getLogger(__name__)
def _check_ip(ip: str) -> bool:
"""
Check IP in range
:param ip:
:return:
"""
address = ipaddress.IPv4Address(ip)
return address in allowed_ips
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
"""
Allow ip address.
:param ips:
:return:
"""
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipaddress.IPv4Address(ip))
elif isinstance(ip, ipaddress.IPv4Network):
allowed_ips.update(ip.hosts())
else:
raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
# Allow access from Telegram servers
allow_ip(TELEGRAM_SUBNET_1, TELEGRAM_SUBNET_2)
class WebhookRequestHandler(web.View):
"""
Simple Webhook request handler for aiohttp web server.
You need to register that in app:
.. code-block:: python3
app.router.add_route('*', '/your/webhook/path', WebhookRequestHandler, name='webhook_handler')
But first you need to configure application for getting Dispatcher instance from request handler!
It must always be with key 'BOT_DISPATCHER'
.. code-block:: python3
bot = Bot(TOKEN, loop)
dp = Dispatcher(bot)
app['BOT_DISPATCHER'] = dp
"""
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_current(dp.bot)
except RuntimeError:
pass
return dp
async def parse_update(self, bot):
"""
Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update`
"""
data = await self.request.json()
return types.Update(**data)
async def post(self):
"""
Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response`
"""
self.validate_ip()
# context.update_state({'CALLER': WEBHOOK,
# WEBHOOK_CONNECTION: True,
# WEBHOOK_REQUEST: self.request})
dispatcher = self.get_dispatcher()
update = await self.parse_update(dispatcher.bot)
results = await self.process_update(update)
response = self.get_response(results)
if response:
web_response = response.get_web_response()
else:
web_response = web.Response(text='ok')
if self.request.app.get('RETRY_AFTER', None):
web_response.headers['Retry-After'] = str(self.request.app['RETRY_AFTER'])
return web_response
async def get(self):
self.validate_ip()
return web.Response(text='')
async def head(self):
self.validate_ip()
return web.Response(text='')
async def process_update(self, update):
"""
Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return:
"""
dispatcher = self.get_dispatcher()
loop = asyncio.get_event_loop()
# Analog of `asyncio.wait_for` but without cancelling task
waiter = loop.create_future()
timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter)
cb = functools.partial(asyncio.tasks._release_waiter, waiter)
fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update))
fut.add_done_callback(cb)
try:
try:
await waiter
except asyncio.CancelledError:
fut.remove_done_callback(cb)
fut.cancel()
raise
if fut.done():
return fut.result()
# context.set_value(WEBHOOK_CONNECTION, False)
fut.remove_done_callback(cb)
fut.add_done_callback(self.respond_via_request)
finally:
timeout_handle.cancel()
def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.",
TimeoutWarning)
dispatcher = self.get_dispatcher()
loop = asyncio.get_running_loop()
try:
results = task.result()
except Exception as e:
loop.create_task(
dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e))
else:
response = self.get_response(results)
if response is not None:
asyncio.ensure_future(response.execute_response(dispatcher.bot))
def get_response(self, results):
"""
Get response object from results.
:param results: list
:return:
"""
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
return result
def check_ip(self):
"""
Check client IP. Accept requests only from telegram servers.
:return:
"""
# For reverse proxy (nginx)
forwarded_for = self.request.headers.get('X-Forwarded-For', None)
if forwarded_for:
# get the left-most ip when there is multiple ips (request got through multiple proxy/load balancers)
forwarded_for = forwarded_for.split(",")[0]
return forwarded_for, _check_ip(forwarded_for)
# For default method
peer_name = self.request.transport.get_extra_info('peername')
if peer_name is not None:
host, _ = peer_name
return host, _check_ip(host)
# Not allowed and can't get client IP
return None, False
def validate_ip(self):
"""
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
"""
if self.request.app.get('_check_ip', False):
ip_address, accept = self.check_ip()
if not accept:
log.warning(f"Blocking request from an unauthorized IP: {ip_address}")
raise web.HTTPUnauthorized()
# context.set_value('TELEGRAM_IP', ip_address)
class GoneRequestHandler(web.View):
"""
If a webhook returns the HTTP error 410 Gone for all requests for more than 23 hours successively,
it can be automatically removed.
"""
async def get(self):
raise HTTPGone()
async def post(self):
raise HTTPGone()
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME):
"""
You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
:param route_name: Name of webhook handler route
:return:
"""
app.router.add_route('*', path, WebhookRequestHandler, name=route_name)
app[BOT_DISPATCHER_KEY] = dispatcher
def get_new_configured_app(dispatcher, path=DEFAULT_WEB_PATH):
"""
Create new :class:`aiohttp.web.Application` and configure it.
:param dispatcher: Dispatcher instance
:param path: Path to your webhook.
:return:
"""
app = web.Application()
configure_app(dispatcher, app, path)
return app
class BaseResponse:
"""
Base class for webhook responses.
"""
@property
def method(self) -> str:
"""
In all subclasses of that class you need to override this property
:return: str
"""
raise NotImplementedError
def prepare(self) -> typing.Dict:
"""
You need to override this method.
:return: response parameters dict
"""
raise NotImplementedError
def cleanup(self) -> typing.Dict:
"""
Cleanup response after preparing. Remove empty fields.
:return: response parameters dict
"""
return {k: v for k, v in self.prepare().items() if v is not None}
def get_response(self):
"""
Get response object
:return:
"""
return {'method': self.method, **self.cleanup()}
def get_web_response(self):
"""
Get prepared web response with JSON data.
:return: :class:`aiohttp.web.Response`
"""
return web.json_response(self.get_response(), dumps=json.dumps)
async def execute_response(self, bot):
"""
Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return:
"""
method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case)
method = getattr(bot, method_name, None)
if method:
return await method(**self.cleanup())
return await bot.request(self.method, self.cleanup())
async def __call__(self, bot=None):
if bot is None:
from aiogram import Bot
bot = Bot.get_current()
return await self.execute_response(bot)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
return await self()
class ReplyToMixin:
"""
Mixin for responses where from which can reply to messages.
"""
def reply(self, message: typing.Union[int, types.Message]):
"""
Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self
"""
setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)
return self
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(target, types.Chat):
chat_id = target.id
elif isinstance(target, (int, str)):
chat_id = target
else:
raise TypeError(f"Bad type of target. ({type(target)})")
setattr(self, 'chat_id', chat_id)
return self
class DisableNotificationMixin:
def without_notification(self):
"""
Disable notification
:return:
"""
setattr(self, 'disable_notification', True)
return self
class DisableWebPagePreviewMixin:
def no_web_page_preview(self):
"""
Disable web page preview
:return:
"""
setattr(self, 'disable_web_page_preview', True)
return self
@staticmethod
def _global_disable_web_page_preview():
"""
Detect global disable web page preview value
:return:
"""
from aiogram import Bot
bot = Bot.get_current()
if bot is not None:
return bot.disable_web_page_preview
class ProtectContentMixin:
def protect_content(self):
"""
Protect content
:return:
"""
setattr(self, "protect_content", True)
return self
@staticmethod
def _global_protect_content():
"""
Detect global protect content value
:return:
"""
from aiogram import Bot
bot = Bot.get_current()
if bot is not None:
return bot.protect_content
class ParseModeMixin:
def as_html(self):
"""
Set parse_mode to HTML
:return:
"""
setattr(self, 'parse_mode', ParseMode.HTML)
return self
def as_markdown(self):
"""
Set parse_mode to Markdown
:return:
"""
setattr(self, 'parse_mode', ParseMode.MARKDOWN)
return self
@staticmethod
def _global_parse_mode():
"""
Detect global parse mode
:return:
"""
from aiogram import Bot
bot = Bot.get_current()
if bot is not None:
return bot.parse_mode
class SendMessage(BaseResponse, ReplyToMixin, ParseModeMixin,
DisableNotificationMixin, DisableWebPagePreviewMixin,
ProtectContentMixin):
"""
You can send message with webhook by using this instance of this object.
All arguments is equal with Bot.send_message method.
"""
__slots__ = ('chat_id', 'text', 'parse_mode',
'disable_web_page_preview', 'disable_notification',
'protect_content', 'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_MESSAGE
def __init__(self, chat_id: Union[Integer, String] = None,
text: String = None,
parse_mode: Optional[String] = None,
disable_web_page_preview: Optional[Boolean] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param text: String - Text of the message to be sent
:param parse_mode: String (Optional) - Send Markdown or HTML, if you want Telegram apps to show bold,
italic, fixed-width text or inline URLs in your bot's message.
:param disable_web_page_preview: Boolean (Optional) - Disables link previews for links in this message
:param disable_notification: Boolean (Optional) - Sends the message silently. Users will receive
a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if text is None:
text = ''
if parse_mode is None:
parse_mode = self._global_parse_mode()
if disable_web_page_preview is None:
disable_web_page_preview = self._global_disable_web_page_preview()
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.text = text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self) -> dict:
return {
'chat_id': self.chat_id,
'text': self.text,
'parse_mode': self.parse_mode,
'disable_web_page_preview': self.disable_web_page_preview,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self
def write_ln(self, *text, sep=' '):
"""
Write line
:param text:
:param sep:
:return:
"""
if self.text and self.text[-1] != '\n':
self.text += '\n'
self.text += markdown.text(*text, sep) + '\n'
return self
class ForwardMessage(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for forward messages of any kind on to webhook.
"""
__slots__ = ('chat_id', 'from_chat_id', 'message_id', 'disable_notification', 'protect_content')
method = api.Methods.FORWARD_MESSAGE
def __init__(self, chat_id: Union[Integer, String] = None,
from_chat_id: Union[Integer, String] = None,
message_id: Integer = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username of the
target channel (in the format @channelusername)
:param from_chat_id: Union[Integer, String] - Unique identifier for the chat where the original
message was sent (or channel username in the format @channelusername)
:param disable_notification: Boolean (Optional) - Sends the message silently. Users will receive a
notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param message_id: Integer - Message identifier in the chat specified in from_chat_id
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.from_chat_id = from_chat_id
self.message_id = message_id
self.disable_notification = disable_notification
self.protect_content = protect_content
def message(self, message: types.Message):
"""
Select target message
:param message:
:return:
"""
setattr(self, 'from_chat_id', message.chat.id)
setattr(self, 'message_id', message.message_id)
return self
def prepare(self) -> dict:
return {
'chat_id': self.chat_id,
'from_chat_id': self.from_chat_id,
'message_id': self.message_id,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
}
class SendPhoto(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send photo on to webhook.
"""
__slots__ = ('chat_id', 'photo', 'caption', 'disable_notification',
'protect_content', 'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_PHOTO
def __init__(self, chat_id: Union[Integer, String],
photo: String,
caption: Optional[String] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username of
the target channel (in the format @channelusername)
:param photo: String - 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.
:param caption: String (Optional) - Photo caption (may also be used when resending photos by file_id),
0-1024 characters after entities parsing
:param disable_notification: Boolean (Optional) - Sends the message silently. Users will receive
a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.photo = photo
self.caption = caption
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self):
return {
'chat_id': self.chat_id,
'photo': self.photo,
'caption': self.caption,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
class SendAudio(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send audio on to webhook.
"""
__slots__ = ('chat_id', 'audio', 'caption', 'duration', 'performer', 'title',
'disable_notification', 'protect_content',
'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_AUDIO
def __init__(self, chat_id: Union[Integer, String],
audio: String,
caption: Optional[String] = None,
duration: Optional[Integer] = None,
performer: Optional[String] = None,
title: Optional[String] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param audio: String - 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.
:param caption: String (Optional) - Audio caption, 0-1024 characters after entities parsing
:param duration: Integer (Optional) - Duration of the audio in seconds
:param performer: String (Optional) - Performer
:param title: String (Optional) - Track name
:param disable_notification: Boolean (Optional) - Sends the message silently.
Users will receive a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.audio = audio
self.caption = caption
self.duration = duration
self.performer = performer
self.title = title
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self):
return {
'chat_id': self.chat_id,
'audio': self.audio,
'caption': self.caption,
'duration': self.duration,
'performer': self.performer,
'title': self.title,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
class SendDocument(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send document on to webhook.
"""
__slots__ = ('chat_id', 'document', 'caption', 'disable_notification',
'protect_content', 'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_DOCUMENT
def __init__(self, chat_id: Union[Integer, String],
document: String,
caption: Optional[String] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param document: String - 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.
:param caption: String (Optional) - Document caption
(may also be used when resending documents by file_id), 0-1024 characters after entities parsing
:param disable_notification: Boolean (Optional) - Sends the message silently.
Users will receive a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.document = document
self.caption = caption
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self):
return {
'chat_id': self.chat_id,
'document': self.document,
'caption': self.caption,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
class SendVideo(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send video on to webhook.
"""
__slots__ = ('chat_id', 'video', 'duration', 'width', 'height', 'caption',
'disable_notification', 'protect_content',
'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_VIDEO
def __init__(self, chat_id: Union[Integer, String],
video: String,
duration: Optional[Integer] = None,
width: Optional[Integer] = None,
height: Optional[Integer] = None,
caption: Optional[String] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param video: String - Video to send. Pass a file_id as String
to send a video that exists on the Telegram servers (recommended), pass an HTTP URL
as a String for Telegram to get a video from the Internet, or upload a new video
using multipart/form-data.
:param duration: Integer (Optional) - Duration of sent video in seconds
:param width: Integer (Optional) - Video width
:param height: Integer (Optional) - Video height
:param caption: String (Optional) - Video caption (may also be used when resending videos by file_id),
0-1024 characters after entities parsing
:param disable_notification: Boolean (Optional) - Sends the message silently.
Users will receive a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.video = video
self.duration = duration
self.width = width
self.height = height
self.caption = caption
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self):
return {
'chat_id': self.chat_id,
'video': self.video,
'duration': self.duration,
'width': self.width,
'height': self.height,
'caption': self.caption,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
class SendVoice(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send voice on to webhook.
"""
__slots__ = ('chat_id', 'voice', 'caption', 'duration', 'disable_notification',
'protect_content', 'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_VOICE
def __init__(self, chat_id: Union[Integer, String],
voice: String,
caption: Optional[String] = None,
duration: Optional[Integer] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param voice: String - Audio 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.
:param caption: String (Optional) - Voice message caption, 0-1024 characters after entities parsing
:param duration: Integer (Optional) - Duration of the voice message in seconds
:param disable_notification: Boolean (Optional) - Sends the message silently.
Users will receive a notification with no sound.
:param protect_content: Boolean (Optional) - Protects the contents of sent messages
from forwarding and saving
:param reply_to_message_id: Integer (Optional) - If the message is a reply, ID of the original message
:param reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String] (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.
"""
if protect_content is None:
protect_content = self._global_protect_content()
self.chat_id = chat_id
self.voice = voice
self.caption = caption
self.duration = duration
self.disable_notification = disable_notification
self.protect_content = protect_content
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
def prepare(self):
return {
'chat_id': self.chat_id,
'voice': self.voice,
'caption': self.caption,
'duration': self.duration,
'disable_notification': self.disable_notification,
'protect_content': self.protect_content,
'reply_to_message_id': self.reply_to_message_id,
'reply_markup': prepare_arg(self.reply_markup),
}
class SendVideoNote(BaseResponse, ReplyToMixin, DisableNotificationMixin, ProtectContentMixin):
"""
Use that response type for send video note on to webhook.
"""
__slots__ = ('chat_id', 'video_note', 'duration', 'length', 'disable_notification',
'protect_content', 'reply_to_message_id', 'reply_markup')
method = api.Methods.SEND_VIDEO_NOTE
def __init__(self, chat_id: Union[Integer, String],
video_note: String,
duration: Optional[Integer] = None,
length: Optional[Integer] = None,
disable_notification: Optional[Boolean] = None,
protect_content: Optional[Boolean] = None,
reply_to_message_id: Optional[Integer] = None,
reply_markup: Optional[Union[
types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, Dict, String]] = None):
"""
:param chat_id: Union[Integer, String] - Unique identifier for the target chat or username
of the target channel (in the format @channelusername)
:param video_note: String - 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. Sending video notes by a URL is currently unsupported