-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
950 lines (818 loc) · 40.8 KB
/
utils.py
File metadata and controls
950 lines (818 loc) · 40.8 KB
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
import configparser
import hashlib
import json
import logging
import os
import pickle
import subprocess
from dataclasses import dataclass
from typing import Callable, Optional
from packaging import version
from packaging.requirements import Requirement
from importlib.metadata import version as importlib_version
from telebot import types
import sys
import threading
import time
import traceback
from importlib import reload
import sql_worker
import telebot
def log_uncaught_exceptions(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
logging.error("UNEXPECTED RUNTIME EXCEPTION", exc_info=(exc_type, exc_value, exc_traceback))
@dataclass
class Command:
command_func: Callable
aliases: Optional[tuple[str]]
class ConfigData:
__ADMIN_RECOMMENDED = {"can_change_info": False,
# "can_post_messages": None,
# "can_edit_messages": None,
"can_delete_messages": False,
"can_invite_users": True,
"can_restrict_members": False,
"can_pin_messages": True,
"can_promote_members": False,
"is_anonymous": False,
"can_manage_video_chats": True,
# "can_manage_voice_chats": None,
"can_manage_topics": True,
"can_post_stories": True,
"can_edit_stories": False,
"can_delete_stories": False}
__ADMIN_RUS = {"can_change_info": "Изменения профиля группы",
# "can_post_messages": None,
# "can_edit_messages": None,
"can_delete_messages": "Удаление сообщений",
"can_invite_users": "Пригласительные ссылки",
"can_restrict_members": "Блокировка пользователей",
"can_pin_messages": "Закрепление сообщений",
"can_promote_members": "Добавление администраторов",
"is_anonymous": "Анонимность",
"can_manage_video_chats": "Управление видеочатами",
# "can_manage_voice_chats": None,
"can_manage_topics": "Управление темами",
"can_post_stories": "Публикация историй",
"can_edit_stories": "Изменение чужих историй",
"can_delete_stories": "Удаление чужих историй"}
# Do not edit this section to change the parameters of the bot!
# TeleBOSS is customizable via config file or chat voting!
# It is possible to access sqlWorker.params directly for parameters that are stored in the database
VERSION = "3.2.1" # Current bot version
CODENAME = "Catalyst Core"
MIN_VERSION = "2.14" # The minimum version from which you can upgrade to this one without breaking the bot
BUILD_DATE = "04.03.2026" # Bot build date
ANONYMOUS_ID = 1087968824 # ID value for anonymous user tg
EASTER_LINK = "https://2girls.1cup.one" # Link for Easter eggs
global_timer = 3600 # Value in seconds of duration of votes
global_timer_ban = 300 # Value in seconds of duration of ban-votes
__votes_need = 0 # Required number of votes for early voting closure
__votes_need_ban = 0 # Required number of votes for early ban-voting closure
__votes_need_min = 2 # Minimum amount of votes for a vote to be accepted
main_chat_id = "" # Outside param/Bot Managed Chat ID
debug = False # Debug mode with special presets and lack of saving parameters in the database
vote_mode = 3 # Sets the mode in which the voice cannot be canceled and transferred (1),
# it cannot be canceled, but it can be transferred (2) and it can be canceled and transferred (3)
vote_privacy = 'private' # Can have values "public", "private" and "hidden", see /votes help for details
marmalade = True # Enable or disable chat protection mechanism Marmalade
marmalade_timer = 64800 # The time during which the user will not be able to enter the main chat from the allied
# one without passing the verification
marmalade_reset_timer = 604800 # Time after which the entry in the database for the Marmalade protection mechanism
# becomes irrelevant and requires updating
wait_timer = 30 # Cooldown before being able to change or cancel voice
kill_mode = 2 # Mode 0 - the /kill command is disabled, mode 1 - everyone can use it, mode 2 - only chat admins
fixed_rules = False # Outside param/If enabled, the presence and absence of rules is decided by the bot host
rate = True # Enables or disables the rating system
admin_fixed = False # Outside param/If enabled, chat participants
# cannot change the admin rights allowed for issuance by voting
admin_allowed = __ADMIN_RECOMMENDED # Admin rights allowed for issuance in the chat
path = "" # Outside param/Path to the chat data folder
token = "" # Outside param/Bot token
chat_mode = "mixed" # Outside param
# Private - the chat is protected with a whitelist
# Mixed - the protection mode is changed by voting in the chat
# Public - the chat is protected by rapid voting after the participant enters the chat
# Captcha - chat is protected by a standard captcha
binary_chat_mode = 0 # Chat protection mode in binary form
bot_id = None # Telegram bot account ID
welcome_default = "Welcome to {1}!" # Default chat greeting
# Can be changed in the welcome.txt file, for example "{0}, welcome to {1}",
# where {0} is the user's nickname, {1} is the name of the chat
thread_id = None # Default topic ID in Telegram chat
SQL_INIT = {"version": VERSION,
"votes": __votes_need,
"votes_ban": __votes_need_ban,
"timer": global_timer,
"timer_ban": global_timer_ban,
"min_vote": __votes_need_min,
"vote_mode": vote_mode, # Now taken from config.ini
"wait_timer": wait_timer, # Now taken from config.ini
"kill_mode": kill_mode, # Now taken from config.ini
"rate": rate, # It seems that this parameter is not used anywhere?
"public_mode": binary_chat_mode,
"allowed_admins": __ADMIN_RECOMMENDED,
"vote_privacy": vote_privacy,
"marmalade": marmalade}
__plugins = []
def __init__(self):
try:
self.path = sys.argv[1] + "/"
if not os.path.isdir(sys.argv[1]):
print("WARNING: working path IS NOT EXIST. Remake.")
os.mkdir(sys.argv[1])
except IndexError:
pass
except IOError:
traceback.print_exc()
print("ERROR: Failed to create working directory! Bot will be closed!")
sys.exit(1)
reload(logging)
logging.basicConfig(
handlers=[
logging.FileHandler(self.path + "logging.log", 'w', 'utf-8'),
logging.StreamHandler(sys.stdout)
],
level=logging.INFO,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt="%d-%m-%Y %H:%M:%S")
sys.excepthook = log_uncaught_exceptions
if not os.path.isfile(self.path + "config.ini"):
print("Config file isn't found! Trying to remake!")
self.remake_conf()
config = configparser.ConfigParser()
while True:
try:
config.read(self.path + "config.ini")
self.token = config["Chat"]["token"]
self.vote_mode = int(config["Chat"]["votes-mode"])
self.wait_timer = int(config["Chat"]["wait-timer"])
self.kill_mode = int(config["Chat"]["kill-mode"])
self.fixed_rules = self.bool_init(config["Chat"]["fixed-rules"])
self.rate = self.bool_init(config["Chat"]["rate"])
self.admin_fixed = self.bool_init(config["Chat"]["admin-fixed"])
self.chat_mode = config["Chat"]["chat-mode"]
if config["Chat"]["chat-id"] != "init":
self.main_chat_id = int(config["Chat"]["chat-id"])
else:
self.debug = True
self.main_chat_id = -1
if self.admin_fixed:
admin_allowed = {}
for name in self.__ADMIN_RECOMMENDED.keys():
admin_allowed.update({
name: self.bool_init(config["Admin-rules"][name.replace("_", "-")])
})
self.admin_allowed = admin_allowed
break
except Exception as e:
logging.error((str(e)))
logging.error(traceback.format_exc())
time.sleep(1)
print("\nInvalid config file! Trying to remake!")
agreement = "-1"
while agreement != "y" and agreement != "n" and agreement != "":
agreement = input("Do you want to reset your broken config file on defaults? (Y/n): ")
agreement = agreement.lower()
if agreement == "" or agreement == "y":
self.remake_conf()
else:
sys.exit(0)
if self.chat_mode not in ["private", "mixed", "public", "captcha"]:
self.chat_mode = "mixed"
logging.warning(f"Incorrect chat-mode value, reset to default (mixed)")
if self.chat_mode == "private":
self.binary_chat_mode = 0
elif self.chat_mode == "public":
self.binary_chat_mode = 1
elif self.chat_mode == "captcha":
self.binary_chat_mode = 2
try:
self.debug = self.bool_init(config["Chat"]["debug"])
except (KeyError, TypeError):
pass
try:
self.thread_id = int(config["Chat"]["thread-id"])
except (KeyError, TypeError, ValueError):
pass
if self.debug:
self.wait_timer = 0
def sql_worker_get(self):
self.__votes_need = sqlWorker.params("votes") # Обращение к глобальной переменной((((
self.__votes_need_ban = sqlWorker.params("votes_ban")
self.__votes_need_min = sqlWorker.params("min_vote")
self.global_timer = sqlWorker.params("timer")
self.global_timer_ban = sqlWorker.params("timer_ban")
self.vote_privacy = sqlWorker.params("vote_privacy")
# Start of backwards compatible code
if not self.admin_fixed:
admin_allowed = sqlWorker.params("allowed_admins")
if not isinstance(admin_allowed, dict):
sqlWorker.params("allowed_admins", rewrite_value=self.__ADMIN_RECOMMENDED)
elif admin_allowed.get("can_manage_chat"):
admin_allowed.pop("can_manage_chat")
sqlWorker.params("allowed_admins", rewrite_value=admin_allowed)
self.admin_allowed = admin_allowed
else:
self.admin_allowed = admin_allowed
# End of backwards compatible code
if self.chat_mode == "mixed":
self.binary_chat_mode = sqlWorker.params("public_mode")
if self.debug:
self.global_timer = 20
self.global_timer_ban = 10
self.__votes_need = 2
self.__votes_need_ban = 2
self.__votes_need_min = 1
@staticmethod
def bool_init(var):
if var.lower() in ("false", "0"):
return False
elif var.lower() in ("true", "1"):
return True
else:
raise TypeError
def auto_thresholds_get(self, ban=False, minimum=False):
try:
member_count = bot.get_chat_members_count(self.main_chat_id)
except telebot.apihelper.ApiTelegramException as e:
logging.error(e)
member_count = 2
if ban:
if member_count > 15:
votes_need_ban = 5
elif member_count > 5:
votes_need_ban = 3
else:
votes_need_ban = 2
if votes_need_ban < self.__votes_need_min:
return self.__votes_need_min
return votes_need_ban
elif minimum:
if member_count > 30:
min_value = 5
elif member_count > 15:
min_value = 3
else:
min_value = 2
if self.__votes_need < min_value:
self.__votes_need = min_value
if self.__votes_need_ban < min_value:
self.__votes_need_ban = min_value
return min_value
else:
votes_need = member_count // 2
if votes_need < self.__votes_need_min:
return self.__votes_need_min
if votes_need > 7:
return 7
if votes_need <= 1:
return 2
return votes_need
def thresholds_get(self, ban=False, minimum=False):
if ban:
if self.__votes_need_ban != 0:
return self.__votes_need_ban
else:
return self.auto_thresholds_get(ban)
elif minimum:
if self.__votes_need_min != 0:
return self.__votes_need_min
else:
return self.auto_thresholds_get(False, minimum)
else:
if self.__votes_need != 0:
return self.__votes_need
else:
return self.auto_thresholds_get()
def is_thresholds_auto(self, ban=False, minimum=False):
if ban:
if not self.__votes_need_ban:
return True
return False
elif minimum:
if not self.__votes_need_min:
return True
return False
else:
if not self.__votes_need:
return True
return False
def thresholds_set(self, value, ban=False, minimum=False):
if ban:
self.__votes_need_ban = value
if not self.debug:
sqlWorker.params("votes_ban", value)
elif minimum:
self.__votes_need_min = value
if self.__votes_need_ban < self.thresholds_get(False, True) and self.__votes_need_ban:
self.__votes_need_ban = value
if self.__votes_need < self.thresholds_get(False, True) and self.__votes_need:
self.__votes_need = value
if not self.debug:
sqlWorker.params("min_vote", value)
else:
self.__votes_need = value
if not self.debug:
sqlWorker.params("votes", value)
def timer_set(self, value, ban=False):
if ban:
self.global_timer_ban = value
if not self.debug:
sqlWorker.params("timer_ban", value)
else:
self.global_timer = value
if not self.debug:
sqlWorker.params("timer", value)
def remake_conf(self):
token, chat_id = "", ""
while token == "":
token = input("Please, write your bot token: ")
while chat_id == "":
chat_id = input('Please enter ID of your chat or "init" to enter initialization mode: ')
config = configparser.ConfigParser()
config.add_section("Chat")
config.set("Chat", "token", token)
config.set("Chat", "chat-id", chat_id)
config.set("Chat", "votes-mode", "3")
config.set("Chat", "wait-timer", "30")
config.set("Chat", "kill-mode", "2")
config.set("Chat", "fixed-rules", "false")
config.set("Chat", "rate", "true")
config.set("Chat", "admin-fixed", "false")
config.set("Chat", "chat-mode", "mixed")
config.set("Chat", "thread-id", "none")
config.add_section("Admin-rules")
for name, value in self.__ADMIN_RECOMMENDED.items():
config.set("Admin-rules", name.replace("_", "-"), str(value).lower())
try:
config.write(open(self.path + "config.ini", "w"))
print("New config file was created successful")
except IOError:
print("ERR: Bot cannot write new config file and will close")
logging.error(traceback.format_exc())
sys.exit(1)
@property
def plugins(self):
return self.__plugins
@plugins.setter
def plugins(self, value):
if not isinstance(value, list):
return
self.__plugins = value
@property
def admin_rus(self):
return self.__ADMIN_RUS
class Helper:
__help_json: dict
def __init__(self):
try:
with open("help.json", encoding='utf-8') as f:
self.__help_json = json.load(f)
except (IOError, json.decoder.JSONDecodeError):
logging.error("Error reading JSON help file! Bot will be closed.")
logging.error(traceback.format_exc())
sys.exit(1)
@property
def help_json(self):
return self.__help_json
def get_main_list(self):
output = "<b>Выберите категорию команд:</b>\n\n<blockquote expandable>"
buttons_main_row = []
buttons_main = []
for index, category in enumerate(self.help_json['category']):
buttons_main_row.append(types.InlineKeyboardButton(text=str(index + 1), callback_data=f"help!_cat_{index}"))
if len(buttons_main_row) > 3:
buttons_main.append(buttons_main_row)
buttons_main_row = []
output += f"<b>{index + 1} - {html_fix(category['name'])}</b>\n"
commands_text = []
for command in category['commands']:
commands_text.append(f"<code>{html_fix(command['name'])}</code>")
if command['aliases']:
commands_text.append(f"<code>{html_fix(', '.join(command['aliases']))}</code>")
output += f'{", ".join(commands_text)}\n'
if buttons_main_row:
buttons_main.append(buttons_main_row)
output += "</blockquote>"
return output, types.InlineKeyboardMarkup(buttons_main)
def get_category_list(self, index):
output = ""
try:
category = self.help_json['category'][int(index)]
except IndexError:
raise IndexError("Category index not found")
output += f"<b>{html_fix(category['name'])}</b>\n<blockquote>"
commands_list = []
for command in category['commands']:
command_text = [html_fix(f"/{command['name']}")]
if command['aliases']:
command_text.append(f'/{html_fix("/".join(command["aliases"]))}')
if command['args']:
command_text.append("[" + html_fix("] [".join(command['args'])) + "]")
if command['mark']:
command_text.append(html_fix(f"({command['mark']})"))
commands_list.append(f"{' '.join(command_text)} - {' '.join(command['short_desc'])}")
output += "{}</blockquote>\n".format('\n'.join(commands_list))
return output, types.InlineKeyboardMarkup([[types.InlineKeyboardButton(text="На главную",
callback_data=f"help!_main")]])
data = ConfigData()
helper = Helper()
bot = telebot.TeleBot(data.token)
sqlWorker = sql_worker.SqlWorker(data.path + "database.db", data.SQL_INIT)
def init():
check_dependency_versions()
data.sql_worker_get()
try:
data.bot_id = bot.get_me().id
except Exception as e:
logging.error(f"Bot was unable to get own ID and will close - {e}")
logging.error(traceback.format_exc())
sys.exit(1)
threading.Thread(target=auto_clear, daemon=True).start()
get_version = sqlWorker.params("version", default_return=data.VERSION)
if version.parse(get_version) < version.parse(data.MIN_VERSION):
logging.error(f"You cannot upgrade from version {get_version} because compatibility is lost! "
f"Minimum version to upgrade to version {data.VERSION} - {data.MIN_VERSION}")
sys.exit(1)
elif version.parse(get_version) < version.parse(data.VERSION):
change_type = "повышение"
logging.warning(f"Version {get_version} upgraded to version {data.VERSION}")
elif version.parse(get_version) > version.parse(data.VERSION):
logging.warning("Version downgrade detected! This can lead to unpredictable consequences for the bot!")
logging.warning(f"Downgraded from {get_version} to {data.VERSION}")
change_type = "понижение"
else:
change_type = ""
try:
info = html_fix(get_last_commit_info().split('\n', maxsplit=1)[1])
if len(info) > 2000:
info = (info[:2000].rsplit(' ', 1)[0] +
'\n<i>чейнджлог коммита слишком длинный для вывода в сообщении...</i>')
info = f'Информация о последних изменениях:\n<blockquote>{info}</blockquote>'
except (FileNotFoundError, RuntimeError) as e:
if str(e) == "Folder .git not found":
logging.warning('The .git folder was not found in the bot directory.')
elif str(e) == "Command 'git' not found":
logging.warning('The "git" command was not found. Please install Git to view commit history.')
info = ('Информация о последних изменениях недоступна.\n'
'Подробная информация о причинах ошибки содержится в логах бота.')
update_text = "" if version.parse(get_version) == version.parse(data.VERSION) \
else f"\nВнимание! Обнаружено {change_type} версии.\n" \
f"Текущая версия: {data.VERSION}\n" \
f"Предыдущая версия: {get_version}\n{info}"
sqlWorker.params("version", rewrite_value=data.VERSION)
logging.info(f'###TELEBOSS {data.VERSION} "{data.CODENAME.upper()}" '
f'BUILD DATE {data.BUILD_DATE} LAUNCHED SUCCESSFULLY!###')
if data.main_chat_id == -1:
logging.warning("WARNING! BOT LAUNCHED IN INIT MODE!\n***\n"
"You need to add TeleBOSS to your chat and use the /getchat command.\n"
"The bot will automatically write information about the ID of this chat\n"
"(and topic, if necessary) to the configuration file.\n"
"Restart the bot and work with it as usual.\n***")
return
try:
if data.debug:
logging.warning("BOT LAUNCHED IN DEBUG MODE!\n***\n"
"The bot will ignore the configuration of some parameters "
"and will not record changes to them.\n***")
bot.send_message(data.main_chat_id, f"Бот запущен в режиме отладки!{update_text}",
message_thread_id=data.thread_id, parse_mode='html')
else:
bot.send_message(data.main_chat_id, f"Бот перезапущен.{update_text}",
message_thread_id=data.thread_id, parse_mode='html')
except telebot.apihelper.ApiTelegramException as e:
logging.error(f"Bot was unable to send a launch message and will be closed! "
f"Possibly the wrong value for the main chat or topic?\n{e}")
sys.exit(1)
def check_dependency_versions():
file_name = 'requirements.txt'
if not os.path.isfile(file_name):
logging.warning(f'File "{file_name}" not found. The bot\'s library version check will not be performed.')
return
with open('requirements.txt', 'r') as f:
for line in f:
if not line.strip() or line.strip().startswith('#'):
continue
req = Requirement(line.strip())
installed_ver = importlib_version(req.name)
if not req.specifier.contains(installed_ver, prereleases=True):
logging.error(f"{req.name}: installed {installed_ver}, but {req.specifier} is required\n"
"Please update the bot's dependencies before starting work. The bot will close.")
sys.exit(1)
def get_last_commit_info(count_of_commits=1, commit_index=0):
if not os.path.isdir('.git'):
raise FileNotFoundError("Folder .git not found")
try:
commits_numbers = subprocess.check_output(['git', 'rev-list', '--count', 'HEAD'],
stderr=subprocess.STDOUT, encoding='utf-8').strip()
if commit_index >= int(commits_numbers):
raise IndexError(f'Commit index exceeds total count ({commits_numbers})')
cmd = ['git', 'log', f'-{count_of_commits}', f'--skip={commit_index}',
'--pretty=format:%ad by %an%n%B_2_strip', '--date=local']
return (subprocess.check_output(cmd, stderr=subprocess.STDOUT, encoding='utf-8').
strip().replace('\n_2_strip\n', '\n\n').replace('_2_strip', '\n'))
except FileNotFoundError:
raise RuntimeError("Command 'git' not found")
except subprocess.CalledProcessError as e:
logging.error(f"Error while running 'git' command: {e}")
logging.error(traceback.format_exc())
raise RuntimeError(f"Error while running 'git' command: {e}")
def auto_clear():
while True:
records = sqlWorker.get_all_polls()
for record in records:
if record[5] + 600 < int(time.time()):
sqlWorker.rem_rec(record[0])
try:
os.remove(data.path + record[0])
except IOError:
pass
logging.info('Removed deprecated poll "' + record[0] + '"')
time.sleep(3600)
def extract_arg(text: str, num: int):
try:
return text.split()[num]
except (IndexError, AttributeError):
return None
def html_fix(text):
return text.replace('&', '&').replace('<', '<').replace('>', '>')
def username_parser(message, html=False):
if message.from_user.first_name == "":
return "DELETED USER"
if message.from_user.username == "GroupAnonymousBot":
return "ANONYMOUS ADMIN"
if message.from_user.username is None:
if message.from_user.last_name is None:
username = str(message.from_user.first_name)
else:
username = str(message.from_user.first_name) + " " + str(message.from_user.last_name)
else:
if message.from_user.last_name is None:
username = str(message.from_user.first_name) + " (@" + str(message.from_user.username) + ")"
else:
username = str(message.from_user.first_name) + " " + str(message.from_user.last_name) + \
" (@" + str(message.from_user.username) + ")"
if not html:
return username
return html_fix(username)
def username_parser_invite(message, html=False):
if message.json.get("new_chat_participant").get("username") is None:
if message.json.get("new_chat_participant").get("last_name") is None:
username = message.json.get("new_chat_participant").get("first_name")
else:
username = message.json.get("new_chat_participant").get("first_name") + " " \
+ message.json.get("new_chat_participant").get("last_name")
else:
if message.json.get("new_chat_participant").get("last_name") is None:
username = message.json.get("new_chat_participant").get("first_name") \
+ " (@" + message.json.get("new_chat_participant").get("username") + ")"
else:
username = message.json.get("new_chat_participant").get("first_name") + " " \
+ message.json.get("new_chat_participant").get("last_name") + \
" (@" + message.json.get("new_chat_participant").get("username") + ")"
if not html:
return username
return html_fix(username)
def username_parser_chat_member(chat_member, html=False, need_username=True):
if chat_member.user.username is None or need_username is False:
if chat_member.user.last_name is None:
username = chat_member.user.first_name
else:
username = chat_member.user.first_name + " " + chat_member.user.last_name
else:
if chat_member.user.last_name is None:
username = chat_member.user.first_name + " (@" + chat_member.user.username + ")"
else:
username = chat_member.user.first_name + " " + chat_member.user.last_name + \
" (@" + chat_member.user.username + ")"
if not html:
return username
return html_fix(username)
def reply_msg_target(message):
if message.json.get("new_chat_participant") is not None:
user_id = message.json.get("new_chat_participant").get("id")
username = username_parser_invite(message)
is_bot = message.json.get("new_chat_participant").get("is_bot")
elif message.left_chat_member is not None:
user_id = message.left_chat_member.id
is_bot = message.left_chat_member.is_bot
message.from_user = message.left_chat_member # Какие ж смешные костыли))0)))
username = username_parser(message)
else:
user_id = message.from_user.id
username = username_parser(message)
is_bot = message.from_user.is_bot
return user_id, username, is_bot
def time_parser(instr: str):
tf = {
"s": lambda x: x,
"m": lambda x: tf['s'](x) * 60,
"h": lambda x: tf['m'](x) * 60,
"d": lambda x: tf['h'](x) * 24,
"w": lambda x: tf['d'](x) * 7,
}
buf = 0
pdata = 0
for label in instr:
if label.isnumeric():
buf = buf * 10 + int(label)
else:
label = label.lower()
if label in tf:
pdata += tf[label](buf)
else:
return None
buf = 0
return pdata + buf
def formatted_timer(timer_in_second):
if timer_in_second <= 0:
return "0c."
elif timer_in_second < 60:
return time.strftime("%Sс.", time.gmtime(timer_in_second))
elif timer_in_second < 3600:
return time.strftime("%Mм. и %Sс.", time.gmtime(timer_in_second))
elif timer_in_second < 86400:
return time.strftime("%Hч., %Mм. и %Sс.", time.gmtime(timer_in_second))
else:
days = timer_in_second // 86400
timer_in_second = timer_in_second - days * 86400
return str(days) + " дн., " + time.strftime("%Hч., %Mм. и %Sс.", time.gmtime(timer_in_second))
def make_keyboard(buttons_scheme, hidden):
row_width = 2
formatted_buttons = []
for button in buttons_scheme:
if "vote!" in button["button_type"]:
text = button["name"]
if not hidden:
text += f' - {len(button["user_list"])}'
formatted_buttons.append(types.InlineKeyboardButton(text=text, callback_data=button["button_type"]))
elif button["button_type"] == "row_width":
row_width = button["row_width"] # Феерически убогий костыль, но мне нравится))))
else:
formatted_buttons.append(types.InlineKeyboardButton(
text=button["name"], callback_data=button["button_type"]))
keyboard = types.InlineKeyboardMarkup(row_width=row_width)
keyboard.add(*formatted_buttons)
return keyboard
def vote_make(text, message, buttons_scheme, add_user, direct, hidden):
if add_user:
vote_message = bot.send_message(data.main_chat_id, text, reply_markup=make_keyboard(
buttons_scheme, hidden), parse_mode="html", message_thread_id=data.thread_id)
elif direct:
vote_message = bot.send_message(message.chat.id, text, reply_markup=make_keyboard(
buttons_scheme, hidden), parse_mode="html", message_thread_id=message.message_thread_id)
else:
vote_message = bot.reply_to(message, text, reply_markup=make_keyboard(
buttons_scheme, hidden), parse_mode="html")
return vote_message
def bot_name_checker(message, get_chat=False) -> bool:
"""Crutch to prevent the bot from responding to other bots commands"""
if message.text is None:
return True
if (data.main_chat_id != -1) == get_chat:
return False
cmd_text = message.text.split()[0]
cmd_list = cmd_text.split('@', maxsplit=1)
return len(cmd_list) == 1 or bot.get_me().username == cmd_list[-1]
def poll_saver(unique_id, message_vote):
try:
with open(data.path + unique_id, 'wb') as poll:
pickle.dump(message_vote, poll, protocol=4)
except (IOError, pickle.PicklingError):
logging.error("Failed to picking a poll! You will not be able to resume the timer after restarting the bot!")
logging.error(traceback.format_exc())
def allowed_list(locked=False):
lines = []
for name, value in data.admin_allowed.items():
status = "✅" if value else ("🔒" if locked else "❌")
lines.append(f"{data.admin_rus[name]} {status}")
return "\n".join(lines)
def welcome_msg_get(username, message):
try:
file = open(data.path + "welcome.txt", 'r', encoding="utf-8")
welcome_msg = file.read().format(username, message.chat.title)
file.close()
except FileNotFoundError:
logging.warning("file \"welcome.txt\" isn't found. The standard welcome message will be used.")
welcome_msg = data.welcome_default.format(username, message.chat.title)
except (IOError, IndexError):
logging.error("file \"welcome.txt\" isn't readable. The standard welcome message will be used.")
logging.error(traceback.format_exc())
welcome_msg = data.welcome_default.format(username, message.chat.title)
if welcome_msg == "":
logging.warning("file \"welcome.txt\" is empty. The standard welcome message will be used.")
welcome_msg = data.welcome_default.format(username, message.chat.title)
return welcome_msg
def write_init_chat(message):
config = configparser.ConfigParser()
try:
config.read(data.path + "config.ini")
config.set("Chat", "chat-id", str(message.chat.id))
if message.message_thread_id is not None:
config.set("Chat", "thread-id", str(message.message_thread_id))
thread_ = " и темы "
else:
thread_ = " "
config.set("Chat", "thread-id", "none")
config.write(open(data.path + "config.ini", "w"))
bot.reply_to(message, f"ID чата{thread_}сохранён. "
"Теперь требуется перезапустить бота для перехода в нормальный режим.")
except Exception as e:
logging.error(str(e) + "\n" + traceback.format_exc())
bot.reply_to(message, "Ошибка обновления конфига! Информация сохранена в логи бота!")
def topic_reply_fix(message): # Опять эти конченые из тг мне насрали
if not message or message.content_type == "forum_topic_created":
return None
return message
def command_forbidden(message, not_in_private_dialog=False, text=None):
if not_in_private_dialog and message.chat.id == message.from_user.id:
text = text or "Данную команду невозможно запустить в личных сообщениях."
bot.reply_to(message, text)
return True
elif not_in_private_dialog:
return False
elif message.chat.id != data.main_chat_id:
text = text or "Данную команду можно запустить только в основном чате."
bot.reply_to(message, text)
return True
return None
def get_hash(user_id, chat_instance, button_data) -> str:
for button in button_data:
if button["button_type"] == "user_votes":
return user_id
return hashlib.pbkdf2_hmac('sha256', str(user_id).encode('utf-8'),
chat_instance.encode('utf-8'), 100000, 16).hex()
def button_anonymous_checker(user_id, chat_id):
try:
for admin in bot.get_chat_administrators(chat_id):
if admin.user.id == user_id:
if admin.is_anonymous:
return True
return False
except telebot.apihelper.ApiTelegramException as e:
logging.error(f"Error checking user with ID {user_id} for being an anonymous administrator.\n{e}")
return None
def make_mailing(vote_type, message_vote_id, current_timer):
mailing_list = sqlWorker.mailing_get_all()
if not mailing_list:
return
if bot.get_chat(data.main_chat_id).username is not None:
format_chat_id = bot.get_chat(data.main_chat_id).username
else:
format_chat_id = "c/" + str(data.main_chat_id)[4:]
for subscriber_index in range(len(mailing_list)):
if not subscriber_index % 10 and subscriber_index:
time.sleep(10) # Protection against too many requests
subscriber = mailing_list[subscriber_index][0]
if bot.get_chat_member(data.main_chat_id, subscriber).status in ("left", "kicked"):
sqlWorker.mailing(subscriber, remove=True)
logging.warning(f"The user with ID {subscriber} is no longer a member of "
f"the chat and has been excluded from mailing list.")
continue
try:
bot.send_message(subscriber,
f"<b>Было запущено новое голосование!</b>\n\nТип голосования: {vote_type}, "
f"длительность: {formatted_timer(current_timer)}\n"
f"Ссылка на голосование: https://t.me/{format_chat_id}/{message_vote_id}",
parse_mode='html')
except telebot.apihelper.ApiTelegramException as e:
logging.error(f"Errors sending mailing to user with ID {subscriber}, "
f"he will be excluded from the mailing list.\n{e}")
sqlWorker.mailing(subscriber, remove=True)
def register_commands(plugins_command_list, built_in_command_list):
for command_list in (plugins_command_list, built_in_command_list):
for command, command_data in command_list.items():
commands_list = [command]
if command_data.aliases:
commands_list.extend(command_data.aliases)
handler_dict = {
'function': command_data.command_func,
'filters': {'commands': commands_list}
}
bot.add_message_handler(handler_dict)
def calc_engine(calc_text, to_send):
try:
result = eval(calc_text.replace(',', '.').replace('^', '**'))
if isinstance(result, float):
result = round(result, 10)
if result.is_integer():
result = int(result)
result = str(result)
except SyntaxError:
to_send.put("Неверно введено выражение для вычисления.")
return
except ZeroDivisionError:
to_send.put(f"{calc_text}\n=деление на 0")
return
except ValueError as e:
if 'Exceeds the limit' in str(e):
to_send.put("Результат слишком большой для отправки.")
else:
logging.error(traceback.format_exc())
to_send.put("Неизвестная ошибка вычисления! Информация сохранена в логи бота.")
return
result = result.replace('.', ',') if calc_text.count(',') >= calc_text.count('.') else result
to_send.put(f"{calc_text}\n=<code>{result}</code>")