Debian Codegraph @

tests/test_plugin_telegram.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from inspect import cleandoc
29 from json import dumps, loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 import re
35 from unittest import mock
36
37 from helpers import AppriseURLTester
38 import pytest
39 import requests
40
41 from apprise import (
42 Apprise,
43 AppriseAsset,
44 AppriseAttachment,
45 NotifyFormat,
46 NotifyType,
47 )
48 from apprise.plugins.telegram import NotifyTelegram
49
50 logging.disable(logging.CRITICAL)
51
52 # Attachment Directory
53 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
54
55 # Our Testing URLs
56 apprise_url_tests = (
57 ##################################
58 # NotifyTelegram
59 ##################################
60 (
61 "tgram://",
62 {
63 "instance": None,
64 },
65 ),
66 # Simple Message
67 (
68 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
69 {
70 "instance": NotifyTelegram,
71 },
72 ),
73 # Simple Message (no images)
74 (
75 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
76 {
77 "instance": NotifyTelegram,
78 # don't include an image by default
79 "include_image": False,
80 },
81 ),
82 # Simple Message with multiple chat names
83 (
84 "tgram://123456789:abcdefg_hijklmnop/id1/id2/",
85 {
86 "instance": NotifyTelegram,
87 },
88 ),
89 # Simple Message with multiple chat names
90 (
91 "tgram://123456789:abcdefg_hijklmnop/?to=id1,id2",
92 {
93 "instance": NotifyTelegram,
94 },
95 ),
96 # Simple Message with an invalid chat ID
97 (
98 "tgram://123456789:abcdefg_hijklmnop/%$/",
99 {
100 "instance": NotifyTelegram,
101 # Notify will fail
102 "response": False,
103 },
104 ),
105 # Simple Message with multiple chat ids
106 (
107 "tgram://123456789:abcdefg_hijklmnop/id1/id2/23423/-30/",
108 {
109 "instance": NotifyTelegram,
110 },
111 ),
112 # Simple Message with multiple chat ids (no images)
113 (
114 "tgram://123456789:abcdefg_hijklmnop/id1/id2/23423/-30/",
115 {
116 "instance": NotifyTelegram,
117 # don't include an image by default
118 "include_image": False,
119 },
120 ),
121 # Support bot keyword prefix
122 (
123 "tgram://bottest@123456789:abcdefg_hijklmnop/lead2gold/",
124 {
125 "instance": NotifyTelegram,
126 },
127 ),
128 # Support Thread Topics
129 (
130 "tgram://bottest@123456789:abcdefg_hijklmnop/id1/?topic=12345",
131 {
132 "instance": NotifyTelegram,
133 },
134 ),
135 # Thread is just an alias of topic
136 (
137 "tgram://bottest@123456789:abcdefg_hijklmnop/id1/?thread=12345",
138 {
139 "instance": NotifyTelegram,
140 },
141 ),
142 # Threads must be numeric
143 (
144 "tgram://bottest@123456789:abcdefg_hijklmnop/id1/?topic=invalid",
145 {
146 "instance": TypeError,
147 },
148 ),
149 # content must be 'before' or 'after'
150 (
151 "tgram://bottest@123456789:abcdefg_hijklmnop/id1/?content=invalid",
152 {
153 "instance": TypeError,
154 },
155 ),
156 (
157 "tgram://bottest@123456789:abcdefg_hijklmnop/id1:invalid/?thread=12345",
158 {
159 "instance": NotifyTelegram,
160 # Notify will fail (bad target)
161 "response": False,
162 },
163 ),
164 # Testing image
165 (
166 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?image=Yes",
167 {
168 "instance": NotifyTelegram,
169 },
170 ),
171 # Testing invalid format (fall's back to html)
172 (
173 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=invalid",
174 {
175 "instance": NotifyTelegram,
176 },
177 ),
178 # Testing empty format (falls back to html)
179 (
180 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=",
181 {
182 "instance": NotifyTelegram,
183 },
184 ),
185 # Testing valid formats
186 (
187 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=markdown",
188 {
189 "instance": NotifyTelegram,
190 },
191 ),
192 (
193 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=markdown&mdv=v1",
194 {
195 "instance": NotifyTelegram,
196 },
197 ),
198 (
199 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=markdown&mdv=v2",
200 {
201 "instance": NotifyTelegram,
202 },
203 ),
204 (
205 "tgram://123456789:abcdefg_hijklmnop/l2g/?format=markdown&mdv=bad",
206 {
207 # Defaults to v2
208 "instance": NotifyTelegram,
209 },
210 ),
211 (
212 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=html",
213 {
214 "instance": NotifyTelegram,
215 },
216 ),
217 (
218 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?format=text",
219 {
220 "instance": NotifyTelegram,
221 },
222 ),
223 # Test Silent Settings
224 (
225 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?silent=yes",
226 {
227 "instance": NotifyTelegram,
228 },
229 ),
230 (
231 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?silent=no",
232 {
233 "instance": NotifyTelegram,
234 },
235 ),
236 # Test Web Page Preview Settings
237 (
238 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?preview=yes",
239 {
240 "instance": NotifyTelegram,
241 },
242 ),
243 (
244 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?preview=no",
245 {
246 "instance": NotifyTelegram,
247 },
248 ),
249 # Simple Message without image
250 (
251 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
252 {
253 "instance": NotifyTelegram,
254 # don't include an image by default
255 "include_image": False,
256 },
257 ),
258 # Invalid Bot Token
259 (
260 "tgram://alpha:abcdefg_hijklmnop/lead2gold/",
261 {
262 "instance": None,
263 },
264 ),
265 # AuthToken + bad url
266 (
267 "tgram://:@/",
268 {
269 "instance": None,
270 },
271 ),
272 (
273 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
274 {
275 "instance": NotifyTelegram,
276 # force a failure
277 "response": False,
278 "requests_response_code": requests.codes.internal_server_error,
279 },
280 ),
281 (
282 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?image=Yes",
283 {
284 "instance": NotifyTelegram,
285 # force a failure without an image specified
286 "include_image": False,
287 "response": False,
288 "requests_response_code": requests.codes.internal_server_error,
289 },
290 ),
291 (
292 "tgram://123456789:abcdefg_hijklmnop/id1/id2/",
293 {
294 "instance": NotifyTelegram,
295 # force a failure with multiple chat_ids
296 "response": False,
297 "requests_response_code": requests.codes.internal_server_error,
298 },
299 ),
300 (
301 "tgram://123456789:abcdefg_hijklmnop/id1/id2/",
302 {
303 "instance": NotifyTelegram,
304 # force a failure without an image specified
305 "include_image": False,
306 "response": False,
307 "requests_response_code": requests.codes.internal_server_error,
308 },
309 ),
310 (
311 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
312 {
313 "instance": NotifyTelegram,
314 # throw a bizarre code forcing us to fail to look it up
315 "response": False,
316 "requests_response_code": 999,
317 },
318 ),
319 (
320 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
321 {
322 "instance": NotifyTelegram,
323 # throw a bizarre code forcing us to fail to look it up without
324 # having an image included
325 "include_image": False,
326 "response": False,
327 "requests_response_code": 999,
328 },
329 ),
330 # Test with image set
331 (
332 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?image=Yes",
333 {
334 "instance": NotifyTelegram,
335 # throw a bizarre code forcing us to fail to look it up without
336 # having an image included
337 "include_image": True,
338 "response": False,
339 "requests_response_code": 999,
340 },
341 ),
342 (
343 "tgram://123456789:abcdefg_hijklmnop/lead2gold/",
344 {
345 "instance": NotifyTelegram,
346 # Throws a series of i/o exceptions with this flag
347 # is set and tests that we gracefully handle them
348 "test_requests_exceptions": True,
349 },
350 ),
351 (
352 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?image=Yes",
353 {
354 "instance": NotifyTelegram,
355 # Throws a series of i/o exceptions with this flag is set and
356 # tests that we gracefully handle them without images set
357 "include_image": True,
358 "test_requests_exceptions": True,
359 },
360 ),
361 )
362
363
364 def test_plugin_telegram_urls():
365 """NotifyTelegram() Apprise URLs."""
366
367 # Run our general tests
368 AppriseURLTester(tests=apprise_url_tests).run_all()
369
370
371 @mock.patch("requests.post")
372 def test_plugin_telegram_general(mock_post):
373 """NotifyTelegram() General Tests."""
374
375 # Bot Token
376 bot_token = "123456789:abcdefg_hijklmnop"
377 invalid_bot_token = "abcd:123"
378
379 # Chat ID
380 chat_ids = "l2g:1234, lead2gold"
381
382 # Prepare Mock
383 mock_post.return_value = requests.Request()
384 mock_post.return_value.status_code = requests.codes.ok
385 mock_post.return_value.content = "{}"
386
387 # Exception should be thrown about the fact no bot token was specified
388 with pytest.raises(TypeError):
389 NotifyTelegram(bot_token=None, targets=chat_ids)
390
391 # Invalid JSON while trying to detect bot owner
392 mock_post.return_value.content = "}"
393 obj = NotifyTelegram(bot_token=bot_token, targets=None)
394 obj.notify(title="hello", body="world")
395
396 # Invalid JSON while trying to detect bot owner + 400 error
397 mock_post.return_value.status_code = requests.codes.internal_server_error
398 obj = NotifyTelegram(bot_token=bot_token, targets=None)
399 obj.notify(title="hello", body="world")
400
401 # Return status back to how they were
402 mock_post.return_value.status_code = requests.codes.ok
403
404 # Exception should be thrown about the fact an invalid bot token was
405 # specifed
406 with pytest.raises(TypeError):
407 NotifyTelegram(bot_token=invalid_bot_token, targets=chat_ids)
408
409 obj = NotifyTelegram(
410 bot_token=bot_token, targets=chat_ids, include_image=True
411 )
412 assert isinstance(obj, NotifyTelegram) is True
413 assert len(obj.targets) == 2
414
415 # Test Image Sending Exceptions
416 mock_post.side_effect = OSError()
417 assert not obj.send_media(obj.targets[0], NotifyType.INFO)
418
419 # Test our other objects
420 mock_post.side_effect = requests.HTTPError
421 assert not obj.send_media(obj.targets[0], NotifyType.INFO)
422
423 # Restore their entries
424 mock_post.side_effect = None
425 mock_post.return_value.content = "{}"
426
427 # test url call
428 assert isinstance(obj.url(), str) is True
429
430 # test privacy version of url
431 assert isinstance(obj.url(privacy=True), str) is True
432 assert obj.url(privacy=True).startswith("tgram://1...p/") is True
433
434 # Test that we can load the string we generate back:
435 obj = NotifyTelegram(**NotifyTelegram.parse_url(obj.url()))
436 assert isinstance(obj, NotifyTelegram) is True
437
438 # Prepare Mock to fail
439 response = mock.Mock()
440 response.status_code = requests.codes.internal_server_error
441
442 # a error response
443 response.content = dumps(
444 {
445 "description": "test",
446 }
447 )
448 mock_post.return_value = response
449
450 # No image asset
451 nimg_obj = NotifyTelegram(bot_token=bot_token, targets=chat_ids)
452 nimg_obj.asset = AppriseAsset(image_path_mask=False, image_url_mask=False)
453
454 # Test that our default settings over-ride base settings since they are
455 # not the same as the one specified in the base; this check merely
456 # ensures our plugin inheritance is working properly
457 assert obj.body_maxlen == NotifyTelegram.body_maxlen
458
459 # This tests erroneous messages involving multiple chat ids
460 assert (
461 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
462 is False
463 )
464 assert (
465 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
466 is False
467 )
468 assert (
469 nimg_obj.notify(
470 body="body", title="title", notify_type=NotifyType.INFO
471 )
472 is False
473 )
474
475 # This tests erroneous messages involving a single chat id
476 obj = NotifyTelegram(bot_token=bot_token, targets="l2g")
477 nimg_obj = NotifyTelegram(bot_token=bot_token, targets="l2g")
478 nimg_obj.asset = AppriseAsset(image_path_mask=False, image_url_mask=False)
479
480 assert (
481 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
482 is False
483 )
484 assert (
485 nimg_obj.notify(
486 body="body", title="title", notify_type=NotifyType.INFO
487 )
488 is False
489 )
490
491 # Bot Token Detection
492 # Just to make it clear to people reading this code and trying to learn
493 # what is going on. Apprise tries to detect the bot owner if you don't
494 # specify a user to message. The idea is to just default to messaging
495 # the bot owner himself (it makes it easier for people). So we're testing
496 # the creating of a Telegram Notification without providing a chat ID.
497 # We're testing the error handling of this bot detection section of the
498 # code
499 mock_post.return_value.content = dumps(
500 {
501 "ok": True,
502 "result": [
503 {
504 "update_id": 645421319,
505 # Entry without `message` in it
506 },
507 {
508 # Entry without `from` in `message`
509 "update_id": 645421320,
510 "message": {
511 "message_id": 2,
512 "chat": {
513 "id": 532389719,
514 "first_name": "Chris",
515 "type": "private",
516 },
517 "date": 1519694394,
518 "text": "/start",
519 "entities": [
520 {
521 "offset": 0,
522 "length": 6,
523 "type": "bot_command",
524 }
525 ],
526 },
527 },
528 {
529 "update_id": 645421321,
530 "message": {
531 "message_id": 2,
532 "from": {
533 "id": 532389719,
534 "is_bot": False,
535 "first_name": "Chris",
536 "language_code": "en-US",
537 },
538 "chat": {
539 "id": 532389719,
540 "first_name": "Chris",
541 "type": "private",
542 },
543 "date": 1519694394,
544 "text": "/start",
545 "entities": [
546 {
547 "offset": 0,
548 "length": 6,
549 "type": "bot_command",
550 }
551 ],
552 },
553 },
554 ],
555 }
556 )
557 mock_post.return_value.status_code = requests.codes.ok
558
559 obj = NotifyTelegram(bot_token=bot_token, targets="12345")
560 assert len(obj.targets) == 1
561 assert obj.targets[0] == (12345, None)
562
563 # Test the escaping of characters since Telegram escapes stuff for us to
564 # which we need to consider
565 mock_post.reset_mock()
566 body = "<p>'\"This can't\t\r\nfail&nbsp;us\"'</p>"
567 assert (
568 obj.notify(
569 body=body, title="special characters", notify_type=NotifyType.INFO
570 )
571 is True
572 )
573 assert mock_post.call_count == 1
574 payload = loads(mock_post.call_args_list[0][1]["data"])
575
576 # Test our payload
577 assert (
578 payload["text"]
579 == "<b>special characters</b>\r\n'\"This can't\t\r\nfail us\"'\r\n"
580 )
581
582 for content in ("before", "after"):
583 # Test our content settings
584 obj = NotifyTelegram(
585 bot_token=bot_token, targets="12345", content=content
586 )
587 # Reset our mock
588 mock_post.reset_mock()
589 # Test sending attachments
590 attach = AppriseAttachment(
591 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
592 )
593 assert (
594 obj.notify(
595 body="body",
596 title="title",
597 notify_type=NotifyType.INFO,
598 attach=attach,
599 )
600 is True
601 )
602
603 # Test large messages
604 assert (
605 obj.notify(
606 body="a" * (obj.telegram_caption_maxlen + 1),
607 title="title",
608 notify_type=NotifyType.INFO,
609 attach=attach,
610 )
611 is True
612 )
613
614 # An invalid attachment will cause a failure
615 path = os.path.join(
616 TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg"
617 )
618 attach = AppriseAttachment(path)
619 assert (
620 obj.notify(
621 body="body",
622 title="title",
623 notify_type=NotifyType.INFO,
624 attach=path,
625 )
626 is False
627 )
628
629 # Test large messages
630 assert (
631 obj.notify(
632 body="a" * (obj.telegram_caption_maxlen + 1),
633 title="title",
634 notify_type=NotifyType.INFO,
635 attach=path,
636 )
637 is False
638 )
639
640 obj = NotifyTelegram(bot_token=bot_token, targets=None)
641 # No user detected; this happens after our firsst notification
642 assert len(obj.targets) == 0
643
644 assert obj.notify(title="hello", body="world") is True
645 assert len(obj.targets) == 1
646 assert obj.targets[0] == ("532389719", None)
647
648 # Do the test again, but without the expected (parsed response)
649 mock_post.return_value.content = dumps(
650 {
651 "ok": True,
652 "result": [],
653 }
654 )
655
656 # No user will be detected now
657 obj = NotifyTelegram(bot_token=bot_token, targets=None)
658 # No user detected; this happens after our firsst notification
659 assert len(obj.targets) == 0
660 assert obj.notify(title="hello", body="world") is False
661 assert len(obj.targets) == 0
662
663 # Do the test again, but with ok not set to True
664 mock_post.return_value.content = dumps(
665 {
666 "ok": False,
667 "result": [
668 {
669 "update_id": 645421321,
670 "message": {
671 "message_id": 2,
672 "from": {
673 "id": 532389719,
674 "is_bot": False,
675 "first_name": "Chris",
676 "language_code": "en-US",
677 },
678 "chat": {
679 "id": 532389719,
680 "first_name": "Chris",
681 "type": "private",
682 },
683 "date": 1519694394,
684 "text": "/start",
685 "entities": [
686 {
687 "offset": 0,
688 "length": 6,
689 "type": "bot_command",
690 }
691 ],
692 },
693 },
694 ],
695 }
696 )
697
698 # No user will be detected now
699 obj = NotifyTelegram(bot_token=bot_token, targets=None)
700 # No user detected; this happens after our firsst notification
701 assert len(obj.targets) == 0
702 assert obj.notify(title="hello", body="world") is False
703 assert len(obj.targets) == 0
704
705 # An edge case where no results were provided; this will probably never
706 # happen, but it helps with test coverage completeness
707 mock_post.return_value.content = dumps(
708 {
709 "ok": True,
710 }
711 )
712
713 # No user will be detected now
714 obj = NotifyTelegram(bot_token=bot_token, targets=None)
715 # No user detected; this happens after our firsst notification
716 assert len(obj.targets) == 0
717 assert obj.notify(title="hello", body="world") is False
718 assert len(obj.targets) == 0
719 # Detect the bot with a bad response
720 mock_post.return_value.content = dumps({})
721 obj.detect_bot_owner()
722
723 # Test our bot detection with a internal server error
724 mock_post.return_value.status_code = requests.codes.internal_server_error
725
726 # internal server error prevents notification from being sent
727 obj = NotifyTelegram(bot_token=bot_token, targets=None)
728 assert len(obj.targets) == 0
729 assert obj.notify(title="hello", body="world") is False
730 assert len(obj.targets) == 0
731
732 # Test our bot detection with an unmappable html error
733 mock_post.return_value.status_code = 999
734 NotifyTelegram(bot_token=bot_token, targets=None)
735 assert len(obj.targets) == 0
736 assert obj.notify(title="hello", body="world") is False
737 assert len(obj.targets) == 0
738
739 # Do it again but this time provide a failure message
740 mock_post.return_value.content = dumps({"description": "Failure Message"})
741 NotifyTelegram(bot_token=bot_token, targets=None)
742 assert len(obj.targets) == 0
743 assert obj.notify(title="hello", body="world") is False
744 assert len(obj.targets) == 0
745
746 # Do it again but this time provide a failure message and perform a
747 # notification without a bot detection by providing at least 1 chat id
748 obj = NotifyTelegram(bot_token=bot_token, targets=["@abcd"])
749 assert (
750 nimg_obj.notify(
751 body="body", title="title", notify_type=NotifyType.INFO
752 )
753 is False
754 )
755
756 # iterate over our exceptions and test them
757 mock_post.side_effect = requests.HTTPError
758
759 # No chat_ids specified
760 obj = NotifyTelegram(bot_token=bot_token, targets=None)
761 assert len(obj.targets) == 0
762 assert obj.notify(title="hello", body="world") is False
763 assert len(obj.targets) == 0
764
765 # Test Telegram Group
766 obj = Apprise.instantiate(
767 "tgram://123456789:ABCdefghijkl123456789opqyz/-123456789525"
768 )
769 assert isinstance(obj, NotifyTelegram)
770 assert len(obj.targets) == 1
771 assert (-123456789525, None) in obj.targets
772
773
774 @mock.patch("requests.post")
775 def test_plugin_telegram_formatting(mock_post):
776 """NotifyTelegram() formatting tests."""
777
778 # Prepare Mock
779 mock_post.return_value = requests.Request()
780 mock_post.return_value.status_code = requests.codes.ok
781 mock_post.return_value.content = "{}"
782
783 # Simple success response
784 mock_post.return_value.content = dumps(
785 {
786 "ok": True,
787 "result": [
788 {
789 "update_id": 645421321,
790 "message": {
791 "message_id": 2,
792 "from": {
793 "id": 532389719,
794 "is_bot": False,
795 "first_name": "Chris",
796 "language_code": "en-US",
797 },
798 "chat": {
799 "id": 532389719,
800 "first_name": "Chris",
801 "type": "private",
802 },
803 "date": 1519694394,
804 "text": "/start",
805 "entities": [
806 {
807 "offset": 0,
808 "length": 6,
809 "type": "bot_command",
810 }
811 ],
812 },
813 },
814 ],
815 }
816 )
817 mock_post.return_value.status_code = requests.codes.ok
818
819 results = NotifyTelegram.parse_url("tgram://123456789:abcdefg_hijklmnop/")
820
821 instance = NotifyTelegram(**results)
822 assert isinstance(instance, NotifyTelegram)
823
824 response = instance.send(title="title", body="body")
825 assert response is True
826 # 1 call to look up bot owner, and second for notification
827 assert mock_post.call_count == 2
828
829 assert (
830 mock_post.call_args_list[0][0][0]
831 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/getUpdates"
832 )
833 assert (
834 mock_post.call_args_list[1][0][0]
835 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/sendMessage"
836 )
837
838 # Reset our values
839 mock_post.reset_mock()
840
841 # Now test our HTML Conversion as TEXT)
842 aobj = Apprise()
843 aobj.add("tgram://123456789:abcdefg_hijklmnop/")
844 assert len(aobj) == 1
845
846 title = "🚨 Change detected for <i>Apprise Test Title</i>"
847 body = (
848 '<a href="http://localhost"><i>Apprise Body Title</i></a>'
849 ' had <a href="http://127.0.0.1">a change</a>'
850 )
851
852 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
853
854 # Test our calls
855 assert mock_post.call_count == 2
856
857 assert (
858 mock_post.call_args_list[0][0][0]
859 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/getUpdates"
860 )
861 assert (
862 mock_post.call_args_list[1][0][0]
863 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/sendMessage"
864 )
865
866 payload = loads(mock_post.call_args_list[1][1]["data"])
867
868 # Test that everything is escaped properly in a TEXT mode
869 assert (
870 payload["text"]
871 == "<b>🚨 Change detected for &lt;i&gt;Apprise Test Title&lt;/i&gt;"
872 '</b>\r\n&lt;a href="http://localhost"&gt;&lt;i&gt;'
873 "Apprise Body Title&lt;/i&gt;&lt;/a&gt; had &lt;"
874 'a href="http://127.0.0.1"&gt;a change&lt;/a&gt;'
875 )
876
877 # Reset our values
878 mock_post.reset_mock()
879
880 # Now test our HTML Conversion as TEXT)
881 aobj = Apprise()
882 aobj.add("tgram://123456789:abcdefg_hijklmnop/?format=html")
883 assert len(aobj) == 1
884
885 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.HTML)
886
887 # Test our calls
888 assert mock_post.call_count == 2
889
890 assert (
891 mock_post.call_args_list[0][0][0]
892 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/getUpdates"
893 )
894 assert (
895 mock_post.call_args_list[1][0][0]
896 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/sendMessage"
897 )
898
899 payload = loads(mock_post.call_args_list[1][1]["data"])
900
901 # Test that everything is escaped properly in a HTML mode
902 assert (
903 payload["text"]
904 == "<b>🚨 Change detected for <i>Apprise Test Title</i></b>\r\n"
905 '<a href="http://localhost"><i>Apprise Body Title</i></a> had '
906 '<a href="http://127.0.0.1">a change</a>'
907 )
908
909 # Reset our values
910 mock_post.reset_mock()
911
912 # Now test our MARKDOWN Handling
913 title = "# 🚨 Change detected for _Apprise Test Title_"
914 body = (
915 "_[Apprise Body Title](http://localhost)_"
916 " had [a change](http://127.0.0.1)"
917 )
918
919 aobj = Apprise()
920 aobj.add("tgram://123456789:abcdefg_hijklmnop/?format=markdown&mdv=2")
921 assert len(aobj) == 1
922
923 assert aobj.notify(
924 title=title, body=body, body_format=NotifyFormat.MARKDOWN
925 )
926
927 # Test our calls
928 assert mock_post.call_count == 2
929
930 assert (
931 mock_post.call_args_list[0][0][0]
932 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/getUpdates"
933 )
934 assert (
935 mock_post.call_args_list[1][0][0]
936 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/sendMessage"
937 )
938
939 payload = loads(mock_post.call_args_list[1][1]["data"])
940
941 # Test that everything is escaped properly in a HTML mode
942 assert (
943 payload["text"] == "# 🚨 Change detected for _Apprise Test Title_\r\n"
944 "_[Apprise Body Title](http://localhost)_ had "
945 "[a change](http://127.0.0.1)"
946 )
947
948 # Reset our values
949 mock_post.reset_mock()
950
951 # Now test our MARKDOWN Handling
952 title = "# 🚨 Change detected for _Apprise Test Title_"
953 body = (
954 "_[Apprise Body Title](http://localhost)_"
955 " had [a change](http://127.0.0.1)"
956 )
957
958 aobj = Apprise()
959 aobj.add("tgram://123456789:abcdefg_hijklmnop/?format=markdown&mdv=1")
960 assert len(aobj) == 1
961
962 assert aobj.notify(
963 title=title, body=body, body_format=NotifyFormat.MARKDOWN
964 )
965
966 # Test our calls
967 assert mock_post.call_count == 2
968
969 assert (
970 mock_post.call_args_list[0][0][0]
971 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/getUpdates"
972 )
973 assert (
974 mock_post.call_args_list[1][0][0]
975 == "https://api.telegram.org/bot123456789:abcdefg_hijklmnop/sendMessage"
976 )
977
978 payload = loads(mock_post.call_args_list[1][1]["data"])
979
980 # Test that everything is escaped properly in a HTML mode
981 assert (
982 payload["text"] == "# 🚨 Change detected for _Apprise Test Title_\r\n"
983 "_[Apprise Body Title](http://localhost)_ had "
984 "[a change](http://127.0.0.1)"
985 )
986
987 # Reset our values
988 mock_post.reset_mock()
989
990 # Upstream to use HTML but input specified as Markdown
991 aobj = Apprise()
992 aobj.add("tgram://987654321:abcdefg_hijklmnop/?format=html")
993 assert len(aobj) == 1
994
995 # Now test our MARKDOWN Handling
996 title = "# 🚨 Another Change detected for _Apprise Test Title_"
997 body = (
998 "_[Apprise Body Title](http://localhost)_"
999 " had [a change](http://127.0.0.2)"
1000 )
1001
1002 # HTML forced by the command line, but MARKDOWN specified as
1003 # upstream mode
1004 assert aobj.notify(
1005 title=title, body=body, body_format=NotifyFormat.MARKDOWN
1006 )
1007
1008 # Test our calls
1009 assert mock_post.call_count == 2
1010
1011 assert (
1012 mock_post.call_args_list[0][0][0]
1013 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/getUpdates"
1014 )
1015 assert (
1016 mock_post.call_args_list[1][0][0]
1017 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1018 )
1019
1020 payload = loads(mock_post.call_args_list[1][1]["data"])
1021
1022 # Test that everything is escaped properly in a HTML mode
1023 assert (
1024 payload["text"] == "<b>\r\n<b>🚨 Another Change detected for "
1025 "<i>Apprise Test Title</i></b>\r\n</b>\r\n<i>"
1026 '<a href="http://localhost">Apprise Body Title</a>'
1027 '</i> had <a href="http://127.0.0.2">a change</a>\r\n'
1028 )
1029
1030 # Now we'll test an edge case where a title was defined, but after
1031 # processing it, it was determiend there really wasn't anything there
1032 # at all at the end of the day.
1033
1034 # Reset our values
1035 mock_post.reset_mock()
1036
1037 # Upstream to use HTML but input specified as Markdown v1
1038 aobj = Apprise()
1039 aobj.add("tgram://987654321:abcdefg_hijklmnop/?format=markdown&mdv=1")
1040 assert len(aobj) == 1
1041
1042 # Now test our MARKDOWN Handling (no title defined... not really anyway)
1043 title = "# "
1044 body = (
1045 "_[Apprise Body Title](http://localhost)_"
1046 " had [a change](http://127.0.0.2)"
1047 )
1048
1049 # MARKDOWN forced by the command line, but TEXT specified as
1050 # upstream mode
1051 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1052
1053 # Test our calls
1054 assert mock_post.call_count == 2
1055
1056 assert (
1057 mock_post.call_args_list[0][0][0]
1058 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/getUpdates"
1059 )
1060 assert (
1061 mock_post.call_args_list[1][0][0]
1062 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1063 )
1064
1065 payload = loads(mock_post.call_args_list[1][1]["data"])
1066
1067 # Test that everything is escaped properly in a MARKDOWN mode
1068 assert payload["text"] == body
1069
1070 # Reset our values
1071 mock_post.reset_mock()
1072
1073 # Upstream to use HTML but input specified as Markdown v2
1074 aobj = Apprise()
1075 aobj.add("tgram://987654321:abcdefg_hijklmnop/?format=markdown&mdv=2")
1076 assert len(aobj) == 1
1077
1078 # MARKDOWN forced by the command line, but TEXT specified as
1079 # upstream mode
1080 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1081
1082 # Test our calls
1083 assert mock_post.call_count == 2
1084
1085 assert (
1086 mock_post.call_args_list[0][0][0]
1087 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/getUpdates"
1088 )
1089 assert (
1090 mock_post.call_args_list[1][0][0]
1091 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1092 )
1093
1094 payload = loads(mock_post.call_args_list[1][1]["data"])
1095
1096 # Test that everything is escaped properly in a MARKDOWN mode
1097 assert (
1098 payload["text"]
1099 == "\\_\\[Apprise Body Title\\]\\(http://localhost\\)\\_ had \\"
1100 "[a change\\]\\(http://127\\.0\\.0\\.2\\)"
1101 )
1102
1103 # Reset our values
1104 mock_post.reset_mock()
1105
1106 # Upstream to use HTML but input specified as Markdown v1
1107 aobj = Apprise()
1108 aobj.add("tgram://987654321:abcdefg_hijklmnop/?format=markdown&mdv=1")
1109 assert len(aobj) == 1
1110
1111 # Set an actual title this time
1112 title = "# A Great Title"
1113 body = (
1114 "_[Apprise Body Title](http://localhost)_"
1115 " had [a change](http://127.0.0.2)"
1116 )
1117
1118 # TEXT forced by the command line, but MARKDOWN specified as
1119 # upstream mode
1120 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1121
1122 # Test our calls
1123 assert mock_post.call_count == 2
1124
1125 assert (
1126 mock_post.call_args_list[0][0][0]
1127 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/getUpdates"
1128 )
1129 assert (
1130 mock_post.call_args_list[1][0][0]
1131 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1132 )
1133
1134 payload = loads(mock_post.call_args_list[1][1]["data"])
1135
1136 # Test that everything is escaped properly in a MARKDOWN mode
1137 assert (
1138 payload["text"] == "# A Great Title\n"
1139 "_[Apprise Body Title](http://localhost)_ had "
1140 "[a change](http://127.0.0.2)"
1141 )
1142
1143 # Reset our values
1144 mock_post.reset_mock()
1145
1146 # Upstream to use HTML but input specified as Markdown v2
1147 aobj = Apprise()
1148 aobj.add("tgram://987654321:abcdefg_hijklmnop/?format=markdown&mdv=2")
1149 assert len(aobj) == 1
1150
1151 # TEXT forced by the command line, but MARKDOWN specified as
1152 # upstream mode
1153 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1154
1155 # Test our calls
1156 assert mock_post.call_count == 2
1157
1158 assert (
1159 mock_post.call_args_list[0][0][0]
1160 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/getUpdates"
1161 )
1162 assert (
1163 mock_post.call_args_list[1][0][0]
1164 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1165 )
1166
1167 payload = loads(mock_post.call_args_list[1][1]["data"])
1168
1169 # Test that everything is escaped properly in a MARKDOWN mode
1170 assert (
1171 payload["text"] == "\\# A Great Title\n"
1172 "\\_\\[Apprise Body Title\\]\\(http://localhost\\)\\_ had "
1173 "\\[a change\\]\\(http://127\\.0\\.0\\.2\\)"
1174 )
1175
1176 # Reset our values
1177 mock_post.reset_mock()
1178
1179 # If input is markdown and output is v2, it is expected the user knows
1180 # what he is doing... no esaping takes place
1181 assert aobj.notify(
1182 title=title, body=body, body_format=NotifyFormat.MARKDOWN
1183 )
1184
1185 # Test our calls
1186 assert mock_post.call_count == 1
1187
1188 assert (
1189 mock_post.call_args_list[0][0][0]
1190 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1191 )
1192
1193 payload = loads(mock_post.call_args_list[0][1]["data"])
1194
1195 # No escaping in this circumstance
1196 assert (
1197 payload["text"] == "# A Great Title\r\n"
1198 "_[Apprise Body Title](http://localhost)_ had "
1199 "[a change](http://127.0.0.2)"
1200 )
1201
1202 # Reset our values
1203 mock_post.reset_mock()
1204
1205 # No body format specified at all... user definitely must know what
1206 # they are doing... still no escaping in this circumstance
1207 assert aobj.notify(title=title, body=body)
1208
1209 # Test our calls
1210 assert mock_post.call_count == 1
1211
1212 assert (
1213 mock_post.call_args_list[0][0][0]
1214 == "https://api.telegram.org/bot987654321:abcdefg_hijklmnop/sendMessage"
1215 )
1216
1217 payload = loads(mock_post.call_args_list[0][1]["data"])
1218
1219 # No escaping in this circumstance
1220 assert (
1221 payload["text"] == "# A Great Title\r\n"
1222 "_[Apprise Body Title](http://localhost)_ had "
1223 "[a change](http://127.0.0.2)"
1224 )
1225
1226 # Reset our values
1227 mock_post.reset_mock()
1228
1229 #
1230 # Now test that <br/> is correctly escaped
1231 #
1232 title = "Test Message Title"
1233 body = "Test Message Body <br/> ok</br>"
1234
1235 aobj = Apprise()
1236 aobj.add("tgram://1234:aaaaaaaaa/-1123456245134")
1237 assert len(aobj) == 1
1238
1239 assert aobj.notify(
1240 title=title, body=body, body_format=NotifyFormat.MARKDOWN
1241 )
1242
1243 # Test our calls
1244 assert mock_post.call_count == 1
1245
1246 assert (
1247 mock_post.call_args_list[0][0][0]
1248 == "https://api.telegram.org/bot1234:aaaaaaaaa/sendMessage"
1249 )
1250
1251 payload = loads(mock_post.call_args_list[0][1]["data"])
1252
1253 # Test that everything is escaped properly in a HTML mode
1254 assert (
1255 payload["text"]
1256 == "<b>Test Message Title\r\n</b>\r\nTest Message Body\r\nok\r\n"
1257 )
1258
1259 # Reset our values
1260 mock_post.reset_mock()
1261
1262 #
1263 # Now test that <br/> is correctly escaped as it would have been via the
1264 # CLI mode where the body_format is TEXT
1265 #
1266
1267 aobj = Apprise()
1268 aobj.add("tgram://1234:aaaaaaaaa/-1123456245134")
1269 assert len(aobj) == 1
1270
1271 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1272
1273 # Test our calls
1274 assert mock_post.call_count == 1
1275
1276 assert (
1277 mock_post.call_args_list[0][0][0]
1278 == "https://api.telegram.org/bot1234:aaaaaaaaa/sendMessage"
1279 )
1280
1281 payload = loads(mock_post.call_args_list[0][1]["data"])
1282
1283 # Test that everything is escaped properly in a HTML mode
1284 assert (
1285 payload["text"] == "<b>Test Message Title</b>\r\n"
1286 "Test Message Body &lt;br/&gt; ok&lt;/br&gt;"
1287 )
1288
1289 # Reset our values
1290 mock_post.reset_mock()
1291
1292 #
1293 # Now test that <br/> is correctly escaped if fed as HTML
1294 #
1295
1296 aobj = Apprise()
1297 aobj.add("tgram://1234:aaaaaaaaa/-1123456245134")
1298 assert len(aobj) == 1
1299
1300 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.HTML)
1301
1302 # Test our calls
1303 assert mock_post.call_count == 1
1304
1305 assert (
1306 mock_post.call_args_list[0][0][0]
1307 == "https://api.telegram.org/bot1234:aaaaaaaaa/sendMessage"
1308 )
1309
1310 payload = loads(mock_post.call_args_list[0][1]["data"])
1311
1312 # Test that everything is escaped properly in a HTML mode
1313 assert (
1314 payload["text"]
1315 == "<b>Test Message Title</b>\r\nTest Message Body\r\nok\r\n"
1316 )
1317
1318
1319 @mock.patch("requests.post")
1320 def test_plugin_telegram_html_formatting(mock_post):
1321 """NotifyTelegram() HTML Formatting."""
1322 # Prepare Mock
1323 mock_post.return_value = requests.Request()
1324 mock_post.return_value.status_code = requests.codes.ok
1325
1326 # Simple success response
1327 mock_post.return_value.content = dumps(
1328 {
1329 "ok": True,
1330 "result": [
1331 {
1332 "update_id": 645421321,
1333 "message": {
1334 "message_id": 2,
1335 "from": {
1336 "id": 532389719,
1337 "is_bot": False,
1338 "first_name": "Chris",
1339 "language_code": "en-US",
1340 },
1341 "chat": {
1342 "id": 532389719,
1343 "first_name": "Chris",
1344 "type": "private",
1345 },
1346 "date": 1519694394,
1347 "text": "/start",
1348 "entities": [
1349 {
1350 "offset": 0,
1351 "length": 6,
1352 "type": "bot_command",
1353 }
1354 ],
1355 },
1356 },
1357 ],
1358 }
1359 )
1360
1361 aobj = Apprise()
1362 aobj.add("tgram://123456789:abcdefg_hijklmnop/")
1363
1364 assert len(aobj) == 1
1365
1366 assert isinstance(aobj[0], NotifyTelegram)
1367
1368 # Test our HTML Conversion
1369 title = "<title>&apos;information&apos</title>"
1370 body = (
1371 "<em>&quot;This is in Italic&quot</em><br/>"
1372 "<h5>&emsp;&emspHeadings&nbsp;are dropped and"
1373 "&nbspconverted to bold</h5>"
1374 )
1375
1376 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.HTML)
1377
1378 # 1 call to look up bot owner, and second for notification
1379 assert mock_post.call_count == 2
1380
1381 payload = loads(mock_post.call_args_list[1][1]["data"])
1382
1383 # Test that everything is escaped properly in a HTML mode
1384 assert (
1385 payload["text"]
1386 == "<b>\r\n<b>'information'</b>\r\n</b>\r\n<i>\"This is in Italic\""
1387 "</i>\r\n<b> Headings are dropped and converted to bold</b>\r\n"
1388 )
1389
1390 mock_post.reset_mock()
1391
1392 assert aobj.notify(title=title, body=body, body_format=NotifyFormat.TEXT)
1393
1394 # owner has already been looked up, so only one call is made
1395 assert mock_post.call_count == 1
1396
1397 payload = loads(mock_post.call_args_list[0][1]["data"])
1398
1399 assert (
1400 payload["text"]
1401 == "<b>&lt;title&gt;&amp;apos;information&amp;apos&lt;/title&gt;</b>"
1402 "\r\n&lt;em&gt;&amp;quot;This is in Italic&amp;quot&lt;/em&gt;&lt;"
1403 "br/&gt;&lt;h5&gt;&amp;emsp;&amp;emspHeadings&amp;nbsp;are "
1404 "dropped and&amp;nbspconverted to bold&lt;/h5&gt;"
1405 )
1406
1407 # Lest test more complex HTML examples now
1408 mock_post.reset_mock()
1409
1410 test_file_01 = os.path.join(TEST_VAR_DIR, "01_test_example.html")
1411 with open(test_file_01) as html_file:
1412 assert aobj.notify(
1413 body=html_file.read(), body_format=NotifyFormat.HTML
1414 )
1415
1416 # owner has already been looked up, so only one call is made
1417 assert mock_post.call_count == 1
1418
1419 payload = loads(mock_post.call_args_list[0][1]["data"])
1420 assert (
1421 payload["text"]
1422 == "\r\n<b>Bootstrap 101 Template</b>\r\n<b>My Title</b>\r\n"
1423 "<b>Heading 1</b>\r\n-Bullet 1\r\n-Bullet 2\r\n-Bullet 3\r\n"
1424 "-Bullet 1\r\n-Bullet 2\r\n-Bullet 3\r\n<b>Heading 2</b>\r\n"
1425 "A div entry\r\nA div entry\r\n"
1426 "<pre><code class=\"language-python\">print('hello')</code></pre>\r\n"
1427 "<b>Heading 3</b>\r\n<b>Heading 4</b>\r\n<b>Heading 5</b>\r\n"
1428 "<b>Heading 6</b>\r\nA set of text\r\n"
1429 "Another line after the set of text\r\nMore text\r\nlabel"
1430 )
1431
1432
1433 @mock.patch("requests.post")
1434 def test_plugin_telegram_html_to_markdown_format(mock_post):
1435 """Test HTML delivery to Telegram Markdown targets."""
1436
1437 # Prepare Mock
1438 mock_post.return_value = requests.Request()
1439 mock_post.return_value.status_code = requests.codes.ok
1440 mock_post.return_value.content = dumps({"ok": True, "result": True})
1441
1442 # Simple HTML that our html_to_markdown converter handles
1443 body = "<b>hello</b> <i>world</i>"
1444
1445 # Markdown v1 gets the converted body in Telegram's own Markdown dialect
1446 # (single-asterisk bold, single-underscore italic).
1447 aobj = Apprise()
1448 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=1")
1449 assert len(aobj) == 1
1450
1451 assert aobj.notify(body=body, body_format=NotifyFormat.HTML)
1452
1453 assert mock_post.call_count == 1
1454 payload = loads(mock_post.call_args_list[0][1]["data"])
1455
1456 assert payload["parse_mode"] == "MARKDOWN"
1457 assert payload["text"] == "*hello* _world_"
1458
1459 mock_post.reset_mock()
1460
1461 # Markdown v2 gets the same dialect-correct delimiters, left unescaped so
1462 # Telegram still parses them as real formatting.
1463 aobj = Apprise()
1464 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1465 assert len(aobj) == 1
1466
1467 assert aobj.notify(body=body, body_format=NotifyFormat.HTML)
1468
1469 assert mock_post.call_count == 1
1470 payload = loads(mock_post.call_args_list[0][1]["data"])
1471
1472 assert payload["parse_mode"] == "MarkdownV2"
1473 assert payload["text"] == "*hello* _world_"
1474
1475 mock_post.reset_mock()
1476
1477 # Telegram escapes v2-only punctuation not covered by generic Markdown.
1478 aobj = Apprise()
1479 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1480 assert len(aobj) == 1
1481
1482 assert aobj.notify(
1483 body="<p>3:00 p.m. (sharp)! Don't be late - see you there.</p>",
1484 body_format=NotifyFormat.HTML,
1485 )
1486
1487 assert mock_post.call_count == 1
1488 payload = loads(mock_post.call_args_list[0][1]["data"])
1489
1490 assert payload["parse_mode"] == "MarkdownV2"
1491 assert payload["text"] == (
1492 r"3:00 p\.m\. \(sharp\)\! Don't be late \- see you there\."
1493 )
1494
1495 mock_post.reset_mock()
1496
1497 # Markdown v2 target, plain TEXT body
1498 aobj = Apprise()
1499 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1500 assert len(aobj) == 1
1501
1502 assert aobj.notify(
1503 body="Tag #1 and *not* bold", body_format=NotifyFormat.TEXT
1504 )
1505
1506 assert mock_post.call_count == 1
1507 payload = loads(mock_post.call_args_list[0][1]["data"])
1508
1509 assert payload["parse_mode"] == "MarkdownV2"
1510 assert payload["text"] == r"Tag \#1 and \*not\* bold"
1511
1512 mock_post.reset_mock()
1513
1514 # Markdown v2 target, no body_format specified
1515 aobj = Apprise()
1516 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1517 assert len(aobj) == 1
1518
1519 assert aobj.notify(body="**already** markdown #tag")
1520
1521 assert mock_post.call_count == 1
1522 payload = loads(mock_post.call_args_list[0][1]["data"])
1523
1524 assert payload["parse_mode"] == "MarkdownV2"
1525 assert payload["text"] == "**already** markdown #tag"
1526
1527 mock_post.reset_mock()
1528
1529 # A heading has no MarkdownV2 entity -- its '#' must be escaped (not left
1530 # bare), or Telegram rejects the entire message outright rather than just.
1531 aobj = Apprise()
1532 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1533 assert len(aobj) == 1
1534
1535 assert aobj.notify(
1536 body="<h1>Title</h1><p>body text</p>", body_format=NotifyFormat.HTML
1537 )
1538
1539 assert mock_post.call_count == 1
1540 payload = loads(mock_post.call_args_list[0][1]["data"])
1541
1542 assert payload["parse_mode"] == "MarkdownV2"
1543 assert payload["text"] == "\\# Title\n\nbody text"
1544
1545 mock_post.reset_mock()
1546
1547 # Convert CommonMark links to Telegram's bare-destination syntax.
1548 aobj = Apprise()
1549 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1550 assert len(aobj) == 1
1551
1552 assert aobj.notify(
1553 body='<a href="https://example.com/x">click</a>',
1554 body_format=NotifyFormat.HTML,
1555 )
1556
1557 assert mock_post.call_count == 1
1558 payload = loads(mock_post.call_args_list[0][1]["data"])
1559
1560 assert payload["parse_mode"] == "MarkdownV2"
1561 assert payload["text"] == "[click](https://example.com/x)"
1562
1563 mock_post.reset_mock()
1564
1565 # Lists and tables have no MarkdownV2 entity either -- their markers
1566 # need the same escaping as a heading's, for the same reason.
1567 aobj = Apprise()
1568 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1569 assert len(aobj) == 1
1570
1571 assert aobj.notify(
1572 body="<ul><li>one</li><li>two</li></ul>",
1573 body_format=NotifyFormat.HTML,
1574 )
1575
1576 assert mock_post.call_count == 1
1577 payload = loads(mock_post.call_args_list[0][1]["data"])
1578
1579 assert payload["parse_mode"] == "MarkdownV2"
1580 assert payload["text"] == "\\- one\n\\- two"
1581
1582 mock_post.reset_mock()
1583
1584 aobj = Apprise()
1585 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1586 assert len(aobj) == 1
1587
1588 assert aobj.notify(
1589 body="<table><tr><td>A</td><td>B</td></tr></table>",
1590 body_format=NotifyFormat.HTML,
1591 )
1592
1593 assert mock_post.call_count == 1
1594 payload = loads(mock_post.call_args_list[0][1]["data"])
1595
1596 assert payload["parse_mode"] == "MarkdownV2"
1597 assert payload["text"] == (
1598 "\\| A \\| B \\|\n\\| \\-\\-\\- \\| \\-\\-\\- \\|"
1599 )
1600
1601 mock_post.reset_mock()
1602
1603 # A code span's content is just as literal to Telegram as it is to
1604 # CommonMark -- the strict escape pass must not touch it.
1605 aobj = Apprise()
1606 aobj.add("tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=2")
1607 assert len(aobj) == 1
1608
1609 assert aobj.notify(
1610 body="<code>a.b-c|d</code>", body_format=NotifyFormat.HTML
1611 )
1612
1613 assert mock_post.call_count == 1
1614 payload = loads(mock_post.call_args_list[0][1]["data"])
1615
1616 assert payload["parse_mode"] == "MarkdownV2"
1617 assert payload["text"] == "`a.b-c|d`"
1618
1619
1620 @mock.patch("requests.post")
1621 def test_plugin_telegram_html_to_markdown_hardening(mock_post):
1622 """Test edge cases in the CommonMark-to-Telegram dialect adaptation."""
1623
1624 # Prepare Mock
1625 mock_post.return_value = requests.Request()
1626 mock_post.return_value.status_code = requests.codes.ok
1627 mock_post.return_value.content = dumps({"ok": True, "result": True})
1628
1629 def notify(body, mdv="2"):
1630 aobj = Apprise()
1631 aobj.add(
1632 "tgram://123456789:abcdefg_hijklmnop/12345"
1633 f"?format=markdown&mdv={mdv}"
1634 )
1635 assert len(aobj) == 1
1636 assert aobj.notify(body=body, body_format=NotifyFormat.HTML)
1637 payload = loads(mock_post.call_args_list[-1][1]["data"])
1638 mock_post.reset_mock()
1639 return payload["text"]
1640
1641 # A link destination containing a literal ')' or '\' must have those
1642 # escaped.
1643 assert notify('<a href="https://example.com/a(b)c">x</a>') == (
1644 "[x](https://example.com/a(b\\)c)"
1645 )
1646
1647 # A code span's content needs every '`'/'\' inside it escaped.
1648 assert notify("<code>a\\b</code>") == "`a\\\\b`"
1649 assert notify("<code>a`b</code>") == "`a\\`b`"
1650
1651 # Immediately-adjacent nested emphasis (no text between the outer and inner
1652 # tag's open) must stay correctly nested ("*_x_*"), not cross ("*_x*_").
1653 assert notify("<b><i>x</i></b>") == "*_x_*"
1654 assert notify("<i><b>x</b></i>") == "*_x_*"
1655
1656 # Legacy Markdown (v1) doesn't support nested entities at all.
1657 assert notify("<b>a <i>b</i> c</b>", mdv="1") == "*a b c*"
1658 assert notify("<b><i>x</i></b>", mdv="1") == "*x*"
1659
1660 # <i><b>x</b></i> and <b><i>x</i></b> both flatten to the identical
1661 # CommonMark "***x***" (html_to_markdown has no separating text to anchor
1662 assert notify("<i><b>x</b></i>", mdv="1") == "*x*"
1663
1664 # Legacy Markdown only recognizes a backslash escape in front of
1665 # '`'/'*'/'_'/'['.
1666 assert (
1667 notify("<p>#tag (test)! &lt;x&gt; ~wave~</p>", mdv="1")
1668 == "#tag (test)! <x> ~wave~"
1669 )
1670 assert (
1671 notify("<p>a[b]c *lit* _lit_ `lit`</p>", mdv="1")
1672 == "a\\[b\\]c \\*lit\\* \\_lit\\_ \\`lit\\`"
1673 )
1674
1675 # Non-adjacent nesting and sibling spans are unaffected.
1676 assert notify("<b>bold <i>italic</i> still bold</b>") == (
1677 "*bold _italic_ still bold*"
1678 )
1679 assert notify("<b>A</b><b>B</b>") == "*A**B*"
1680
1681 # A nested bold opening *while italic is already open, with real text in
1682 # between* (so the two opening delimiters aren't touching) is a completely.
1683 assert notify("<i>a <b>b</b> c</i>") == "_a *b* c_"
1684 assert notify("<i>a <b>b</b> c</i>", mdv="1") == "_a b c_"
1685
1686 # The reverse nesting (bold containing italic, separated by text) was
1687 # already correct, and must stay that way.
1688 assert notify("<b>a <i>b</i> c</b>") == "*a _b_ c*"
1689
1690 # A literal "\x01<digits>\x01"-shaped sequence in ordinary text must pass
1691 # through completely unaltered.
1692 assert notify("literal \x010\x01 text, no code or links at all") == (
1693 "literal \x010\x01 text, no code or links at all"
1694 )
1695
1696 # overflow=split can hand this method just one chunk of a longer body, with
1697 # a span that doesn't open or close until a different chunk entirely.
1698 aobj = Apprise()
1699 aobj.add(
1700 "tgram://123456789:abcdefg_hijklmnop/12345"
1701 "?format=markdown&mdv=2&overflow=split"
1702 )
1703 assert len(aobj) == 1
1704 assert aobj.notify(
1705 body="<b>" + ("x" * 4990) + "</b>", body_format=NotifyFormat.HTML
1706 )
1707 assert mock_post.call_count == 2
1708 texts = [loads(c[1]["data"])["text"] for c in mock_post.call_args_list]
1709
1710 # Each half is independently balanced -- an odd number of un-escaped
1711 # '*'/'_' in either one would mean Telegram still rejects it.
1712 for text in texts:
1713 assert text.count("*") % 2 == 0
1714 assert text.count("_") % 2 == 0
1715
1716 # A split at a bold close must not leave an empty entity.
1717 assert texts[1] == "x" * (len(texts[1]))
1718
1719 # The same overflow split can also land mid-code-span or mid-link.
1720 assert (
1721 NotifyTelegram._commonmark_to_telegram(
1722 "text ``unterminated", strict=True
1723 )
1724 == "text \\`\\`unterminated"
1725 )
1726 assert (
1727 NotifyTelegram._commonmark_to_telegram(
1728 "a](<https://incomplete no close", strict=True
1729 )
1730 == "a](\\<https://incomplete no close"
1731 )
1732
1733 # Empty adjacent entities collapse without affecting following text.
1734 assert NotifyTelegram._commonmark_to_telegram("****x") == "x"
1735
1736 # Cascade close that pops an open span whose delimiter was the LAST item
1737 # in the output buffer (empty entity) -- the delimiter is dropped.
1738 assert NotifyTelegram._commonmark_to_telegram("******") == ""
1739
1740 # Unclosed spans at the end of the V1 input are force-closed by the cleanup
1741 # loop.
1742 f1 = NotifyTelegram._commonmark_to_telegram
1743 assert f1("***italic text") == "*italic text*"
1744 assert f1("**text") == "*text*"
1745 # An unterminated open with no content at all collapses to nothing.
1746 assert f1("**") == ""
1747
1748 # A link destination containing a backslash-escaped '>' in V1 mode:
1749 # the scan skips escaped characters and still finds the '>)' terminator.
1750 assert (
1751 notify('<a href="https://example.com/x>y">click</a>', mdv="1")
1752 == r"[click](https://example.com/x\\>y)"
1753 )
1754
1755 # HTML body with a title in V1 mode: _build_send_calls merges the title
1756 # as a heading before dialect conversion (covers the title-merge branch).
1757 aobj_v1 = Apprise()
1758 aobj_v1.add(
1759 "tgram://123456789:abcdefg_hijklmnop/12345?format=markdown&mdv=1"
1760 )
1761 assert aobj_v1.notify(
1762 body="<b>hello</b>", title="My Title", body_format=NotifyFormat.HTML
1763 )
1764 payload = loads(mock_post.call_args_list[-1][1]["data"])
1765 assert payload["text"] == "# My Title\n*hello*"
1766 mock_post.reset_mock()
1767
1768 # Title that reduces to an empty string after stripping leading heading and
1769 # list characters (html_to_markdown converts " - " to "-").
1770 assert aobj_v1.notify(
1771 body="<b>hello</b>", title=" - ", body_format=NotifyFormat.HTML
1772 )
1773 payload = loads(mock_post.call_args_list[-1][1]["data"])
1774 assert payload["text"] == "*hello*"
1775 mock_post.reset_mock()
1776
1777
1778 @mock.patch("requests.post")
1779 def test_plugin_telegram_overflow_split_repair(mock_post):
1780 """Test that overflow=split can't break entity boundaries across
1781 messages: _build_send_calls() adapts the whole body to Telegram's
1782 dialect before splitting (not per-chunk after), and
1783 _repair_split_chunk() patches up whatever the split itself still cuts
1784 in half across two messages."""
1785
1786 # Prepare Mock
1787 mock_post.return_value = requests.Request()
1788 mock_post.return_value.status_code = requests.codes.ok
1789 mock_post.return_value.content = dumps({"ok": True, "result": True})
1790
1791 def notify_split(body):
1792 aobj = Apprise()
1793 aobj.add(
1794 "tgram://123456789:abcdefg_hijklmnop/12345"
1795 "?format=markdown&mdv=2&overflow=split"
1796 )
1797 assert len(aobj) == 1
1798 assert aobj.notify(body=body, body_format=NotifyFormat.HTML)
1799 texts = [loads(c[1]["data"])["text"] for c in mock_post.call_args_list]
1800 mock_post.reset_mock()
1801 return texts
1802
1803 # A bold span long enough to force a split, immediately followed by plain
1804 # text that was never part of it.
1805 texts = notify_split(
1806 "<b>" + ("x" * 4990) + "</b>" + "TAIL_SHOULD_NOT_BE_BOLD"
1807 )
1808 assert len(texts) == 2
1809 # The part that fit keeps its formatting...
1810 assert texts[0].startswith("*x")
1811 assert texts[0].endswith("x*")
1812 # ...but the unrelated trailing text does not become bold.
1813 assert "TAIL" in texts[1]
1814 assert not texts[1].startswith("*")
1815 for text in texts:
1816 assert text.count("*") % 2 == 0
1817 assert text.count("_") % 2 == 0
1818
1819 # A link long enough that its URL alone forces a split.
1820 url = "https://example.com/" + ("a" * 4990)
1821 texts = notify_split(f'<a href="{url}">click here</a>')
1822 assert len(texts) >= 2
1823 for text in texts:
1824 # Every chunk must be valid MarkdownV2: no unescaped reserved chars.
1825 assert not re.search(r"(?<!\\)[_*\[\]()~`>#+=|{}.!<-]", text)
1826
1827 # A <pre> block long enough to force a split.
1828 content = "line.with.dots-and-dashes_under " * 200
1829 texts = notify_split(f"<pre>{content}</pre>")
1830 assert len(texts) >= 2
1831 for text in texts:
1832 assert not re.search(r"(?<!\\)[_*\[\]()~`>#+=|{}.!<-]", text)
1833
1834 # A short message that never triggers a split at all is unaffected.
1835 texts = notify_split("<b>short</b> <i>text</i>")
1836 assert texts == ["*short* _text_"]
1837
1838 # A continuation chunk where the carried-over destination *does* close
1839 # within this same chunk (not needing yet another one), even with an.
1840 assert NotifyTelegram._repair_split_chunk(
1841 "a\\)b)more text\\.", True, {"in_link_dest": True}
1842 ) == ("a\\)b\\)more text\\.", {})
1843
1844 # A carried-over code span closing within this chunk, same idea.
1845 assert NotifyTelegram._repair_split_chunk(
1846 "code```more text\\.", True, {"in_code": 3}
1847 ) == ("codemore text\\.", {})
1848
1849 # A carried-over destination that doesn't end in *this* chunk either.
1850 assert NotifyTelegram._repair_split_chunk(
1851 "still no close here", True, {"in_link_dest": True}
1852 ) == ("still no close here", {"in_link_dest": True})
1853
1854 repair = NotifyTelegram._repair_split_chunk
1855
1856 # V1 (non-strict) with an unmatched backtick: the backtick run has no
1857 # closing partner, so the `if strict:` branch is NOT taken.
1858 assert repair("`code no close", False, {}) == ("`code no close", {})
1859
1860 # A pending close count for '*' in strict mode: the matching close
1861 # delimiter in this chunk is discarded (the open was already dropped).
1862 assert repair("*text", True, {"*": 1}) == ("text", {"*": 0})
1863
1864 # Same for '_'.
1865 assert repair("_text", True, {"_": 1}) == ("text", {"_": 0})
1866
1867 # Strict mode: '](url)' with NO matching '[' on the link stack escapes
1868 # the construct rather than emitting it verbatim.
1869 assert repair("](https://e.com)", True, {}) == (
1870 "\\]\\(https://e\\.com\\)",
1871 {},
1872 )
1873
1874 # Strict mode: '](url' with no closing ')' sets in_link_dest pending.
1875 assert repair("](https://e.com no-close", True, {}) == (
1876 "\\]\\(https://e\\.com no\\-close",
1877 {"in_link_dest": True},
1878 )
1879
1880 # Strict mode: opening and immediately closing the same delimiter with no
1881 # content in between -- the empty span is dropped from the output.
1882 assert repair("**", True, {}) == ("", {})
1883
1884 # Strict mode: a stray ']', '(', or ')' outside any complete link entity
1885 # is backslash-escaped rather than passed through verbatim.
1886 assert repair("]text", True, {}) == ("\\]text", {})
1887 assert repair("(text)", True, {}) == ("\\(text\\)", {})
1888
1889 # Strict mode: a dangling open at the end of the chunk with no content
1890 # after it is removed as an empty span (not propagated as pending).
1891 assert repair("text*", True, {}) == ("text", {})
1892
1893
1894 @mock.patch("requests.post")
1895 def test_plugin_telegram_threads(mock_post):
1896 """NotifyTelegram() Threads/Topics."""
1897 # Prepare Mock
1898 mock_post.return_value = requests.Request()
1899 mock_post.return_value.status_code = requests.codes.ok
1900
1901 # Simple success response
1902 mock_post.return_value.content = dumps(
1903 {
1904 "ok": True,
1905 "result": [
1906 {
1907 "update_id": 645421321,
1908 "message": {
1909 "message_id": 2,
1910 "from": {
1911 "id": 532389719,
1912 "is_bot": False,
1913 "first_name": "Chris",
1914 "language_code": "en-US",
1915 },
1916 "chat": {
1917 "id": 532389719,
1918 "first_name": "Chris",
1919 "type": "private",
1920 },
1921 "date": 1519694394,
1922 "text": "/start",
1923 "entities": [
1924 {
1925 "offset": 0,
1926 "length": 6,
1927 "type": "bot_command",
1928 }
1929 ],
1930 },
1931 },
1932 ],
1933 }
1934 )
1935
1936 aobj = Apprise()
1937 aobj.add("tgram://123456789:abcdefg_hijklmnop/?thread=1234")
1938
1939 assert len(aobj) == 1
1940
1941 assert isinstance(aobj[0], NotifyTelegram)
1942
1943 body = "my threaded message"
1944
1945 assert aobj.notify(body=body)
1946
1947 # 1 call to look up bot owner, and second for notification
1948 assert mock_post.call_count == 2
1949
1950 payload = loads(mock_post.call_args_list[1][1]["data"])
1951
1952 assert "message_thread_id" in payload
1953 assert payload["message_thread_id"] == 1234
1954
1955 mock_post.reset_mock()
1956
1957 aobj = Apprise()
1958 aobj.add("tgram://123456789:abcdefg_hijklmnop/?topic=1234")
1959
1960 assert len(aobj) == 1
1961
1962 assert isinstance(aobj[0], NotifyTelegram)
1963
1964 body = "my message"
1965
1966 assert aobj.notify(body=body)
1967
1968 # 1 call to look up bot owner, and second for notification
1969 assert mock_post.call_count == 2
1970
1971 payload = loads(mock_post.call_args_list[1][1]["data"])
1972
1973 assert "message_thread_id" in payload
1974 assert payload["message_thread_id"] == 1234
1975
1976 mock_post.reset_mock()
1977
1978 aobj = Apprise()
1979 aobj.add("tgram://123456789:abcdefg_hijklmnop/9876:1234/9876:1111")
1980
1981 assert len(aobj) == 1
1982
1983 assert isinstance(aobj[0], NotifyTelegram)
1984
1985 body = "my message"
1986
1987 assert aobj.notify(body=body)
1988
1989 # 1 call to look up bot owner, and second for notification
1990 assert mock_post.call_count == 2
1991
1992 payload = loads(mock_post.call_args_list[0][1]["data"])
1993
1994 assert "message_thread_id" in payload
1995 assert payload["message_thread_id"] == 1111
1996
1997 payload = loads(mock_post.call_args_list[1][1]["data"])
1998
1999 assert "message_thread_id" in payload
2000 assert payload["message_thread_id"] == 1234
2001
2002 mock_post.reset_mock()
2003
2004
2005 @mock.patch("requests.post")
2006 def test_plugin_telegram_markdown_v2(mock_post):
2007 """NotifyTelegram() MarkdownV2."""
2008 # Prepare Mock
2009 mock_post.return_value = requests.Request()
2010 mock_post.return_value.status_code = requests.codes.ok
2011
2012 # Simple success response
2013 mock_post.return_value.content = dumps(
2014 {
2015 "ok": True,
2016 "result": [
2017 {
2018 "update_id": 645421321,
2019 "message": {
2020 "message_id": 2,
2021 "from": {
2022 "id": 532389719,
2023 "is_bot": False,
2024 "first_name": "Chris",
2025 "language_code": "en-US",
2026 },
2027 "chat": {
2028 "id": 532389719,
2029 "first_name": "Chris",
2030 "type": "private",
2031 },
2032 "date": 1519694394,
2033 "text": "/start",
2034 "entities": [
2035 {
2036 "offset": 0,
2037 "length": 6,
2038 "type": "bot_command",
2039 }
2040 ],
2041 },
2042 },
2043 ],
2044 }
2045 )
2046
2047 aobj = Apprise()
2048 aobj.add("tgram://123456789:abcdefg_hijklmnop/?mdv=2&format=markdown")
2049 assert len(aobj) == 1
2050 assert isinstance(aobj[0], NotifyTelegram)
2051
2052 body = "# my message\r\n## more content\r\n\\# already escaped hashtag"
2053
2054 # Test with body format set to markdown
2055 assert aobj.notify(body=body, body_format=NotifyFormat.TEXT)
2056
2057 # 1 call to look up bot owner, and second for notification
2058 assert mock_post.call_count == 2
2059 payload = loads(mock_post.call_args_list[1][1]["data"])
2060
2061 # Our content is escapped properly
2062 assert (
2063 payload["text"] == "\\# my message\r\n"
2064 "\\#\\# more content\r\n\\# already escaped hashtag"
2065 )
2066
2067 mock_post.reset_mock()
2068
2069 # We'll iterate over all of the bad unsupported characters
2070 mdv2_unsupported = (
2071 "_",
2072 "*",
2073 "[",
2074 "]",
2075 "(",
2076 ")",
2077 "~",
2078 "`",
2079 ">",
2080 "#",
2081 "+",
2082 "=",
2083 "|",
2084 "{",
2085 "}",
2086 ".",
2087 "!",
2088 "-",
2089 )
2090
2091 for c in mdv2_unsupported:
2092 body = f"bad character: {c}, and already escapped \\{c}"
2093
2094 # Test with body format set to markdown
2095 assert aobj.notify(body=body, body_format=NotifyFormat.TEXT)
2096 assert mock_post.call_count == 1
2097 payload = loads(mock_post.call_args_list[0][1]["data"])
2098
2099 # Our content is escapped properly
2100 assert (
2101 payload["text"]
2102 == f"bad character: \\{c}, and already escapped \\{c}"
2103 )
2104
2105 mock_post.reset_mock()
2106
2107
2108 @mock.patch("requests.post")
2109 def test_plugin_telegram_attach_memory(mock_post):
2110 """Regression: AttachMemory must be sendable without OSError."""
2111 from apprise.attachment.memory import AttachMemory
2112
2113 response = mock.Mock()
2114 response.status_code = requests.codes.ok
2115 response.content = dumps({"ok": True, "result": True})
2116 mock_post.return_value = response
2117
2118 obj = NotifyTelegram(
2119 bot_token="123456789:abcdefg_hijklmnop", targets="12345"
2120 )
2121
2122 mem = AttachMemory(
2123 content=b"<html><body><h1>Test</h1></body></html>",
2124 name="test.html",
2125 mimetype="text/html",
2126 )
2127
2128 assert obj.notify(body="Test", attach=mem) is True
2129 assert mock_post.call_count >= 1
2130
2131
2132 @mock.patch("requests.post")
2133 def test_plugin_telegram_template_blocks(mock_post, tmpdir):
2134 """NotifyTelegram() - Rich Message template mode."""
2135 response = mock.Mock()
2136 response.status_code = requests.codes.ok
2137 response.content = dumps({"ok": True})
2138 mock_post.return_value = response
2139
2140 # Write a minimal Rich Message JSON template to disk
2141 template = tmpdir.join("blocks.json")
2142 template.write(
2143 cleandoc("""
2144 {
2145 "blocks": [
2146 {
2147 "type": "section_heading",
2148 "text": "{{app_title}}"
2149 },
2150 {
2151 "type": "paragraph",
2152 "text": "{{app_body}}"
2153 }
2154 ]
2155 }
2156 """)
2157 )
2158
2159 obj = Apprise.instantiate(
2160 "tgram://123456789:abcdefg_hijklmnop/lead2gold/"
2161 "?template={}&:mykey=myval".format(str(template))
2162 )
2163 assert isinstance(obj, NotifyTelegram)
2164
2165 # Verify tokens and template were parsed correctly
2166 assert "mykey" in obj.tokens
2167 assert obj.tokens["mykey"] == "myval"
2168 assert obj.template
2169
2170 assert (
2171 obj.notify(body="hello", title="world", notify_type=NotifyType.INFO)
2172 is True
2173 )
2174 assert mock_post.called is True
2175
2176 # Inspect the posted URL and payload
2177 posted_url = mock_post.call_args_list[0][0][0]
2178 assert posted_url.endswith("/sendRichMessage")
2179
2180 posted = loads(mock_post.call_args_list[0][1]["data"])
2181 assert posted["chat_id"] == "@lead2gold"
2182 assert "rich_message" in posted
2183 blocks = posted["rich_message"]["blocks"]
2184 assert any(b.get("type") == "section_heading" for b in blocks)
2185 assert any(b.get("type") == "paragraph" for b in blocks)
2186
2187 heading = next(b for b in blocks if b.get("type") == "section_heading")
2188 assert heading["text"] == "world"
2189 paragraph = next(b for b in blocks if b.get("type") == "paragraph")
2190 assert paragraph["text"] == "hello"
2191
2192
2193 @mock.patch("requests.post")
2194 def test_plugin_telegram_template_invalid_json(mock_post, tmpdir):
2195 """NotifyTelegram() - Rich Message template with invalid JSON fails."""
2196 response = mock.Mock()
2197 response.status_code = requests.codes.ok
2198 response.content = dumps({"ok": True})
2199 mock_post.return_value = response
2200
2201 template = tmpdir.join("bad.json")
2202 template.write("{ not valid json }")
2203
2204 obj = Apprise.instantiate(
2205 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2206 str(template)
2207 )
2208 )
2209 assert isinstance(obj, NotifyTelegram)
2210
2211 assert (
2212 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2213 )
2214 assert mock_post.called is False
2215
2216
2217 @mock.patch("requests.post")
2218 def test_plugin_telegram_template_blocks_not_list(mock_post, tmpdir):
2219 """NotifyTelegram() - 'blocks' missing/not-a-list/empty is rejected."""
2220 response = mock.Mock()
2221 response.status_code = requests.codes.ok
2222 response.content = dumps({"ok": True})
2223 mock_post.return_value = response
2224
2225 # 'blocks' key entirely missing
2226 template = tmpdir.join("missing_blocks.json")
2227 template.write('{"text": "no blocks here"}')
2228
2229 obj = Apprise.instantiate(
2230 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2231 str(template)
2232 )
2233 )
2234 assert isinstance(obj, NotifyTelegram)
2235 assert (
2236 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2237 )
2238 assert mock_post.called is False
2239
2240 # 'blocks' present but not a list
2241 template.write('{"blocks": "not-a-list"}')
2242 obj2 = Apprise.instantiate(
2243 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2244 str(template)
2245 )
2246 )
2247 assert isinstance(obj2, NotifyTelegram)
2248 assert (
2249 obj2.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2250 )
2251 assert mock_post.called is False
2252
2253 # Empty list is also rejected
2254 template.write('{"blocks": []}')
2255 obj3 = Apprise.instantiate(
2256 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2257 str(template)
2258 )
2259 )
2260 assert isinstance(obj3, NotifyTelegram)
2261 assert (
2262 obj3.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2263 )
2264 assert mock_post.called is False
2265
2266
2267 @mock.patch("requests.post")
2268 def test_plugin_telegram_template_block_missing_type(mock_post, tmpdir):
2269 """NotifyTelegram() - a block dict without 'type' is rejected."""
2270 response = mock.Mock()
2271 response.status_code = requests.codes.ok
2272 response.content = dumps({"ok": True})
2273 mock_post.return_value = response
2274
2275 template = tmpdir.join("no_type.json")
2276 template.write('{"blocks": [{"text": "hi"}]}')
2277
2278 obj = Apprise.instantiate(
2279 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2280 str(template)
2281 )
2282 )
2283 assert isinstance(obj, NotifyTelegram)
2284 assert (
2285 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2286 )
2287 assert mock_post.called is False
2288
2289
2290 @mock.patch("requests.post")
2291 def test_plugin_telegram_template_content_not_dict(mock_post, tmpdir):
2292 """NotifyTelegram() - template that parses to a JSON array is
2293 rejected."""
2294 response = mock.Mock()
2295 response.status_code = requests.codes.ok
2296 response.content = dumps({"ok": True})
2297 mock_post.return_value = response
2298
2299 template = tmpdir.join("array.json")
2300 template.write('[{"type": "paragraph"}]')
2301
2302 obj = Apprise.instantiate(
2303 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2304 str(template)
2305 )
2306 )
2307 assert isinstance(obj, NotifyTelegram)
2308 assert (
2309 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2310 )
2311 assert mock_post.called is False
2312
2313
2314 @mock.patch("requests.post")
2315 def test_plugin_telegram_template_block_not_dict(mock_post, tmpdir):
2316 """NotifyTelegram() - non-dict entry in blocks list is rejected."""
2317 response = mock.Mock()
2318 response.status_code = requests.codes.ok
2319 response.content = dumps({"ok": True})
2320 mock_post.return_value = response
2321
2322 template = tmpdir.join("bad_block.json")
2323 template.write('{"blocks": ["not-a-dict"]}')
2324
2325 obj = Apprise.instantiate(
2326 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2327 str(template)
2328 )
2329 )
2330 assert isinstance(obj, NotifyTelegram)
2331 assert (
2332 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2333 )
2334 assert mock_post.called is False
2335
2336
2337 @mock.patch("requests.post")
2338 def test_plugin_telegram_template_load_error(mock_post, tmpdir):
2339 """NotifyTelegram() - template OSError during read fails gracefully."""
2340 response = mock.Mock()
2341 response.status_code = requests.codes.ok
2342 response.content = dumps({"ok": True})
2343 mock_post.return_value = response
2344
2345 # Write an empty file so the attachment resolves but open() can be
2346 # mocked to fail
2347 template = tmpdir.join("empty.json")
2348 template.write("")
2349
2350 obj = Apprise.instantiate(
2351 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2352 str(template)
2353 )
2354 )
2355 assert isinstance(obj, NotifyTelegram)
2356
2357 with mock.patch("builtins.open", side_effect=OSError):
2358 assert (
2359 obj.notify(body="x", title="y", notify_type=NotifyType.INFO)
2360 is False
2361 )
2362 assert mock_post.called is False
2363
2364
2365 def test_plugin_telegram_template_bad_tokens():
2366 """NotifyTelegram() - invalid tokens type raises TypeError."""
2367 with pytest.raises(TypeError):
2368 NotifyTelegram(
2369 bot_token="123456789:abcdefg_hijklmnop",
2370 targets="lead2gold",
2371 tokens="not-a-dict",
2372 )
2373
2374
2375 def test_plugin_telegram_template_add_failure():
2376 """NotifyTelegram() - TypeError when AppriseAttachment.add() drops
2377 entry."""
2378 with mock.patch("apprise.plugins.telegram.AppriseAttachment") as mock_cls:
2379 inst = mock.MagicMock()
2380 inst.__len__ = mock.Mock(return_value=0)
2381 mock_cls.return_value = inst
2382
2383 with pytest.raises(TypeError):
2384 NotifyTelegram(
2385 bot_token="123456789:abcdefg_hijklmnop",
2386 targets="lead2gold",
2387 template="file:///some/template.json",
2388 )
2389
2390
2391 @mock.patch("requests.post")
2392 def test_plugin_telegram_template_inaccessible(mock_post, tmpdir):
2393 """NotifyTelegram() - template attachment that cannot be accessed
2394 fails."""
2395 response = mock.Mock()
2396 response.status_code = requests.codes.ok
2397 response.content = dumps({"ok": True})
2398 mock_post.return_value = response
2399
2400 # Point to a template file that does not exist
2401 missing = str(tmpdir.join("missing.json"))
2402
2403 obj = Apprise.instantiate(
2404 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2405 missing
2406 )
2407 )
2408 assert isinstance(obj, NotifyTelegram)
2409 assert (
2410 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2411 )
2412 assert mock_post.called is False
2413
2414
2415 @mock.patch("requests.post")
2416 def test_plugin_telegram_template_none_token_value(mock_post, tmpdir):
2417 """NotifyTelegram() - a None token value (e.g. app_image_url) is
2418 coerced to an empty string before JSON-escaping."""
2419 response = mock.Mock()
2420 response.status_code = requests.codes.ok
2421 response.content = dumps({"ok": True})
2422 mock_post.return_value = response
2423
2424 # Template references app_image_url which will be None when
2425 # include_image=False
2426 template = tmpdir.join("img.json")
2427 template.write(
2428 '{"blocks": [{"type": "paragraph",'
2429 ' "text": "{{app_body}} img={{app_image_url}}"}]}'
2430 )
2431
2432 obj = Apprise.instantiate(
2433 "tgram://123456789:abcdefg_hijklmnop/lead2gold/"
2434 "?image=no&template={}".format(str(template))
2435 )
2436 assert isinstance(obj, NotifyTelegram)
2437 assert (
2438 obj.notify(body="hi", title="y", notify_type=NotifyType.INFO) is True
2439 )
2440 posted = loads(mock_post.call_args_list[0][1]["data"])
2441 paragraph = posted["rich_message"]["blocks"][0]
2442 assert paragraph["text"] == "hi img="
2443
2444
2445 @mock.patch("requests.post")
2446 def test_plugin_telegram_template_url_roundtrip(mock_post, tmpdir):
2447 """NotifyTelegram() - template + tokens survive url()/parse_url()
2448 round-trip."""
2449 response = mock.Mock()
2450 response.status_code = requests.codes.ok
2451 response.content = dumps({"ok": True})
2452 mock_post.return_value = response
2453
2454 template = tmpdir.join("rt.json")
2455 template.write(
2456 cleandoc("""
2457 {
2458 "blocks": [
2459 {"type": "paragraph", "text": "{{app_body}}"}
2460 ]
2461 }
2462 """)
2463 )
2464
2465 obj1 = NotifyTelegram(
2466 bot_token="123456789:abcdefg_hijklmnop",
2467 targets="lead2gold",
2468 template=str(template),
2469 tokens={"key1": "val1", "key2": "val2"},
2470 )
2471
2472 url = obj1.url()
2473 result = NotifyTelegram.parse_url(url)
2474 assert result is not None
2475
2476 obj2 = NotifyTelegram(**result)
2477 assert isinstance(obj2, NotifyTelegram)
2478
2479 # Connection identity must be preserved
2480 assert obj1.url_identifier == obj2.url_identifier
2481
2482 # Tokens must survive the round-trip
2483 assert obj2.tokens.get("key1") == "val1"
2484 assert obj2.tokens.get("key2") == "val2"
2485
2486 # Template must be present after round-trip
2487 assert obj2.template
2488
2489
2490 @mock.patch("requests.post")
2491 def test_plugin_telegram_template_multi_target(mock_post, tmpdir):
2492 """NotifyTelegram() - Rich Message is POSTed once per target."""
2493 response = mock.Mock()
2494 response.status_code = requests.codes.ok
2495 response.content = dumps({"ok": True})
2496 mock_post.return_value = response
2497
2498 template = tmpdir.join("multi.json")
2499 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2500
2501 obj = Apprise.instantiate(
2502 "tgram://123456789:abcdefg_hijklmnop/12345/67890:55/"
2503 "?template={}".format(str(template))
2504 )
2505 assert isinstance(obj, NotifyTelegram)
2506 assert len(obj.targets) == 2
2507
2508 assert obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is True
2509 assert mock_post.call_count == 2
2510
2511 posted_1 = loads(mock_post.call_args_list[0][1]["data"])
2512 posted_2 = loads(mock_post.call_args_list[1][1]["data"])
2513 assert posted_1["chat_id"] == 12345
2514 assert "message_thread_id" not in posted_1
2515 assert posted_2["chat_id"] == 67890
2516 assert posted_2["message_thread_id"] == 55
2517
2518
2519 @mock.patch("requests.post")
2520 def test_plugin_telegram_template_with_attachment(mock_post, tmpdir):
2521 """NotifyTelegram() - attachments remain untouched in template mode,
2522 sent separately after the Rich Message."""
2523 response = mock.Mock()
2524 response.status_code = requests.codes.ok
2525 response.content = dumps({"ok": True})
2526 mock_post.return_value = response
2527
2528 template = tmpdir.join("attach.json")
2529 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2530
2531 obj = Apprise.instantiate(
2532 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2533 str(template)
2534 )
2535 )
2536 assert isinstance(obj, NotifyTelegram)
2537
2538 # Pass a raw (not pre-wrapped) attachment path; template mode must
2539 # still normalize it into an AppriseAttachment internally.
2540 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
2541
2542 assert obj.notify(body="hi", title="y", attach=path) is True
2543
2544 # First call is the Rich Message itself
2545 first_url = mock_post.call_args_list[0][0][0]
2546 assert first_url.endswith("/sendRichMessage")
2547
2548 # Second call is the attachment, sent via the normal send_media() path
2549 second_url = mock_post.call_args_list[1][0][0]
2550 assert not second_url.endswith("/sendRichMessage")
2551
2552
2553 @mock.patch("requests.post")
2554 def test_plugin_telegram_template_attachment_failure(mock_post, tmpdir):
2555 """NotifyTelegram() - a failed attachment send flags an overall
2556 failure in Rich Message mode."""
2557 response = mock.Mock()
2558 response.status_code = requests.codes.ok
2559 response.content = dumps({"ok": True})
2560 mock_post.return_value = response
2561
2562 template = tmpdir.join("attach_fail.json")
2563 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2564
2565 obj = Apprise.instantiate(
2566 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2567 str(template)
2568 )
2569 )
2570 assert isinstance(obj, NotifyTelegram)
2571
2572 # Point to an attachment that cannot be accessed
2573 attach = AppriseAttachment("file:///path/does/not/exist.gif")
2574
2575 assert obj.notify(body="hi", title="y", attach=attach) is False
2576
2577
2578 @mock.patch("requests.post")
2579 def test_plugin_telegram_template_preview_enabled(mock_post, tmpdir):
2580 """NotifyTelegram() - preview=yes omits link_preview_options."""
2581 response = mock.Mock()
2582 response.status_code = requests.codes.ok
2583 response.content = dumps({"ok": True})
2584 mock_post.return_value = response
2585
2586 template = tmpdir.join("preview.json")
2587 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2588
2589 obj = Apprise.instantiate(
2590 "tgram://123456789:abcdefg_hijklmnop/lead2gold/"
2591 "?preview=yes&template={}".format(str(template))
2592 )
2593 assert isinstance(obj, NotifyTelegram)
2594 assert obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is True
2595 posted = loads(mock_post.call_args_list[0][1]["data"])
2596 assert "link_preview_options" not in posted
2597
2598
2599 @mock.patch("requests.post")
2600 def test_plugin_telegram_template_http_error(mock_post, tmpdir):
2601 """NotifyTelegram() - Rich Message HTTP error is handled gracefully."""
2602 response = mock.Mock()
2603 response.status_code = requests.codes.internal_server_error
2604 response.content = dumps({"description": "failure"})
2605 mock_post.return_value = response
2606
2607 template = tmpdir.join("err.json")
2608 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2609
2610 obj = Apprise.instantiate(
2611 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2612 str(template)
2613 )
2614 )
2615 assert isinstance(obj, NotifyTelegram)
2616 assert (
2617 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2618 )
2619
2620 # Also cover the case where the error response body itself is not
2621 # parsable JSON (falls back to the generic HTTP status string)
2622 response.content = b"not-json"
2623 assert (
2624 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2625 )
2626
2627
2628 @mock.patch("requests.post")
2629 def test_plugin_telegram_template_request_exception(mock_post, tmpdir):
2630 """NotifyTelegram() - Rich Message RequestException is handled
2631 gracefully."""
2632 mock_post.side_effect = requests.RequestException()
2633
2634 template = tmpdir.join("exc.json")
2635 template.write('{"blocks": [{"type": "paragraph", "text": "hi"}]}')
2636
2637 obj = Apprise.instantiate(
2638 "tgram://123456789:abcdefg_hijklmnop/lead2gold/?template={}".format(
2639 str(template)
2640 )
2641 )
2642 assert isinstance(obj, NotifyTelegram)
2643 assert (
2644 obj.notify(body="x", title="y", notify_type=NotifyType.INFO) is False
2645 )