-
Notifications
You must be signed in to change notification settings - Fork 0
/
logs2tg.py
executable file
·163 lines (134 loc) · 4.53 KB
/
logs2tg.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
import asyncio
import traceback
import os
import typing
import html
import sys
import json
import re
async def main() -> None:
aggregator = Aggregator(await tg_sender(sys.argv[1]))
reader = await connect_stdin()
while True:
line = await reader.readline()
if not line:
break
sline = line.rstrip(b"\n").decode("utf-8", "ignore")
aggregator.notify(sline)
await aggregator.close()
Flusher = typing.Callable[[str], typing.Awaitable[None]]
async def tg_sender(chat: str) -> Flusher:
token = os.environ["TG_TOKEN"]
RE_TOPIC = re.compile(
r"""
https://t\.me/c/
(?P<chat_id> \d+ )
(?:
/
(?P<thread_id> \d+ )
)?
""",
re.VERBOSE,
)
if (m := RE_TOPIC.match(chat)) is None:
raise ValueError("Invalid chat URL")
chat_id = -1000000000000 - int(m.group("chat_id"))
if (topic_id := m.group("thread_id")) is not None:
topic_id = int(topic_id)
me = await call_tg(token, "getMe", {})
print(f"Logged in as {me['username']}")
chat_info = await call_tg(token, "getChat", {"chat_id": chat_id})
print(f"Chat: {chat_info['title']}")
async def send(text: str) -> None:
try:
await call_tg(
token,
"sendMessage",
{
"chat_id": chat_id,
"message_thread_id": topic_id,
"text": "<pre>" + html.escape(text) + "</pre>",
"parse_mode": "HTML",
},
)
except Exception:
traceback.print_exc()
return send
async def call_tg(token: str, method: str, data: dict[str, typing.Any]) -> typing.Any:
proc = await asyncio.create_subprocess_exec(
"curl",
f"https://api.telegram.org/bot{token}/{method}",
"-H",
"Content-Type: application/json",
"-d",
json.dumps(data),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdin=asyncio.subprocess.DEVNULL,
)
stdout, _ = await proc.communicate()
try:
resp = json.loads(stdout)
except json.JSONDecodeError:
raise ValueError("Invalid JSON response")
if not isinstance(resp, dict) or not resp.get("ok") or "result" not in resp:
raise ValueError(f"Telegram error: {resp.get('description')}")
return resp["result"]
class Aggregator:
MAX_MSG_LINES = 100
MAX_MSG_CHARS = 4000
MAX_QUEUE_LEN = 500
WAIT_SECONDS = 1
def __init__(self, flush: Flusher) -> None:
self._flush = flush
self._task: asyncio.Task[None] | None = None
self._queue = asyncio.Queue[str | None]()
self._skipped = 0
async def run(self) -> None:
start = asyncio.get_event_loop().time()
lines = list[str]()
lines_chars = 0
while True:
try:
wait = start + self.WAIT_SECONDS - asyncio.get_event_loop().time()
line = await asyncio.wait_for(self._queue.get(), timeout=wait)
except asyncio.TimeoutError:
await self._flush("\n".join(lines))
self._skipped = 0
self._task = None
return
if line is None:
line = f"[[{self._skipped} lines suppressed]]"
self._skipped = 0
if (
lines_chars + len(line) + 1 > self.MAX_MSG_CHARS
or len(lines) > self.MAX_MSG_LINES
):
await self._flush("\n".join(lines))
lines.clear()
lines_chars = 0
if len(lines) == 0:
start = asyncio.get_event_loop().time()
lines.append(line)
lines_chars += len(line) + 1
def notify(self, line: str) -> None:
if self._skipped:
self._skipped += 1
elif self._queue.qsize() >= self.MAX_QUEUE_LEN:
self._skipped = 1
self._queue.put_nowait(None)
else:
self._queue.put_nowait(line)
if self._task is None:
self._task = asyncio.create_task(self.run())
async def close(self) -> None:
if self._task is not None:
await self._task
async def connect_stdin() -> asyncio.StreamReader:
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await asyncio.get_event_loop().connect_read_pipe(lambda: protocol, sys.stdin)
return reader
if __name__ == "__main__":
asyncio.run(main())