-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
87 lines (74 loc) · 2.42 KB
/
utils.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
import json
import datetime
import requests
import threading
import traceback
from constants import (
TELEGRAM_BOT_TOKEN,
TELEGRAM_CHAT_ID,
ALERT_LEVEL_ICON_MAPPING
)
def write_to_json(data, filename):
with open(filename, 'w') as json_file:
json.dump({"data": data}, json_file, indent=4)
def format_datetime(timestamp):
return datetime.datetime.utcfromtimestamp(timestamp).strftime(
'%Y-%m-%d %H:%M:%S')
def send_telegram_message(bot_token, chat_id, message):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {
'chat_id': chat_id,
'parse_mode': 'HTML',
'text': message,
}
try:
response = requests.post(url, json=payload, timeout=10)
if response.status_code == 200:
print("Message sent successfully!")
else:
print(f"Failed to send message. Status code: {response.status_code}")
except requests.RequestException as e:
print(f"Failed to send message: {e}")
def handle_error(error_message):
traceback_str = traceback.format_exc()
send_telegram_message(
TELEGRAM_BOT_TOKEN,
TELEGRAM_CHAT_ID,
f"[ERROR]:\n{error_message}.\n\n[TRACEBACK]\n {traceback_str}"
)
class CMThread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._exc = None
self._traceback = None
def run(self):
try:
if self._target:
self._target(*self._args, **self._kwargs)
except Exception as e:
self._traceback = traceback.format_exc()
self._exc = e
def get_exception(self):
if self._traceback and self._exc:
return f"[ERROR]\n{self._exc}\n\n[TRACEBACK]\n{self._traceback}"
def send_exceptions_to_tg(self):
exception = self.get_exception()
if exception:
send_telegram_message(
TELEGRAM_BOT_TOKEN,
TELEGRAM_CHAT_ID,
f"Error on thread.\n\n{exception}"
)
def send_alert(alert_rule, metric_label):
message = (
f"{ALERT_LEVEL_ICON_MAPPING[alert_rule.level]} {alert_rule.name}\n\n" +
f"{alert_rule.message}\n\n" +
f"alert_level={alert_rule.level}\n" +
f"metric_label={metric_label}\n"
)
print('message', message)
send_telegram_message(
TELEGRAM_BOT_TOKEN,
TELEGRAM_CHAT_ID,
message,
)