-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapodiktum_library.py
2467 lines (2324 loc) · 85.9 KB
/
apodiktum_library.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__version__ = (2, 2, 20)
# ▄▀█ █▄ █ █▀█ █▄ █ █▀█ ▀▀█ █▀█ █ █ █▀
# █▀█ █ ▀█ █▄█ █ ▀█ ▀▀█ █ ▀▀█ ▀▀█ ▄█
#
# © Copyright 2023
#
# 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/file_dumbster/11
# meta pic: https://t.me/file_dumbster/13
# scope: hikka_min 1.3.3
# requires: emoji alphabet_detector
import ast
import asyncio
import collections
import contextlib
import copy
import hashlib
import html
import io
import logging
import math
import re
from datetime import datetime, timedelta
from typing import IO, Any, Optional, Tuple, Union
import aiohttp
import emoji
import grapheme
import requests
from aiogram.types import ChatPermissions
from aiogram.utils.exceptions import (
BotKicked,
ChatNotFound,
MessageCantBeDeleted,
MessageToDeleteNotFound,
)
from telethon.errors import UserNotParticipantError
from telethon.hints import EntityLike
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditBannedRequest,
GetFullChannelRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.messages import (
GetDialogFiltersRequest,
UpdateDialogFilterRequest,
)
from telethon.tl.types import (
Channel,
Chat,
ChatAdminRights,
ChatBannedRights,
Message,
MessageEntityUrl,
User,
)
from .. import loader, utils
logger = logging.getLogger(__name__)
class ApodiktumLib(loader.Library):
"""
The Apodiktum Library is a collection of useful functions and classes for all Hikka developers.
"""
developer = "@apodiktum_modules"
version = __version__
strings = {
"_cfg_cst_auto_migrate": "Wheather to auto migrate defined changes on startup.",
"_cfg_doc_log_channel": "Wheather to log debug as info in logger channel.",
"_cfg_doc_log_debug": (
"Wheather to log declared debug messages as info in logger channel."
),
}
strings_de = {
"_cfg_cst_auto_migrate": (
"Ob definierte Änderungen beim Start automatisch migriert werden sollen."
),
"_cfg_doc_log_channel": (
"Ob Debug als Info im Logger-Kanal protokolliert werden soll."
),
"_cfg_doc_log_debug": (
"Ob deklarierte Debug-Meldungen als Info im Logger-Kanal"
" protokolliert werden sollen."
),
}
strings_ru = {}
all_strings = {
"strings": strings,
"strings_en": strings,
"strings_de": strings_de,
"strings_ru": strings_ru,
}
def __init__(self):
"""
Initializes the library config.
"""
self.config = loader.LibraryConfig(
loader.ConfigValue(
"auto_migrate",
True,
doc=lambda: self.strings("_cfg_cst_auto_migrate"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"log_channel",
True,
doc=lambda: self.strings("_cfg_doc_log_channel"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"log_debug",
False,
doc=lambda: self.strings("_cfg_doc_log_debug"),
validator=loader.validators.Boolean(),
),
)
async def init(self):
"""
Initializes the library.
"""
if self.config["log_channel"]:
logging.getLogger(self.__class__.__name__).info(
"Apodiktum Library"
f" v{__version__[0]}.{__version__[1]}.{__version__[2]} loading..."
)
else:
logging.getLogger(self.__class__.__name__).debug(
"Apodiktum Library"
f" v{__version__[0]}.{__version__[1]}.{__version__[2]} loading..."
)
logging.getLogger(self.__class__.__name__).debug(
"Apodiktum Library"
f" v{__version__[0]}.{__version__[1]}.{__version__[2]} started for"
f" {self.client} | {self.client.tg_id}"
)
self.allmodules._apodiktum_lib_version = __version__
self.loaded_classes = {}
if not hasattr(self, "_watcher_q_queue"):
self._watcher_q_queue = {}
if not hasattr(self, "_watcher_q_task"):
self._watcher_q_task = {}
await self.__init_classes()
await self.__refresh_classes()
self._acl_task = asyncio.ensure_future(
self._controllerloader.ensure_controller()
)
self.lookup("evaluator").apo_lib = self
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
"Apodiktum Library"
f" v{__version__[0]}.{__version__[1]}.{__version__[2]} successfully"
" loaded.",
)
async def __init_classes(self):
"""
Initializes all classes in the library.
"""
self.utils = ApodiktumUtils(self)
self._controllerloader = ApodiktumControllerLoader(self)
self._internal = ApodiktumInternal(self)
self.migrator = ApodiktumMigrator(self)
self.watcher_q = ApodiktumWatcherQueue(self)
self.utils_beta = (
ApodiktumUtilsBeta(self) if await self._internal._beta_access() else None
)
self.loaded_classes["utils"] = self.utils
self.loaded_classes["_controllerloader"] = self._controllerloader
self.loaded_classes["_internal"] = self._internal
self.loaded_classes["migrator"] = self.migrator
self.loaded_classes["watcher_q"] = self.watcher_q
if self.utils_beta:
self.loaded_classes["utils_beta"] = self.utils_beta
async def __refresh_classes(self):
"""
Refresh all classes.
"""
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
"Refreshing all classes to the current library state.",
debug_msg=True,
)
for cl in self.loaded_classes:
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
f"Refreshing {cl} to the current library state.",
debug_msg=True,
)
self.loaded_classes[cl] = await self.loaded_classes[cl]._refresh_lib(self)
if getattr(self, cl):
setattr(self, cl, self.loaded_classes[cl])
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
"Refreshing of all classes done.",
debug_msg=True,
)
async def on_lib_update(self, new_lib: loader.Library):
"""
Called when the library is updated, to give old vars to the new library.
:param new_lib: The new library
"""
await self.__refresh_classes()
with contextlib.suppress(Exception):
self._acl_task.cancel()
with contextlib.suppress(Exception):
self._ss_task.cancel()
(
new_lib._watcher_q_queue,
new_lib._watcher_q_task,
) = self._internal._lib_update_watcher_q_handler()
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
"Apodiktum Library"
f" v{__version__[0]}.{__version__[1]}.{__version__[2]} was"
" updated.",
)
self.allmodules._apodiktum_controller_init = False
return
class ApodiktumControllerLoader(loader.Module):
"""
This class is used to load the Apo-LibController
"""
def __init__(
self,
lib: loader.Library,
):
self.utils = lib.utils
self.utils.log(
logging.DEBUG,
lib.__class__.__name__,
f"class {self.__class__.__name__} is being initiated!",
debug_msg=True,
)
self.lib = lib
self._db = lib.db
self._client = lib.client
self.inline = lib.inline
self._libclassname = lib.__class__.__name__
self.unload_controller = False
async def _refresh_lib(
self,
lib: loader.Library,
):
"""
!do not use this method directly!
Refreshes the class with the current state of the library
:param lib: The library class
:return: None
"""
self.lib = lib
self.utils = lib.utils
return self
async def _init_controller(self):
"""
Initializes the Apo-LibController download and load
"""
self.utils.log(
logging.DEBUG,
self._libclassname,
"Attempting to load ApoLibController from GitHub.",
debug_msg=True,
)
controller_loaded = await self._load_github()
if controller_loaded:
return controller_loaded
self._controller_found = False
return None
async def ensure_controller(self, first_loop: bool = True):
"""
Ensures that the Apo-LibController is loaded
"""
if not getattr(self.lib.allmodules, "_apodiktum_controller_init", False):
self.lib.allmodules._apodiktum_controller_init = True
while True:
if not self.unload_controller:
if first_loop:
if (
not await self._wait_load(
delay=5, retries=5, first_loop=first_loop
)
and not self._controller_refresh()
):
await self._init_controller()
first_loop = False
elif not self._controller_refresh():
await self._init_controller()
await asyncio.sleep(5)
return
def _controller_refresh(self):
"""
Checks if the Apo-LibController is loaded
"""
self._controller_found = bool(self.lib.lookup("Apo-LibController"))
return self._controller_found
async def _load_github(self):
"""
Downloads the Apo-LibController from GitHub
"""
link = "https://raw.githubusercontent.com/anon97945/hikka-mods/master/apolib_controller.py"
async with aiohttp.ClientSession() as session, session.head(link) as response:
if response.status >= 300:
return None
link_message = await self._client.send_message(
"me", f"{self.lib.get_prefix()}dlmod {link}"
)
await self.lib.allmodules.commands["dlmod"](link_message)
lib_controller = await self._wait_load(delay=5, retries=5)
await link_message.delete()
return lib_controller
async def _wait_load(self, delay, retries, first_loop=False):
"""
Waits for the Apo-LibController to load
:param delay: The delay between retries
:param retries: The number of retries
:param first_loop: Whether this is the first loop
:return: Whether the Apo-LibController was loaded
"""
while retries:
if lib_controller := self.lib.lookup("Apo-LibController"):
self.utils.log(
logging.DEBUG,
self._libclassname,
"ApoLibController found!",
debug_msg=True,
)
return lib_controller
if not getattr(self.lib.lookup("Loader"), "fully_loaded", False):
retries = 1
elif (
getattr(self.lib.lookup("Loader"), "fully_loaded", False) and first_loop
):
retries = 0
else:
retries -= 1
if retries != 0:
self.utils.log(
logging.DEBUG,
self._libclassname,
"ApoLibController not found, retrying in"
f" {delay} seconds...\nHikka"
" fully loaded:"
f" {getattr(self.lib.lookup('Loader'), 'fully_loaded', False)}",
debug_msg=True,
)
if retries == 0:
return False
await asyncio.sleep(delay)
class ApodiktumWatcherQueue(loader.Module):
"""
Apodiktum Watcher Queue queues messages for the watcher
"""
def __init__(
self,
lib: loader.Library,
):
self.utils = lib.utils
self.utils.log(
logging.DEBUG,
lib.__class__.__name__,
f"class {self.__class__.__name__} is being initiated!",
debug_msg=True,
)
self.lib = lib
self._db = lib.db
self._client = lib.client
self.inline = lib.inline
self._libclassname = self.lib.__class__.__name__
self._lib_db = self._db.setdefault(self._libclassname, {})
self._chats_db = self._lib_db.setdefault("chats", {})
self._watcher_q_queue = lib._watcher_q_queue
self._watcher_q_task = lib._watcher_q_task
self.__init_old_watcher_handler()
async def _refresh_lib(
self,
lib: loader.Library,
):
"""
!do not use this method directly!
Refreshes the class with the current state of the library
:param lib: The library class
:return: None
"""
self.lib = lib
self.utils = lib.utils
return self
def __init_old_watcher_handler(self):
"""
Initializes the old watcher handler
"""
if not getattr(self, "first_run", True):
return
self.first_run = False
for name in list(self._watcher_q_task):
for method in list(self._watcher_q_task[name]):
self._watcher_q_task[name].pop(method)
self.register(name, method)
if not self._watcher_q_queue[name]:
self._watcher_q_task.pop(name)
async def msg_reciever(self, message: Message):
"""
!do not use this method directly, it will be used by `apolib_controller.py`!
Recieves messages and queues them for the handler.
:param message: The message to queue
:return: None
"""
for sub_queue in self._watcher_q_queue:
for queue in self._watcher_q_queue[sub_queue].values():
await queue.put(message)
def register(self, name: str, method: str = "q_watcher"):
"""
Adds a new method to the queue
:param name: The name of the module
:param method: The method to use for the queue
:return: None
"""
if not hasattr(self.lib.lookup(name), method):
self.utils.log(
logging.ERROR,
self.__class__.__name__,
f"Module `{name}` has no method called `{method}`!",
)
return
self._watcher_q_queue.setdefault(name, {}).setdefault(method, asyncio.Queue())
self._watcher_q_task.setdefault(name, {}).setdefault(
method, asyncio.create_task(self.__queue_method_handler(name, method))
)
def unregister(self, name: str, method: str = "q_watcher"):
"""
Removes a queue handler
:param name: The name of the module
:param method: The method to remove
:return: None
"""
self._watcher_q_task[name][method].cancel()
self._watcher_q_task[name].pop(method)
self._watcher_q_queue[name].pop(method)
if not self._watcher_q_task[name]:
self._watcher_q_task.pop(name)
if not self._watcher_q_queue[name]:
self._watcher_q_queue.pop(name)
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
f"Unregistered method `{method}` for `{name}` from the queue!\nCurrent"
f" watcher tasks: {self._watcher_q_task}",
debug_msg=True,
)
async def __queue_method_handler(self, name: str, method: str):
"""
Handles the queue for a module
:param name: The name of the module
:param method: The method to use for the queue
:return: Message Object
"""
try:
while True:
try:
msg = await self._watcher_q_queue[name][method].get()
await getattr(self.lib.lookup(name), method)(msg) if hasattr(
self.lib.lookup(name), method
) else self.unregister(name, method)
except KeyError:
self.utils.log(
logging.DEBUG,
self.__class__.__name__,
f"Task stopped! Method `{method}` of `{name}` is not"
" registered!",
debug_msg=True,
)
break
except Exception as exc:
self.utils.log(
logging.ERROR,
name,
f"Exception in method `{method}` of `{name}`:\n{exc}",
exc_info=True,
)
continue
return
except asyncio.CancelledError:
return
class ApodiktumUtils(loader.Module):
"""
This class is used to handle all the utility functions of the library.
"""
def __init__(
self,
lib: loader.Library,
):
self.lib = lib
self._db = lib.db
self._client = lib.client
self.inline = lib.inline
self._libclassname = lib.__class__.__name__
self._lib_db = self._db.setdefault(self._libclassname, {})
self._chats_db = self._lib_db.setdefault("chats", {})
self._perms_cache = {}
self._get_fullchannelrequest_cache = {}
self.log(
logging.DEBUG,
self._libclassname,
f"class {self.__class__.__name__} is being initiated!",
debug_msg=True,
)
async def _refresh_lib(
self,
lib: loader.Library,
):
"""
!do not use this method directly!
Refreshes the class with the current state of the library
:param lib: The library class
:return: None
"""
self.lib = lib
self.utils = lib.utils
return self
def get_str(
self, string: str, all_strings: dict, message: Optional[Message] = None
) -> str:
"""
Get a string from a dictionary
:param string: The string to get
:param all_strings: The dictionary to get the string from
:param message: The message to check for forced chat strings
:return: The translated string
"""
base_strings = "strings"
default_lang = None
if (
"hikka.translations" in self._db
and "lang" in self._db["hikka.translations"]
):
default_lang = self._db["hikka.translations"]["lang"]
languages = {base_strings: all_strings[base_strings]}
for lang in all_strings:
if len(lang.split("_", 1)) == 2:
languages[lang.split("_", 1)[1]] = {
**all_strings[base_strings],
**all_strings[lang],
}
if message:
if chat_id := utils.get_chat_id(message):
chatid_db = self._chats_db.setdefault(str(chat_id), {})
forced_lang = chatid_db.get("forced_lang")
for lang, strings in languages.items():
if lang and forced_lang == lang:
if string in strings:
return strings[string].replace("<br>", "\n")
break
if (
default_lang
and default_lang in list(languages)
and string in languages[default_lang]
):
return languages[default_lang][string].replace("<br>", "\n")
return all_strings[base_strings][string].replace("<br>", "\n")
def log(
self,
level: Optional[int] = None,
name: Optional[str] = None,
text: Optional[str] = None,
debug_msg: Optional[bool] = False,
exc_info: Optional[Exception] = False,
):
"""
Logs a message to the console
:param level: The logging level | not required if exc_info is True
:param name: The name of the module | not required if exc_info is True
:param text: The text to log | not required if exc_info is True
:param debug_msg: Whether to log the message as a defined debug message
:param exc_info: Whether to log the exception info
:return: None
"""
if not name:
name = self._libclassname
apo_logger = logging.getLogger(name)
if exc_info:
return apo_logger.exception(text)
if (
not debug_msg and self.lib.config["log_channel"] and level == logging.DEBUG
) or (debug_msg and self.lib.config["log_debug"] and level == logging.DEBUG):
return apo_logger.info(text, exc_info=exc_info)
if level in [logging.CRITICAL, logging.FATAL]:
return apo_logger.critical(text, exc_info=exc_info)
if level == logging.ERROR:
return apo_logger.error(text, exc_info=exc_info)
if level == logging.WARNING:
return apo_logger.warning(text, exc_info=exc_info)
if level == logging.INFO:
return apo_logger.info(text, exc_info=exc_info)
return (
apo_logger.debug(text, exc_info=exc_info)
if level == logging.DEBUG
else None
)
async def is_member(
self,
chat: EntityLike,
user: Optional[EntityLike] = None,
exp: Optional[int] = 5,
force: Optional[bool] = False,
) -> bool:
"""
Checks if a user is a member of a chat
:param entity: Chat ID or Chat Entity
:param user: User ID or User Entity
:param exp: The max time of cached results in seconds
:param force: Whether to force a refresh of the cache
:return: perms if user is a member of the chat, None otherwise
"""
try:
return await self._client.get_perms_cached(
chat,
user,
exp=exp,
force=force,
)
except UserNotParticipantError:
return None
async def is_linkedchannel(
self,
chat: EntityLike,
user: EntityLike,
exp: Optional[int] = 300,
force: Optional[bool] = False,
) -> bool:
"""
Checks if the message is from the linked channel
:param chat: Chat ID or Chat Entity
:param user: User ID or User Entity
:param exp: The max time of cached results in seconds
:param force: Whether to force refresh the cache
:return: True if the message is from the linked channel, False otherwise
"""
chat = await self._client.get_entity(chat) if isinstance(chat, int) else chat
user = (
await self._client.get_entity(user)
if user and isinstance(user, int)
else user
)
if not isinstance(user, Channel):
return False
full_channel = await self._client.get_fullchannel(
user,
exp=exp,
force=force,
)
if (
full_channel
and full_channel.full_chat
and full_channel.full_chat.linked_chat_id
):
return chat.id == int(full_channel.full_chat.linked_chat_id)
@staticmethod
async def get_buttons(
message: Message,
) -> dict:
"""
Gets the buttons as a dict
:param message: Message
:return: Buttons as dict
"""
chat_id = utils.get_chat_id(message)
button_dict = {}
bmsg = await message.client.get_messages(chat_id, ids=message.id)
buttons = bmsg.buttons
for row_count, row in enumerate(buttons):
button_dict[row_count] = {}
for button_count, button in enumerate(row):
button_dict[row_count][button_count] = {"text": button.text}
if button.data:
button_dict[row_count][button_count]["data"] = button.data
if button.url:
button_dict[row_count][button_count]["url"] = button.url
return button_dict
async def get_tag(
self,
user: EntityLike,
WithID: bool = False,
) -> str:
"""
Get the tag of a user/channel
:param user: User/Channel
:param WithID: Return the tag with the ID
:return: Tag message as string
"""
user = await self._client.get_entity(user) if isinstance(user, int) else user
if isinstance(user, Channel):
if WithID:
return (
f"<a href='tg://resolve?domain={user.username}'>{user.title}</a>"
f" (<code>{str(user.id)}</code>)"
if user.username
else f"{user.title}(<code>{str(user.id)}</code>)"
)
return (
f"<a href='tg://resolve?domain={user.username}'>{user.title}</a>"
if user.username
else f"{user.title}"
)
if WithID:
return (
f"<a href='tg://resolve?domain={user.username}'>{user.first_name}</a>"
f" (<code>{str(user.id)}</code>)"
if user.username
else (
f"<a href='tg://user?id={str(user.id)}'>{user.first_name}</a>"
f" (<code>{str(user.id)}</code>)"
)
)
return (
f"<a href='tg://resolve?domain={user.username}'>{user.first_name}</a>"
if user.username
else f"<a href='tg://user?id={str(user.id)}'>{user.first_name}</a>"
)
async def get_tag_link(self, user: EntityLike) -> str:
"""
Returns a tag link to the user's profile
:param user: User or user ID
:return: Tag link as string
"""
user = await self._client.get_entity(user) if isinstance(user, int) else user
if isinstance(user, User):
return f"tg://user?id={user.id}"
if isinstance(user, Channel) and getattr(user, "username", None):
return f"tg://resolve?domain={user.username}"
return ""
async def get_invite_link(
self,
chat: Union[Chat, int],
) -> str:
"""
Gets the invite link for the chat (need to be admin and invite user perms)
:param chat: Chat or chat ID
:return: Invite link as string
"""
chat = await self._client.get_entity(chat) if isinstance(chat, int) else chat
if chat.username:
link = f"https://t.me/{chat.username}"
elif chat.admin_rights and chat.admin_rights.invite_users:
link = await self._client(GetFullChannelRequest(channel=chat.id))
link = link.full_chat.exported_invite.link
else:
link = None
return link
async def get_user_id(self, message: Message, strip: bool = False) -> int:
"""
Gets the user ID from a message
:param message: Message
:param strip: Remove -100 from the user_id
:return: User ID
"""
try:
user_id = (
getattr(message, "sender_id", False)
or message.action_message.action.users[0]
)
except Exception: # skipcq: PYL-W0703
try:
user_id = message.action_message.action.from_id.user_id
except Exception: # skipcq: PYL-W0703
try:
user_id = message.from_id.user_id
except Exception: # skipcq: PYL-W0703
try:
user_id = message.action_message.from_id.user_id
except Exception: # skipcq: PYL-W0703
try:
user_id = message.action.from_user.id
except Exception: # skipcq: PYL-W0703
try:
user_id = (await message.get_user()).id
except Exception: # skipcq: PYL-W0703
try:
user_id = message.peer_id.channel_id
except Exception: # skipcq: PYL-W0703
try:
user_id = message.from_id
except Exception: # skipcq: PYL-W0703
self.log(
logging.DEBUG,
self._libclassname,
"Can't extract entity from event"
f" {type(message)}",
)
return
if str(user_id).startswith("-100") and strip:
user_id = int(str(user_id)[4:])
else:
user_id = int(user_id)
return user_id
@staticmethod
def validate_boolean(s: Any) -> bool:
"""
Validates a boolean value
:param s: String
:return: True if the string represents a boolean, False otherwise
"""
try:
return loader.validators.Boolean().validate(s)
except loader.validators.ValidationError:
return False
@staticmethod
def validate_integer(
s: Any,
digits: Optional[int] = None,
minimum: Optional[int] = None,
maximum: Optional[int] = None,
) -> bool:
"""
Checks if the string represents an integer
:param s: String to check
:param digits: Number of digits
:param minimum: Minimum value
:param maximum: Maximum value
:return: True if the string represents an integer, False otherwise
"""
kwargs = {}
if digits is not None:
kwargs["digits"] = digits
if minimum is not None:
kwargs["minimum"] = minimum
if maximum is not None:
kwargs["maximum"] = maximum
try:
loader.validators.Integer().validate(s, **kwargs)
return True
except loader.validators.ValidationError:
return False
@staticmethod
def validate_string(
s: Any,
minimum: Optional[int] = None,
maximum: Optional[int] = None,
length: Optional[int] = None,
) -> bool:
"""
Checks if the string represents a string
:param s: String to check
:param minimum: Minimum length
:param maximum: Maximum length
:param length: Exact length
:return: True if the string represents a string, False otherwise
"""
try:
if not isinstance(length, int):
if (
isinstance(minimum, int)
and len(list(grapheme.graphemes(str(s)))) < minimum
):
return False
if (
isinstance(maximum, int)
and len(list(grapheme.graphemes(str(s)))) > maximum
):
return False
elif (
isinstance(length, int)
and len(list(grapheme.graphemes(str(s)))) != length
):
return False
return True
except TypeError:
return False
@staticmethod
def validate_float(
s: Any,
minimum: Optional[float] = None,
maximum: Optional[float] = None,
) -> bool:
"""
Checks if the string represents a float
:param s: String to check
:param minimum: Minimum value
:param maximum: Maximum value
:return: True if the string represents a float, False otherwise
"""
kwargs = {}
if minimum is not None:
kwargs["minimum"] = minimum
if maximum is not None:
kwargs["maximum"] = maximum
try:
loader.validators.Float().validate(s, **kwargs)
return True
except loader.validators.ValidationError:
return False
@staticmethod
def validate_datetime(s: Any, dt_format: Optional[str] = "%Y-%m-%d") -> bool:
"""
Checks if the string represents a date
:param s: String to check
:param dt_format: Date/Time/Datetime format -> https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
:return: True if the string represents a date, False otherwise
"""
try:
datetime.strptime(s, dt_format)
return True
except (ValueError, TypeError):
return False
@staticmethod
def validate_tgid(s: Any) -> bool:
"""
Checks if the string represents a Telegram ID
:param s: String to check
:return: True if the string represents a Telegram ID, False otherwise
"""
try:
loader.validators.TelegramID().validate(s)
return True
except loader.validators.ValidationError:
return False
@staticmethod
def validate_none(s: Any) -> bool:
"""
Checks if the string represents a None value
:param s: String to check
:return: True if the string represents a None value, False otherwise
"""
try:
return s in {None, False, ""}
except TypeError:
return False
@staticmethod
def validate_regex(
s: Any,
regex: str,
) -> bool:
"""