-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.py
69 lines (53 loc) · 1.77 KB
/
telegram.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
import settings
from monitors.base import MonitorException
from utils import requests_retry_session
def send_telegram_message(*, message: str):
"""Send a Telegram message.
Note: As the message allows for Markdown formatting, the message body must be correctly escaped,
or the message will not be sent.
Args:
message (str): Message body.
"""
url = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_BOT_TOKEN
data = {"chat_id": settings.TELEGRAM_CHANNEL, "text": message, "parse_mode": "MarkdownV2"}
res = requests_retry_session().post(url, json=data)
try:
res.raise_for_status()
except Exception:
print(res.text)
raise
def notify_monitor_exception(*, monitor_name: str, exception: MonitorException):
"""Send Telegram message about a failed monitor.
Args:
monitor_name (str): Failed monitor's name
exception (MonitorException): Exception instance
"""
# We must escape reserved Markdown characters
message = (
f"""
*{monitor_name}*
{exception}
""".replace(
"!", "\\!"
)
.replace("-", "\\-")
.replace(".", "\\.")
.replace("|", "\\|")
.replace("(", "\\(")
.replace(")", "\\)")
)
# Split message in 4096 characters size chunks
chunk_size = 4096
chunks = [message[i : i + chunk_size] for i in range(0, len(message), chunk_size)]
for chunk in chunks:
send_telegram_message(message=chunk)
def notify_exception(*, exception: Exception):
"""Send Telegram message about an encountered exception.
Args:
exception (Exception): Exception instance
"""
message = f"""
Encountered exception:
{exception}
"""
send_telegram_message(message=message)