-
Notifications
You must be signed in to change notification settings - Fork 3
/
telegram_log_handler.py
29 lines (26 loc) · 1.02 KB
/
telegram_log_handler.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
import logging
import requests
import getpass
from datetime import datetime
class TelegramLogHandler(logging.Handler):
def __init__(self, bot_token, chat_id):
super().__init__()
self.bot_token = bot_token
self.chat_id = chat_id
self.username = getpass.getuser()
def emit(self, record):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = f"{timestamp} - {self.username} - {self.format(record)}"
self.send_telegram_message(log_entry)
def send_telegram_message(self, message):
url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
payload = {
"chat_id": self.chat_id,
"text": message
}
try :
response = requests.post(url, json=payload)
if response.status_code != 200:
print(f"Failed to send Telegram message. Error code: {response.status_code}")
except Exception as e:
print(f"Telegram request failed with exception :\n{e}")