-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpmlog.py
324 lines (298 loc) · 11.2 KB
/
pmlog.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
__version__ = (0, 1, 9)
# ▄▀█ █▄ █ █▀█ █▄ █ █▀█ ▀▀█ █▀█ █ █ █▀
# █▀█ █ ▀█ █▄█ █ ▀█ ▀▀█ █ ▀▀█ ▀▀█ ▄█
#
# © Copyright 2024
#
# developed by @anon97945
#
# https://t.me/apodiktum_modules
# https://github.com/anon97945
#
# 🔒 Licensed under the GNU GPLv3
# 🌐 https://www.gnu.org/licenses/gpl-3.0.html
# meta developer: @apodiktum_modules
# meta banner: https://t.me/apodiktum_dumpster/11
# meta pic: https://t.me/apodiktum_dumpster/13
# scope: hikka_only
# scope: hikka_min 1.3.3
import logging
from datetime import datetime
from io import BytesIO
from telethon.errors import MessageIdInvalidError
from telethon.tl.types import Message, User
from telethon.tl.functions.messages import (
ReadDiscussionRequest,
)
from telethon.tl.functions.channels import (
GetForumTopicsRequest,
CreateForumTopicRequest,
ToggleForumRequest,
EditForumTopicRequest,
)
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class ApodiktumPMLogMod(loader.Module):
"""
Logs PMs to a group/channel
"""
strings = {
"name": "Apo-PMLog",
"developer": "@anon97945",
"_cfg_bots": "Whether to log bots or not.",
"_cfg_loglist": "Add telegram id's to log them.",
"_cfg_selfdestructive": (
"Whether selfdestructive media should be logged or not. This"
" violates TG TOS!"
),
"_cfg_whitelist": (
"Whether the list is a for excluded(True) or included(False) chats."
),
"_cfg_reatime_usernames": "Whether to update the topic names in realtime or not.",
"_cfg_mark_read": "Whether to mark the messsages in the log as read or not.",
"_cfg_cst_auto_migrate": "Wheather to auto migrate defined changes on startup.",
}
strings_en = {}
strings_de = {
"_cfg_bots": "Ob Bots geloggt werden sollen oder nicht.",
"_cfg_loglist": "Fügen Sie Telegram-IDs hinzu, um sie zu protokollieren.",
"_cfg_selfdestructive": (
"Ob selbstzerstörende Medien geloggt werden sollen oder nicht. Dies"
" verstößt gegen die TG TOS!"
),
"_cfg_whitelist": (
"Ob die Liste für ausgeschlossene (Wahr) oder eingeschlossene"
" (Falsch) Chats ist."
),
"_cmd_doc_cpmlog": "Dadurch wird die Konfiguration für das Modul geöffnet.",
}
strings_ru = {
"_cfg_bots": "Логировать ли ботов или нет",
"_cfg_loglist": "Добавьте айди Telegram, чтобы зарегистрировать их",
"_cfg_selfdestructive": (
"Должны ли самоуничтожающиеся медиафайлы регистрироваться или нет."
" Это нарушает «Условия использования Telegram» (ToS)"
),
"_cfg_whitelist": "Использовать белый список (True) или черный (False).",
"_cmd_doc_cpmlog": "Это откроет конфиг для модуля.",
}
all_strings = {
"strings": strings,
"strings_en": strings,
"strings_de": strings_de,
"strings_ru": strings_ru,
}
changes = {
"migration1": {
"name": {
"old": "Apo PMLogger",
"new": "Apo-PMLog",
},
},
}
def __init__(self):
self._ratelimit = []
self.config = loader.ModuleConfig(
loader.ConfigValue(
"log_bots",
False,
doc=lambda: self.strings("_cfg_bots"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"log_list",
[777000],
doc=lambda: self.strings("_cfg_loglist"),
validator=loader.validators.Series(
validator=loader.validators.TelegramID()
),
),
loader.ConfigValue(
"log_self_destr",
False,
doc=lambda: self.strings("_cfg_selfdestructive"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"realtime_names",
True,
doc=lambda: self.strings("_cfg_reatime_usernames"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"whitelist",
True,
doc=lambda: self.strings("_cfg_whitelist"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"mark_read",
True,
doc=lambda: self.strings("_cfg_mark_read"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"auto_migrate",
True,
doc=lambda: self.strings("_cfg_cst_auto_migrate"),
validator=loader.validators.Boolean(),
), # for MigratorClass
)
async def client_ready(self):
self.apo_lib = await self.import_lib(
"https://raw.githubusercontent.com/anon97945/hikka-libs/master/apodiktum_library.py",
suspend_on_error=True,
)
await self.apo_lib.migrator.auto_migrate_handler(
self.__class__.__name__,
self.strings("name"),
self.changes,
self.config["auto_migrate"],
)
self.apo_lib.watcher_q.register(self.__class__.__name__)
self._topic_cache = {}
self.c, _ = await utils.asset_channel(
self._client,
"[Apo] PMLog",
"Chat for logged PMs. The ID's in the topic titles are the user ID's, don't remove them!",
silent=True,
invite_bot=False,
)
if not self.c.forum:
await self._client(ToggleForumRequest(self.c.id, True))
async def on_unload(self):
self.apo_lib.watcher_q.unregister(self.__class__.__name__)
async def cpmlogcmd(self, message: Message):
"""
This will open the config for the module.
"""
name = self.strings("name")
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config {name}")
)
async def _topic_cacher(self, user: User):
if user.id not in self._topic_cache:
forum = await self._client(
GetForumTopicsRequest(
channel=self.c.id,
offset_date=datetime.now(),
offset_id=0,
offset_topic=0,
limit=0,
)
)
for topic in forum.topics:
if str(user.id) in topic.title:
self._topic_cache[user.id] = topic
break
return user.id in self._topic_cache
async def _topic_creator(self, user: User):
await self._client(
CreateForumTopicRequest(
channel=self.c.id,
title=f"{user.first_name} ({user.id})",
icon_color=42,
)
)
return await self._topic_cacher(user)
async def _topic_handler(self, user: User, message: Message):
if not await self._topic_cacher(user): # create topic if not exists
await self._topic_creator(user)
if (
self.config["realtime_names"]
and self._topic_cache[user.id].title != f"{user.first_name} ({user.id})"
):
await self._client(
EditForumTopicRequest(
channel=self.c.id,
topic_id=self._topic_cache[user.id].id,
title=f"{user.first_name} ({user.id})",
)
)
self._topic_cache[user.id].title = f"{user.first_name} ({user.id})"
await message.client.send_message(
self.c.id,
f"New name:\n<code>{user.first_name} ({user.id})</code>\n\nOld name:\n<code>{self._topic_cache[user.id].title}</code>",
reply_to=self._topic_cache[user.id].id,
)
return True
async def q_watcher(self, message: Message):
try:
await self._queue_handler(message)
except Exception as exc: # skipcq: PYL-W0703
if "topic was deleted" in str(exc):
self._topic_cache.pop(utils.get_chat_id(message))
await self._queue_handler(message)
return
async def _queue_handler(self, message: Message):
if not isinstance(message, Message) or not message.is_private:
return
user = await message.get_sender()
if user.id == self.tg_id:
user = await message.get_chat()
if user.bot and not self.config["log_bots"] or user.id == self.tg_id:
return
chatidindb = utils.get_chat_id(message) in (self.config["log_list"] or [])
if (
self.config["whitelist"]
and chatidindb
or not self.config["whitelist"]
and not chatidindb
):
return
try:
if await self._topic_handler(user, message):
msg = await message.forward_to(
self.c.id, top_msg_id=self._topic_cache[user.id].id
)
if self.config["mark_read"]:
await self._client(
ReadDiscussionRequest(
self.c.id,
getattr(
getattr(msg, "reply_to", None),
"reply_to_top_id",
None,
)
or getattr(
getattr(msg, "reply_to", None),
"reply_to_msg_id",
None,
),
2**31 - 1,
)
)
except MessageIdInvalidError:
if not message.file or not self.config["log_self_destr"]:
return
file = BytesIO()
caption = f"{utils.escape_html(message.text)}"
await self._client.download_file(message, file)
file.name = (
message.file.name or f"{message.file.media.id}{message.file.ext}"
)
file.seek(0)
msg = await self._client.send_file(
self.c.id,
file,
force_document=True,
caption=caption,
reply_to=self._topic_cache[user.id].id,
)
await self._client(
ReadDiscussionRequest(
self.c.id,
getattr(
getattr(msg, "reply_to", None),
"reply_to_top_id",
None,
)
or getattr(
getattr(msg, "reply_to", None),
"reply_to_msg_id",
None,
),
2**31 - 1,
)
)