-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmsg_merger.py
596 lines (557 loc) · 21.1 KB
/
msg_merger.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
__version__ = (0, 1, 23)
# ▄▀█ █▄ █ █▀█ █▄ █ █▀█ ▀▀█ █▀█ █ █ █▀
# █▀█ █ ▀█ █▄█ █ ▀█ ▀▀█ █ ▀▀█ ▀▀█ ▄█
#
# © 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.6.1
import contextlib
import logging
from datetime import datetime, timezone
from telethon.errors import MessageIdInvalidError
from telethon.tl.types import Message
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class ApodiktumMsgMergerMod(loader.Module):
"""
This module will merge own messages, if there is no message in between.
"""
strings = {
"name": "Apo-MsgMerger",
"developer": "@anon97945",
"_cfg_active": "Whether the module is turned on (or not).",
"_cfg_blacklist_chats": "The list of chats that the module will watch(or not).",
"_cfg_cst_auto_migrate": "Wheather to auto migrate defined changes on startup.",
"_cfg_new_line_prefix": "The prefix which will be added to the new line.",
"_cfg_edit_timeout": (
"The maximum time in minuted to edit the message. 0 for no limit."
),
"_cfg_ignore_prefix": "The prefix to ignore the merging fully.",
"_cfg_link_preview": (
"Whether to send webpage previews.\nLeave empty to use"
" automatically decide based on the messages to merge."
),
"_cfg_merge_own_reply": "Whether to merge any message from own reply.",
"_cfg_merge_own_reply_msg": (
"The message which will stay if the message is merged from own reply."
),
"_cfg_merge_urls": "Whether to merge messages with URLs.",
"_cfg_new_lines": "The number of new lines to add to the message.",
"_cfg_reverse_merge": (
"Whether to merge into the new(True) or old(False) message."
),
"_cfg_skip_emoji": "Whether to skip the merging of messages with single emoji.",
"_cfg_skip_reactions": (
"Whether to skip the merging of messages with reactions."
),
"_cfg_skip_length": "The length of the message to skip the merging.",
"_cfg_skip_prefix": "The prefix to skip the merging.",
"_cfg_skip_reply": "Whether to skip the merging of messages with reply.",
"_cfg_whitelist": (
"Whether the chatlist includes(True) or excludes(False) the chat."
),
"undo_merge_fail": "<b>Failed to unmerge the messages.</b>",
"nothing_to_merge": "<b>Nothing to merge.</b>",
}
strings_en = {}
strings_de = {}
strings_ru = {}
all_strings = {
"strings": strings,
"strings_en": strings,
"strings_de": strings_de,
"strings_ru": strings_ru,
}
changes = {
"migration1": {
"name": {
"old": "Apo MsgMerger",
"new": "Apo-MsgMerger",
},
},
}
def __init__(self):
self._ratelimit = []
self.merged_msgs = {}
self.config = loader.ModuleConfig(
loader.ConfigValue(
"active",
True,
doc=lambda: self.strings("_cfg_active"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"chatlist",
doc=lambda: self.strings("_cfg_blacklist_chats"),
validator=loader.validators.Series(loader.validators.TelegramID()),
),
loader.ConfigValue(
"edit_timeout",
2,
doc=lambda: self.strings("_cfg_edit_timeout"),
validator=loader.validators.Union(
loader.validators.Integer(minimum=1),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"ignore_prefix",
["+"],
doc=lambda: self.strings("_cfg_ignore_prefix"),
validator=loader.validators.Series(
loader.validators.Union(
loader.validators.String(length=1),
loader.validators.NoneType(),
),
),
),
loader.ConfigValue(
"link_preview",
doc=lambda: self.strings("_cfg_link_preview"),
validator=loader.validators.Union(
loader.validators.Boolean(),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"merge_own_reply",
False,
doc=lambda: self.strings("_cfg_merge_own_reply"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"merge_urls",
True,
doc=lambda: self.strings("_cfg_merge_urls"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"new_line_pref",
">",
doc=lambda: self.strings("_cfg_new_line_prefix"),
validator=loader.validators.Union(
loader.validators.String(length=1),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"new_lines",
1,
doc=lambda: self.strings("_cfg_new_lines"),
validator=loader.validators.Integer(minimum=1, maximum=2),
),
loader.ConfigValue(
"own_reply_msg",
"<code>☝️</code>",
doc=lambda: self.strings("_cfg_merge_own_reply_msg"),
validator=loader.validators.Union(
loader.validators.String(),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"reverse_merge",
True,
doc=lambda: self.strings("_cfg_reverse_merge"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"skip_emoji",
True,
doc=lambda: self.strings("_cfg_skip_emoji"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"skip_length",
doc=lambda: self.strings("_cfg_skip_length"),
validator=loader.validators.Union(
loader.validators.Integer(minimum=0),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"skip_prefix",
[">"],
doc=lambda: self.strings("_cfg_skip_prefix"),
validator=loader.validators.Series(
loader.validators.Union(
loader.validators.String(length=1),
loader.validators.NoneType(),
),
),
),
loader.ConfigValue(
"skip_reactions",
True,
doc=lambda: self.strings("_cfg_skip_reactions"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"skip_reply",
False,
doc=lambda: self.strings("_cfg_skip_reply"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"whitelist",
False,
doc=lambda: self.strings("_cfg_whitelist"),
validator=loader.validators.Boolean(),
),
)
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__)
async def on_unload(self):
self.apo_lib.watcher_q.unregister(self.__class__.__name__)
async def cmsgmergercmd(self, message: Message):
"""
open the config of the module.
"""
name = self.strings("name")
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config {name}")
)
async def mergecmd(self, message: Message):
"""
merge all messages of own until the last message of another user.
"""
chat_id = utils.get_chat_id(message)
text = ""
del_msgs = []
merge_msgs = []
try:
msgs = await self._client.get_messages(chat_id, limit=100)
for i in range(-len(msgs), -1):
if (
not isinstance(msgs[i], Message)
or not msgs[i].out
or msgs[i].forward
or msgs[i].via_bot
or msgs[i].sender_id != self.tg_id
or (self.config["skip_reactions"] and msgs[i].reactions)
or (msgs[i].media and not getattr(msgs[i].media, "webpage", False))
or (not self.config["merge_own_reply"] and msgs[i].is_reply)
):
break
if i != -len(msgs):
del_msgs += [msgs[i].id]
merge_msgs += [msgs[i]]
if merge_msgs:
for msg in reversed(merge_msgs):
if text:
text += "\n" * self.config["new_lines"]
if self.config["new_line_pref"]:
text += self.config["new_line_pref"]
if (
not text
and self.apo_lib.utils.raw_text(msg).startswith(
self.get_prefix()
)
and not self.config["new_line_pref"]
):
text += ">"
text += self.apo_lib.utils.raw_text(msg, True)
await self._client.delete_messages(chat_id, del_msgs)
if not text:
text = self.apo_lib.utils.get_str(
"nothing_to_merge", self.all_strings, message
)
return await utils.answer(message, text)
except IndexError:
return
async def unmergecmd(self, message: Message):
"""
unmerge the messages.
"""
chat_id = utils.get_chat_id(message)
if utils.get_chat_id(message) in self.merged_msgs:
try:
for key, msg_value in self.merged_msgs[chat_id]["message"].items():
if key == "text":
msg_text = msg_value
elif key == "link_preview":
msg_link_preview = msg_value
for key, msg_value in self.merged_msgs[chat_id]["last_msg"].items():
if key == "id":
last_msg_id = msg_value
elif key == "text":
last_msg_text = msg_value
elif key == "link_preview":
last_msg_link_preview = msg_value
await self.client.edit_message(
chat_id,
last_msg_id,
last_msg_text,
link_preview=last_msg_link_preview,
)
await self.client.edit_message(
message, msg_text, link_preview=msg_link_preview
)
except MessageIdInvalidError:
await utils.answer(message, self.strings("undo_merge_fail"))
else:
await utils.answer(message, self.strings("undo_merge_fail"))
self.merged_msgs.clear()
async def q_watcher(self, message: Message):
await self._queue_handler(message)
async def _queue_handler(self, message: Message):
if (
not self.config["active"]
or not isinstance(message, Message)
or not message.out
or message.forward
or message.via_bot
or self.apo_lib.utils.raw_text(message).startswith(self.get_prefix())
):
return
chat_id = utils.get_chat_id(message)
if (self.config["whitelist"] and chat_id not in self.config["chatlist"]) or (
not self.config["whitelist"] and chat_id in self.config["chatlist"]
):
return
if self.config["ignore_prefix"] and any(
self.apo_lib.utils.raw_text(message).startswith(prefix)
for prefix in self.config["ignore_prefix"]
):
return
if self.config["skip_prefix"] and (
found_prefix := next(
(
prefix
for prefix in self.config["skip_prefix"]
if self.apo_lib.utils.raw_text(message).startswith(prefix)
),
None,
)
):
text = message.text.replace(utils.escape_html(found_prefix), "", 1)
if len(text) > 0:
with contextlib.suppress(Exception):
await message.edit(text)
return
if (
(
self.config["skip_length"]
and len(self.apo_lib.utils.remove_html(message.text))
>= self.config["skip_length"]
)
or (self.config["skip_reactions"] and message.reactions)
or (
message.media
and not getattr(message.media, "webpage", False)
or (
not self.config["merge_urls"]
and self.apo_lib.utils.get_entityurls(message)
)
)
):
return
last_msg = None
try:
if utils.get_topic(message):
last_msg_iter = await self._client.get_messages(
chat_id, limit=5, reply_to=utils.get_topic(message)
)
else:
last_msg_iter = await self._client.get_messages(chat_id, limit=5)
for i in range(-4, -1):
if last_msg_iter[i].id != message.id:
last_msg = last_msg_iter[i]
break
except IndexError:
return
if (
self.config["merge_own_reply"]
and message.is_reply
and (
not message.reply_to_msg_id
or message.reply_to_msg_id != utils.get_topic(message)
)
):
last_msg_reply = await message.get_reply_message()
last_msg = last_msg_reply
else:
last_msg_reply = None
if (
(
self.config["skip_emoji"]
and (
self.apo_lib.utils.is_emoji(self.apo_lib.utils.raw_text(message))
or self.apo_lib.utils.is_emoji(
self.apo_lib.utils.raw_text(last_msg)
)
)
)
or (
self.config["skip_reply"]
and not self.config["merge_own_reply"]
and (message.is_reply or last_msg.is_reply)
and (
not message.reply_to_msg_id
or message.reply_to_msg_id != utils.get_topic(message)
)
)
or (
last_msg.is_reply
and message.is_reply
and (
not message.reply_to_msg_id
or message.reply_to_msg_id != utils.get_topic(message)
)
and not self.config["merge_own_reply"]
)
):
return
if (
last_msg.sender_id != self.tg_id
or not isinstance(last_msg, Message)
or last_msg.via_bot
or last_msg.fwd_from
or (self.config["skip_reactions"] and last_msg.reactions)
or (
last_msg.media
and not getattr(last_msg.media, "webpage", False)
or (
not self.config["merge_urls"]
and self.apo_lib.utils.get_entityurls(last_msg)
)
)
or self.apo_lib.utils.remove_html(last_msg.text)[0] == self.get_prefix()
):
return
if self.config["ignore_prefix"] and any(
self.apo_lib.utils.raw_text(last_msg).startswith(prefix)
for prefix in self.config["ignore_prefix"]
):
return
if (
self.config["edit_timeout"]
and (
datetime.now(timezone.utc) - (last_msg.edit_date or last_msg.date)
).total_seconds()
> self.config["edit_timeout"] * 60
) and (
self.config["merge_own_reply"]
and (
not message.is_reply
or message.reply_to_msg_id
and message.reply_to_msg_id == utils.get_topic(message)
)
or not self.config["merge_own_reply"]
):
return
text = last_msg.text
text += "\n" * self.config["new_lines"]
if self.config["new_line_pref"]:
text += self.config["new_line_pref"]
text += message.text
if (
(message.is_reply and message.reply_to_msg_id != utils.get_topic(message))
or self.config["reverse_merge"]
) and (
not self.config["merge_own_reply"]
or not message.is_reply
or message.reply_to_msg_id == utils.get_topic(message)
):
message, last_msg = last_msg, message
message_text = last_msg.text
last_msg_text = message.text
else:
message_text = message.text
last_msg_text = last_msg.text
if self.config["link_preview"] is None:
link_preview = getattr(message.media, "webpage", False) or getattr(
last_msg.media, "webpage", False
)
else:
link_preview = bool(self.config["link_preview"])
try:
if self.config["reverse_merge"] and (
self.config["merge_own_reply"]
and (
(
last_msg.is_reply
and last_msg.reply_to_msg_id != utils.get_topic(last_msg)
)
or (
message.is_reply
and (
not message.reply_to_msg_id
or message.reply_to_msg_id != utils.get_topic(message)
)
)
)
):
if last_msg.is_reply and last_msg.reply_to_msg_id != utils.get_topic(
last_msg
):
reply = await last_msg.get_reply_message()
else:
reply = await message.get_reply_message()
await last_msg.delete()
msg = await last_msg.client.send_message(
chat_id, text, reply_to=reply, link_preview=link_preview
)
else:
msg = await last_msg.edit(text, link_preview=link_preview)
if msg.out:
if (
self.config["merge_own_reply"]
and self.config["own_reply_msg"]
and not self.config["reverse_merge"]
and (
message.is_reply
and (
not message.reply_to_msg_id
or message.reply_to_msg_id != utils.get_topic(message)
)
)
):
await message.edit(
self.config["own_reply_msg"], link_preview=link_preview
)
else:
await message.delete()
self.merged_msgs.clear()
self.merged_msgs[chat_id] = {
"message": {
"text": message_text,
"link_preview": link_preview,
},
"last_msg": {
"id": msg.id or last_msg.id,
"text": last_msg_text,
"link_preview": link_preview,
},
}
return
except Exception as exc:
self.apo_lib.utils.log(
logging.DEBUG,
__name__,
f"Edit failed on last_msg:\n{str(exc)}",
debug_msg=True,
)
return