forked from k2-fsa/icefall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TelegramStreamIO.py
76 lines (65 loc) · 2.27 KB
/
TelegramStreamIO.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
import logging
from configparser import ConfigParser
import requests
def escape_html(text: str):
"""
Escapes all html characters in text
:param str text:
:rtype: str
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">")
class TelegramStreamIO(logging.Handler):
API_ENDPOINT = "https://api.telegram.org"
MAX_MESSAGE_LEN = 4096
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s at %(funcName)s "
"(line %(lineno)s):\n\n%(message)s"
)
def __init__(self, tg_configfile: str):
super(TelegramStreamIO, self).__init__()
config = ConfigParser()
if not config.read(tg_configfile):
raise FileNotFoundError(
f"{tg_configfile} not found. " "Retry without --telegram-cred flag."
)
config = config["TELEGRAM"]
token = config["token"]
self.chat_id = config["chat_id"]
self.url = f"{self.API_ENDPOINT}/bot{token}/sendMessage"
@staticmethod
def setup_logger(params):
if not params.telegram_cred:
return
formatter = logging.Formatter(
f"{params.exp_dir.name} %(asctime)s \n%(message)s"
)
tg = TelegramStreamIO(params.telegram_cred)
tg.setLevel(logging.WARN)
tg.setFormatter(formatter)
logging.getLogger("").addHandler(tg)
def emit(self, record: logging.LogRecord):
"""
Emit a record.
Send the record to the Web server as a percent-encoded dictionary
"""
data = {
"chat_id": self.chat_id,
"text": self.format(self.mapLogRecord(record)),
"parse_mode": "HTML",
}
try:
requests.get(self.url, json=data)
# return response.json()
except Exception as e:
logging.error(f"Failed to send telegram message: {repr(e)}")
pass
def mapLogRecord(self, record):
"""
Default implementation of mapping the log record into a dict
that is sent as the CGI data. Overwrite in your class.
Contributed by Franz Glasner.
"""
for k, v in record.__dict__.items():
if isinstance(v, str):
setattr(record, k, escape_html(v))
return record