-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathhellutils.py
604 lines (526 loc) · 20.2 KB
/
hellutils.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
597
598
599
600
601
602
603
604
# credits to @mrconfused
import asyncio
import datetime
import importlib
import inspect
import logging
import math
import os
import re
import sys
import time
import traceback
from pathlib import Path
from time import gmtime, strftime
from telethon import events
from telethon.tl.functions.channels import GetParticipantRequest
from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantCreator
from var import Var
from userbot import CMD_LIST, LOAD_PLUG, LOGS, SUDO_LIST, bot
from userbot.helpers.exceptions import CancelProcess
from userbot.uniborgConfig import Config
ENV = bool(os.environ.get("ENV", False))
if ENV:
from userbot.uniborgConfig import Config
else:
if os.path.exists("config.py"):
from config import Development as Config
def load_module(shortname):
if shortname.startswith("__"):
pass
elif shortname.endswith("_"):
import userbot.utils
path = Path(f"userbot/plugins/{shortname}.py")
name = "userbot.plugins.{}".format(shortname)
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
LOGS.info("Successfully imported " + shortname)
else:
import userbot.utils
path = Path(f"userbot/plugins/{shortname}.py")
name = "userbot.plugins.{}".format(shortname)
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
mod.bot = bot
mod.tgbot = bot.tgbot
mod.Var = Var
mod.command = command
mod.logger = logging.getLogger(shortname)
# support for uniborg
sys.modules["uniborg.util"] = userbot.utils
mod.Config = Config
mod.borg = bot
mod.hellbot = bot
mod.edit_or_reply = edit_or_reply
mod.delete_hell = delete_hell
# support for hellbot originals
sys.modules["hellbot.utils"] = userbot.utils
sys.modules["hellbot"] = userbot
# support for paperplaneextended
sys.modules["userbot.events"] = userbot.utils
spec.loader.exec_module(mod)
# for imports
sys.modules["userbot.plugins." + shortname] = mod
LOGS.info("Successfully imported " + shortname)
def remove_plugin(shortname):
try:
try:
for i in LOAD_PLUG[shortname]:
bot.remove_event_handler(i)
del LOAD_PLUG[shortname]
except BaseException:
name = f"userbot.plugins.{shortname}"
for i in reversed(range(len(bot._event_builders))):
ev, cb = bot._event_builders[i]
if cb.__module__ == name:
del bot._event_builders[i]
except BaseException:
raise ValueError
def admin_cmd(pattern=None, command=None, **args):
args["func"] = lambda e: e.via_bot_id is None
stack = inspect.stack()
previous_stack_frame = stack[1]
file_test = Path(previous_stack_frame.filename)
file_test = file_test.stem.replace(".py", "")
allow_sudo = args.get("allow_sudo", False)
# get the pattern from the decorator
if pattern is not None:
if pattern.startswith(r"\#"):
# special fix for snip.py
args["pattern"] = re.compile(pattern)
elif pattern.startswith(r"^"):
args["pattern"] = re.compile(pattern)
cmd = pattern.replace("$", "").replace("^", "").replace("\\", "")
try:
CMD_LIST[file_test].append(cmd)
except BaseException:
CMD_LIST.update({file_test: [cmd]})
else:
if len(Config.COMMAND_HAND_LER) == 2:
hellreg = "^" + Config.COMMAND_HAND_LER
reg = Config.COMMAND_HAND_LER[1]
elif len(Config.COMMAND_HAND_LER) == 1:
hellreg = "^\\" + Config.COMMAND_HAND_LER
reg = Config.COMMAND_HAND_LER
args["pattern"] = re.compile(hellreg + pattern)
if command is not None:
cmd = reg + command
else:
cmd = (
(reg + pattern).replace("$", "").replace("\\", "").replace("^", "")
)
try:
CMD_LIST[file_test].append(cmd)
except BaseException:
CMD_LIST.update({file_test: [cmd]})
args["outgoing"] = True
# should this command be available for other users?
if allow_sudo:
args["from_users"] = list(Config.SUDO_USERS)
# Mutually exclusive with outgoing (can only set one of either).
args["incoming"] = True
del args["allow_sudo"]
# error handling condition check
elif "incoming" in args and not args["incoming"]:
args["outgoing"] = True
# add blacklist chats, UB should not respond in these chats
args["blacklist_chats"] = True
black_list_chats = list(Config.UB_BLACK_LIST_CHAT)
if black_list_chats:
args["chats"] = black_list_chats
# add blacklist chats, UB should not respond in these chats
if "allow_edited_updates" in args and args["allow_edited_updates"]:
del args["allow_edited_updates"]
# check if the plugin should listen for outgoing 'messages'
return events.NewMessage(**args)
def sudo_cmd(pattern=None, command=None, **args):
args["func"] = lambda e: e.via_bot_id is None
stack = inspect.stack()
previous_stack_frame = stack[1]
file_test = Path(previous_stack_frame.filename)
file_test = file_test.stem.replace(".py", "")
allow_sudo = args.get("allow_sudo", False)
# get the pattern from the decorator
if pattern is not None:
if pattern.startswith(r"\#"):
# special fix for snip.py
args["pattern"] = re.compile(pattern)
elif pattern.startswith(r"^"):
args["pattern"] = re.compile(pattern)
cmd = pattern.replace("$", "").replace("^", "").replace("\\", "")
try:
SUDO_LIST[file_test].append(cmd)
except BaseException:
SUDO_LIST.update({file_test: [cmd]})
else:
if len(Config.SUDO_COMMAND_HAND_LER) == 2:
hellreg = "^" + Config.SUDO_COMMAND_HAND_LER
reg = Config.SUDO_COMMAND_HAND_LER[1]
elif len(Config.SUDO_COMMAND_HAND_LER) == 1:
hellreg = "^\\" + Config.SUDO_COMMAND_HAND_LER
reg = Config.COMMAND_HAND_LER
args["pattern"] = re.compile(hellreg + pattern)
if command is not None:
cmd = reg + command
else:
cmd = (
(reg + pattern).replace("$", "").replace("\\", "").replace("^", "")
)
try:
SUDO_LIST[file_test].append(cmd)
except BaseException:
SUDO_LIST.update({file_test: [cmd]})
args["outgoing"] = True
# should this command be available for other users?
if allow_sudo:
args["from_users"] = list(Config.SUDO_USERS)
# Mutually exclusive with outgoing (can only set one of either).
args["incoming"] = True
del args["allow_sudo"]
# error handling condition check
elif "incoming" in args and not args["incoming"]:
args["outgoing"] = True
# add blacklist chats, UB should not respond in these chats
args["blacklist_chats"] = True
black_list_chats = list(Config.UB_BLACK_LIST_CHAT)
if black_list_chats:
args["chats"] = black_list_chats
# add blacklist chats, UB should not respond in these chats
if "allow_edited_updates" in args and args["allow_edited_updates"]:
del args["allow_edited_updates"]
# check if the plugin should listen for outgoing 'messages'
return events.NewMessage(**args)
# https://t.me/c/1220993104/623253
# https://docs.telethon.dev/en/latest/misc/changelog.html#breaking-changes
async def edit_or_reply(
event,
text,
parse_mode=None,
link_preview=None,
file_name=None,
aslink=False,
linktext=None,
caption=None,
):
link_preview = link_preview or False
reply_to = await event.get_reply_message()
if len(text) < 4096:
parse_mode = parse_mode or "md"
if event.sender_id in Config.SUDO_USERS:
if reply_to:
return await reply_to.reply(
text, parse_mode=parse_mode, link_preview=link_preview
)
return await event.reply(
text, parse_mode=parse_mode, link_preview=link_preview
)
return await event.edit(text, parse_mode=parse_mode, link_preview=link_preview)
asciich = ["*", "`", "_"]
for i in asciich:
text = re.sub(rf"\{i}", "", text)
if aslink:
linktext = linktext or "Message was to big so pasted to bin"
try:
key = (
requests.post(
"https://nekobin.com/api/documents", json={"content": text}
)
.json()
.get("result")
.get("key")
)
text = linktext + f" [here](https://nekobin.com/{key})"
except:
text = re.sub(r"•", ">>", text)
kresult = requests.post(
"https://del.dog/documents", data=text.encode("UTF-8")
).json()
text = linktext + f" [here](https://del.dog/{kresult['key']})"
if event.sender_id in Config.SUDO_USERS:
if reply_to:
return await reply_to.reply(text, link_preview=link_preview)
return await event.reply(text, link_preview=link_preview)
return await event.edit(text, link_preview=link_preview)
file_name = file_name or "output.txt"
caption = caption or None
with open(file_name, "w+") as output:
output.write(text)
if reply_to:
await reply_to.reply(caption, file=file_name)
await event.delete()
return os.remove(file_name)
if event.sender_id in Config.SUDO_USERS:
await event.reply(caption, file=file_name)
await event.delete()
return os.remove(file_name)
await event.client.send_file(event.chat_id, file_name, caption=caption)
await event.delete()
os.remove(file_name)
async def delete_hell(event, text, time=None, parse_mode=None, link_preview=None):
parse_mode = parse_mode or "md"
link_preview = link_preview or False
time = time or 5
if event.sender_id in Config.SUDO_USERS:
reply_to = await event.get_reply_message()
hellevent = (
await reply_to.reply(text, link_preview=link_preview, parse_mode=parse_mode)
if reply_to
else await event.reply(
text, link_preview=link_preview, parse_mode=parse_mode
)
)
else:
hellevent = await event.edit(
text, link_preview=link_preview, parse_mode=parse_mode
)
await asyncio.sleep(time)
return await hellevent.delete()
# from paperplaneextended
on = bot.on
def on(**args):
def decorator(func):
async def wrapper(event):
# do things like check if sudo
await func(event)
client.add_event_handler(wrapper, events.NewMessage(**args))
return wrapper
return decorater
def errors_handler(func):
async def wrapper(errors):
try:
await func(errors)
except BaseException:
date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
new = {
'error': str(sys.exc_info()[1]),
'date': datetime.datetime.now()
}
text = "**USERBOT CRASH REPORT**\n\n"
link = "[here](https://t.me/sn12384)"
text += "If you wanna you can report it"
text += f"- just forward this message {link}.\n"
text += "Nothing is logged except the fact of error and date\n"
ftext = "\nDisclaimer:\nThis file uploaded ONLY here,"
ftext += "\nwe logged only fact of error and date,"
ftext += "\nwe respect your privacy,"
ftext += "\nyou may not report this error if you've"
ftext += "\nany confidential data here, no one will see your data\n\n"
ftext += "--------BEGIN USERBOT TRACEBACK LOG--------"
ftext += "\nDate: " + date
ftext += "\nGroup ID: " + str(errors.chat_id)
ftext += "\nSender ID: " + str(errors.sender_id)
ftext += "\n\nEvent Trigger:\n"
ftext += str(errors.text)
ftext += "\n\nTraceback info:\n"
ftext += str(traceback.format_exc())
ftext += "\n\nError text:\n"
ftext += str(sys.exc_info()[1])
ftext += "\n\n--------END USERBOT TRACEBACK LOG--------"
command = "git log --pretty=format:\"%an: %s\" -5"
ftext += "\n\n\nLast 5 commits:\n"
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
result = str(stdout.decode().strip()) \
+ str(stderr.decode().strip())
ftext += result
return wrapper
async def progress(
current, total, event, start, type_of_ps, file_name=None, is_cancelled=None
):
"""Generic progress_callback for uploads and downloads."""
now = time.time()
diff = now - start
if is_cancelled is True:
raise CancelProcess
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
speed = current / diff
elapsed_time = round(diff) * 1000
time_to_completion = round((total - current) / speed) * 1000
estimated_total_time = elapsed_time + time_to_completion
progress_str = "[{0}{1}] {2}%\n".format(
"".join(["▰" for i in range(math.floor(percentage / 10))]),
"".join(["▱" for i in range(10 - math.floor(percentage / 10))]),
round(percentage, 2),
)
tmp = progress_str + "{0} of {1}\nETA: {2}".format(
humanbytes(current), humanbytes(total), time_formatter(estimated_total_time)
)
if file_name:
await event.edit(
"{}\nFile Name: `{}`\n{}".format(type_of_ps, file_name, tmp)
)
else:
await event.edit("{}\n{}".format(type_of_ps, tmp))
def humanbytes(size):
"""Input size in bytes,
outputs in a human readable format"""
# https://stackoverflow.com/a/49361727/4723940
if not size:
return ""
# 2 ** 10 = 1024
power = 2 ** 10
raised_to_pow = 0
dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
while size > power:
size /= power
raised_to_pow += 1
return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
def human_to_bytes(size: str) -> int:
units = {
"M": 2 ** 20,
"MB": 2 ** 20,
"G": 2 ** 30,
"GB": 2 ** 30,
"T": 2 ** 40,
"TB": 2 ** 40,
}
size = size.upper()
if not re.match(r" ", size):
size = re.sub(r"([KMGT])", r" \1", size)
number, unit = [string.strip() for string in size.split()]
return int(float(number) * units[unit])
# Inputs time in milliseconds, to get beautified time, as string
def time_formatter(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days) + " day(s), ") if days else "")
+ ((str(hours) + " hour(s), ") if hours else "")
+ ((str(minutes) + " minute(s), ") if minutes else "")
+ ((str(seconds) + " second(s), ") if seconds else "")
+ ((str(milliseconds) + " millisecond(s), ") if milliseconds else "")
)
return tmp[:-2]
class Loader:
def __init__(self, func=None, **args):
self.Var = Var
bot.add_event_handler(func, events.NewMessage(**args))
# Admin checker by uniborg
async def is_admin(client, chat_id, user_id):
if not str(chat_id).startswith("-100"):
return False
try:
req_jo = await client(GetParticipantRequest(channel=chat_id, user_id=user_id))
chat_participant = req_jo.participant
if isinstance(
chat_participant, (ChannelParticipantCreator, ChannelParticipantAdmin)
):
return True
except Exception:
return False
else:
return False
def register(**args):
args["func"] = lambda e: e.via_bot_id is None
stack = inspect.stack()
previous_stack_frame = stack[1]
file_test = Path(previous_stack_frame.filename)
file_test = file_test.stem.replace(".py", "")
pattern = args.get("pattern", None)
disable_edited = args.get("disable_edited", True)
allow_sudo = args.get("allow_sudo", False)
if pattern is not None and not pattern.startswith("(?i)"):
args["pattern"] = "(?i)" + pattern
if "disable_edited" in args:
del args["disable_edited"]
reg = re.compile("(.*)")
if pattern is not None:
try:
cmd = re.search(reg, pattern)
try:
cmd = cmd.group(1).replace("$", "").replace("\\", "").replace("^", "")
except BaseException:
pass
try:
CMD_LIST[file_test].append(cmd)
except BaseException:
CMD_LIST.update({file_test: [cmd]})
except BaseException:
pass
if allow_sudo:
args["from_users"] = list(Config.SUDO_USERS)
# Mutually exclusive with outgoing (can only set one of either).
args["incoming"] = True
del args["allow_sudo"]
# error handling condition check
elif "incoming" in args and not args["incoming"]:
args["outgoing"] = True
# add blacklist chats, UB should not respond in these chats
args["blacklist_chats"] = True
black_list_chats = list(Config.UB_BLACK_LIST_CHAT)
if len(black_list_chats) > 0:
args["chats"] = black_list_chats
def decorator(func):
if not disable_edited:
bot.add_event_handler(func, events.MessageEdited(**args))
bot.add_event_handler(func, events.NewMessage(**args))
try:
LOAD_PLUG[file_test].append(func)
except Exception:
LOAD_PLUG.update({file_test: [func]})
return func
return decorator
def command(**args):
args["func"] = lambda e: e.via_bot_id is None
stack = inspect.stack()
previous_stack_frame = stack[1]
file_test = Path(previous_stack_frame.filename)
file_test = file_test.stem.replace(".py", "")
pattern = args.get("pattern", None)
allow_sudo = args.get("allow_sudo", None)
allow_edited_updates = args.get("allow_edited_updates", False)
args["incoming"] = args.get("incoming", False)
args["outgoing"] = True
if bool(args["incoming"]):
args["outgoing"] = False
try:
if pattern is not None and not pattern.startswith("(?i)"):
args["pattern"] = "(?i)" + pattern
except BaseException:
pass
reg = re.compile("(.*)")
if pattern is not None:
try:
cmd = re.search(reg, pattern)
try:
cmd = cmd.group(1).replace("$", "").replace("\\", "").replace("^", "")
except BaseException:
pass
try:
CMD_LIST[file_test].append(cmd)
except BaseException:
CMD_LIST.update({file_test: [cmd]})
except BaseException:
pass
if allow_sudo:
args["from_users"] = list(Config.SUDO_USERS)
# Mutually exclusive with outgoing (can only set one of either).
args["incoming"] = True
del allow_sudo
try:
del args["allow_sudo"]
except BaseException:
pass
args["blacklist_chats"] = True
black_list_chats = list(Config.UB_BLACK_LIST_CHAT)
if len(black_list_chats) > 0:
args["chats"] = black_list_chats
if "allow_edited_updates" in args:
del args["allow_edited_updates"]
def decorator(func):
if allow_edited_updates:
bot.add_event_handler(func, events.MessageEdited(**args))
bot.add_event_handler(func, events.NewMessage(**args))
try:
LOAD_PLUG[file_test].append(func)
except BaseException:
LOAD_PLUG.update({file_test: [func]})
return func
return decorator