-
Notifications
You must be signed in to change notification settings - Fork 104
/
bot_handler.py
1917 lines (1632 loc) · 76.3 KB
/
bot_handler.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
"""
Copyright (C) 2023-2024 Fern Lane, Hanssen
This file is part of the GPT-Telegramus distribution
(see <https://github.com/F33RNI/GPT-Telegramus>)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import annotations
import asyncio
from ctypes import c_bool
import datetime
import functools
import gc
import logging
import multiprocessing
import time
from math import sqrt
from typing import Dict, Tuple
import telegram
from telegram import (
Update,
InlineKeyboardButton,
InlineKeyboardMarkup,
BotCommand,
)
from telegram.ext import (
ApplicationBuilder,
ContextTypes,
CommandHandler,
MessageHandler,
filters,
CallbackQueryHandler,
)
import requests
from _version import __version__
from main import load_and_parse_config
import bot_sender
import users_handler
import messages
import request_response_container
import queue_handler
import module_wrapper_global
from caption_command_handler import CaptionCommandHandler
# User commands
BOT_COMMAND_START = "start"
BOT_COMMAND_HELP = "help"
BOT_COMMAND_CHAT = "chat"
BOT_COMMAND_MODULE = "module"
BOT_COMMAND_STYLE = "style"
BOT_COMMAND_MODEL = "model"
BOT_COMMAND_CLEAR = "clear"
BOT_COMMAND_LANG = "lang"
BOT_COMMAND_CHAT_ID = "chatid"
# Admin-only commands
BOT_COMMAND_ADMIN_QUEUE = "queue"
BOT_COMMAND_ADMIN_RESTART = "restart"
BOT_COMMAND_ADMIN_USERS = "users"
BOT_COMMAND_ADMIN_BAN = "ban"
BOT_COMMAND_ADMIN_UNBAN = "unban"
BOT_COMMAND_ADMIN_BROADCAST = "broadcast"
# After how many seconds restart bot polling if error occurs
RESTART_ON_ERROR_DELAY = 10
async def _send_safe(
chat_id: int,
text: str,
context: ContextTypes.DEFAULT_TYPE,
reply_to_message_id: int or None = None,
reply_markup: InlineKeyboardMarkup or None = None,
markdown: bool = False,
):
"""Sends message without raising any error
Args:
chat_id (int): ID of user (or chat)
text (str): text to send
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
reply_to_message_id (int or None, optional): ID of message to reply on. Defaults to None
reply_markup (InlineKeyboardMarkup or None, optional): buttons. Defaults to None
markdown (bool, optional): True to parse as markdown. Defaults to False
"""
try:
await context.bot.send_message(
chat_id=chat_id,
text=text,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
disable_web_page_preview=True,
parse_mode="MarkdownV2" if markdown else None,
)
except Exception as e:
logging.error(f"Error sending {text} to {chat_id}", exc_info=e)
class BotHandler:
def __init__(
self,
config: Dict,
config_file: str,
messages_: messages.Messages,
users_handler_: users_handler.UsersHandler,
logging_queue: multiprocessing.Queue,
queue_handler_: queue_handler.QueueHandler,
modules: Dict,
web_cooldown_timer: multiprocessing.Value,
web_request_lock: multiprocessing.Lock,
):
self.config = config
self.config_file = config_file
self.messages = messages_
self.users_handler = users_handler_
self.logging_queue = logging_queue
self.queue_handler = queue_handler_
self.modules = modules
# LMAO
self.web_cooldown_timer = web_cooldown_timer
self.web_request_lock = web_request_lock
self.prevent_shutdown_flag = multiprocessing.Value(c_bool, False)
self._application = None
self._event_loop = None
def start_bot(self):
"""
Starts bot (blocking)
:return:
"""
while True:
try:
# Close previous event loop
# Maybe we should optimize this and everything asyncio below (inside start_bot)
try:
loop = asyncio.get_running_loop()
if loop and loop.is_running():
logging.info("Stopping current event loop before starting a new one")
loop.stop()
except Exception as e:
logging.warning(f"Error stopping current event loop: {e}")
# Create new event loop
logging.info("Creating a new event loop")
self._event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._event_loop)
# Build bot
telegram_config = self.config.get("telegram")
proxy = telegram_config.get("proxy")
if proxy:
logging.info(f"Using proxy {proxy} for Telegram bot")
builder = (
ApplicationBuilder()
.token(telegram_config.get("api_key"))
.proxy(proxy)
.get_updates_proxy(proxy)
)
else:
builder = ApplicationBuilder().token(telegram_config.get("api_key"))
self._application = builder.build()
# Set commands
self._event_loop.run_until_complete(self._set_bot_commands_list())
# User commands
logging.info("Adding user command handlers")
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_START, self.bot_command_start))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_HELP, self.bot_command_help))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_CHAT, self.bot_module_request))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_MODULE, self.bot_command_module))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_STYLE, self.bot_command_style))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_MODEL, self.bot_command_model))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_CLEAR, self.bot_command_clear))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_LANG, self.bot_command_lang))
self._application.add_handler(CaptionCommandHandler(BOT_COMMAND_CHAT_ID, self.bot_command_chatid))
# Create all possible command handlers
for module_name in module_wrapper_global.MODULES:
logging.info(f"Adding /{module_name} command handler")
self._application.add_handler(
CaptionCommandHandler(
module_name, functools.partial(self.bot_module_request, module_name=module_name)
)
)
# Handle requests as messages
if telegram_config.get("reply_to_messages"):
logging.info("Adding message handlers")
self._application.add_handler(
MessageHandler(filters.TEXT & (~filters.COMMAND), self.bot_module_request)
)
self._application.add_handler(
MessageHandler(filters.PHOTO & (~filters.COMMAND), self.bot_module_request)
)
# Admin commands
logging.info("Adding admin command handlers")
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_QUEUE, self.bot_command_queue))
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_RESTART, self.bot_command_restart))
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_USERS, self.bot_command_users))
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_BAN, self.bot_command_ban))
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_UNBAN, self.bot_command_unban))
self._application.add_handler(CommandHandler(BOT_COMMAND_ADMIN_BROADCAST, self.bot_command_broadcast))
# Unknown command -> send help
logging.info("Adding unknown command handler")
self._application.add_handler(MessageHandler(filters.COMMAND, self.bot_command_unknown))
# Add buttons handler
logging.info("Adding markup handler")
self._application.add_handler(CallbackQueryHandler(self.query_callback))
# Start telegram bot polling
logging.info("Starting bot polling")
self._application.run_polling(close_loop=False, stop_signals=[])
# Exit requested
except (KeyboardInterrupt, SystemExit):
logging.warning("KeyboardInterrupt or SystemExit @ bot_start")
break
# Bot error?
except Exception as e:
if "Event loop is closed" in str(e):
with self.prevent_shutdown_flag.get_lock():
prevent_shutdown = self.prevent_shutdown_flag.value
if not prevent_shutdown:
logging.warning("Stopping telegram bot")
break
else:
logging.error("Telegram bot error", exc_info=e)
# Restart bot
logging.info(f"Restarting bot polling after {RESTART_ON_ERROR_DELAY} seconds")
try:
time.sleep(RESTART_ON_ERROR_DELAY)
# Exit requested while waiting for restart
except (KeyboardInterrupt, SystemExit):
logging.warning("KeyboardInterrupt or SystemExit while waiting @ bot_start")
break
# Restart bot or exit from loop
with self.prevent_shutdown_flag.get_lock():
prevent_shutdown = self.prevent_shutdown_flag.value
if prevent_shutdown:
logging.info("Restarting bot polling")
else:
break
# If we're here, exit requested
logging.warning("Telegram bot stopped")
async def _set_bot_commands_list(self) -> None:
"""Sets telegram bot commands
This must be called inside start_bot() or bot_command_restart()
"""
telegram_config = self.config.get("telegram")
if telegram_config.get("commands_description_enabled"):
try:
logging.info("Trying to set bot commands")
bot_commands = []
for command_description in telegram_config.get("commands_description"):
bot_commands.append(
BotCommand(
command_description["command"],
command_description["description"],
)
)
module_icon_names = self.messages.get_message("modules")
for module_name, module in self.modules.items():
if module is None:
continue
module_icon_name = module_icon_names.get(module_name)
module_name_user = f"{module_icon_name.get('icon')} {module_icon_name.get('name')}"
bot_commands.append(
BotCommand(
module_name,
module_name_user,
)
)
await self._application.bot.set_my_commands(bot_commands)
except Exception as e:
logging.error("Error setting bot commands description", exc_info=e)
async def query_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Buttons (reply_markup) callback
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
Raises:
Exception: _description_
"""
try:
telegram_chat_id = update.effective_chat.id
data_ = update.callback_query.data
if telegram_chat_id is None or data_ is None:
return
# Parse data from markup
action, data_, argument_ = data_.split("|")
if not action:
raise Exception("No action in callback data")
if not data_:
data_ = None
if not argument_:
argument_ = None
# Get user
banned, user = await self._user_get_check(update, context, prompt_language_selection=False)
if user is None:
return
user_id = user.get("user_id")
user_name = self.users_handler.get_key(0, "user_name", "", user=user)
lang_id = self.users_handler.get_key(0, "lang_id", "eng", user=user)
# Log action
logging.info(f"{action} markup action from {user_name} ({user_id})")
# Exit if banned
if banned:
return
# Regenerate request
if action == "regenerate":
# Parse message ID
if not argument_:
reply_message_id = None
else:
reply_message_id = int(argument_.strip())
# Get last message ID
reply_message_id_last = self.users_handler.get_key(0, "reply_message_id_last", user=user)
if reply_message_id_last is None or reply_message_id_last != reply_message_id:
await _send_safe(
user_id,
self.messages.get_message("regenerate_error_not_last", lang_id=lang_id),
context,
)
return
# Get user's latest request
request_text = self.users_handler.get_key(0, "request_last", user=user)
request_image = self.users_handler.read_request_image(0, user=user)
# Check for empty request
if not request_text:
await _send_safe(
user_id,
self.messages.get_message("regenerate_error_empty", lang_id=lang_id),
context,
)
return
# Ask
await self._bot_module_request_raw(
data_,
request_text,
user_id,
reply_message_id_last,
context,
request_image,
)
# Continue generating
elif action == "continue":
# Parse message ID
if not argument_:
reply_message_id = None
else:
reply_message_id = int(argument_.strip())
# Get last message ID
reply_message_id_last = self.users_handler.get_key(0, "reply_message_id_last", user=user)
if reply_message_id_last is None or reply_message_id_last != reply_message_id:
await _send_safe(
user_id,
self.messages.get_message("continue_error_not_last", lang_id=lang_id),
context,
)
return
# Ask
await self._bot_module_request_raw(
data_,
self.config.get(data_).get("continue_request_text", "continue"),
user_id,
reply_message_id_last,
context,
)
# Send suggestion
elif action == "suggestion":
# Parse message ID
if not argument_:
reply_message_id = None
else:
reply_message_id = int(argument_.strip())
# Get last message ID
reply_message_id_last = self.users_handler.get_key(0, "reply_message_id_last", user=user)
if reply_message_id_last is None or reply_message_id_last != reply_message_id:
await _send_safe(user_id, self.messages.get_message("suggestion_error", lang_id=lang_id), context)
return
# Get module name and suggestion id
data_parts_ = data_.split("_")
suggestion_id = data_parts_[-1]
module_name_ = "_".join(data_parts_[:-1])
# Find suggestion
suggestions = self.users_handler.get_key(0, "suggestions", user=user, default_value=[])
suggestion = None
for suggestion_id_, suggestion_ in suggestions:
if suggestion_id_ == suggestion_id:
suggestion = suggestion_
break
# Check
if not suggestion:
logging.warning(f"No suggestion with ID {suggestion_id} saved")
await _send_safe(user_id, self.messages.get_message("suggestion_error", lang_id=lang_id), context)
return
# Ask
await self._bot_module_request_raw(
module_name_,
suggestion,
user_id,
reply_message_id_last,
context,
)
# Stop generating
elif action == "stop":
# Parse message ID
if not argument_:
reply_message_id = None
else:
reply_message_id = int(argument_.strip())
# Get last message ID
reply_message_id_last = self.users_handler.get_key(0, "reply_message_id_last", user=user)
if reply_message_id_last is None or reply_message_id_last != reply_message_id:
await _send_safe(
user_id,
self.messages.get_message("stop_error_not_last", lang_id=lang_id),
context,
)
return
# Get queue as list
with self.queue_handler.lock:
queue_list = queue_handler.queue_to_list(self.queue_handler.request_response_queue)
# Try to find our container
aborted = False
for container in queue_list:
if container.user_id == user_id and container.reply_message_id == reply_message_id_last:
# Request cancel
logging.info(f"Requested container {container.id} abort")
container.processing_state = request_response_container.PROCESSING_STATE_CANCEL
queue_handler.put_container_to_queue(
self.queue_handler.request_response_queue,
self.queue_handler.lock,
container,
)
aborted = True
break
# Cannot abort
if not aborted:
await _send_safe(user_id, self.messages.get_message("stop_error", lang_id=lang_id), context)
# Clear chat
elif action == "clear":
await self._bot_command_clear_raw(data_, user, context)
# Change module
elif action == "module":
await self._bot_command_module_raw(data_, user, context)
# Change style
elif action == "style":
await self._bot_command_style_raw(data_, user, context)
# Change model
elif action == "model":
await self._bot_command_model_raw(data_, argument_, user, context)
# Change language
elif action == "lang":
await self._bot_command_lang_raw(data_, user, context)
# Error parsing data?
except Exception as e:
logging.error("Query callback error", exc_info=e)
await context.bot.answer_callback_query(update.callback_query.id)
async def bot_module_request(
self, update: Update, context: ContextTypes.DEFAULT_TYPE, module_name: str or None = None
) -> None:
"""Direct module command request (/lmao_chatgpt, /gemini, ...) or message request
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
module_name (str or None, optional): name of module (command) or None in case of message. Defaults to None
"""
# Handle unknown module
if module_name:
if self.modules.get(module_name) is None:
await self.bot_command_help(update, context)
return
# Get user
banned, user = await self._user_get_check(update, context)
if user is None:
return
user_id = user.get("user_id")
user_name = self.users_handler.get_key(0, "user_name", "", user=user)
# Log command or message
if module_name:
logging.info(f"/{module_name} command from {user_name} ({user_id})")
else:
logging.info(f"Text message from {user['user_name']} ({user['user_id']})")
# Exit if banned
if banned:
return
# Check for image and download it
image = None
if update.message.photo:
try:
logging.info("Trying to download request image")
image_file_id = update.message.photo[-1].file_id
image_url = (
await telegram.Bot(self.config.get("telegram").get("api_key")).getFile(image_file_id)
).file_path
image = requests.get(image_url, timeout=60).content
except Exception as e:
logging.error(f"Error downloading request image: {e}")
# Extract text request
if update.message.caption:
request_message = update.message.caption.strip()
elif context.args is not None:
request_message = str(" ".join(context.args)).strip()
elif update.message.text:
request_message = update.message.text.strip()
else:
request_message = ""
# Process request
await self._bot_module_request_raw(
module_name,
request_message,
user_id,
update.message.message_id,
context,
image=image,
)
async def _bot_module_request_raw(
self,
module_name: str or None,
request_message: str or None,
user_id: int,
reply_message_id: int,
context: ContextTypes.DEFAULT_TYPE,
image: bytes or None = None,
) -> None:
"""Processes request to module
Args:
module_name (str or None): name of module or None to get from user's data
request_message (str or None): request text or None to just change user's default module
user_id (int): ID of user
reply_message_id (int): ID of message to reply on
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
image (bytes or None, optional): request image as bytes or None to use only text. Defaults to None
"""
# Set default user' module
if module_name:
self.users_handler.set_key(user_id, "module", module_name)
# Use user's module
else:
module_name = self.users_handler.get_key(user_id, "module", self.config.get("modules").get("default"))
lang_id = self.users_handler.get_key(user_id, "lang_id", "eng")
user_name = self.users_handler.get_key(user_id, "user_name", "")
# Check module name
if not module_name or self.modules.get(module_name) is None:
await _send_safe(
user_id,
self.messages.get_message("response_error", lang_id=lang_id).format(
error_text=f"No module named {module_name}. Please load this module or select another one"
),
context,
reply_to_message_id=reply_message_id,
)
return
# Name of module
module_icon_name = self.messages.get_message("modules", lang_id=lang_id).get(module_name)
module_name_user = f"{module_icon_name.get('icon')} {module_icon_name.get('name')}"
# Just change module
if not request_message:
await _send_safe(
user_id,
self.messages.get_message("empty_request_module_changed", lang_id=lang_id).format(
module_name=module_name_user
),
context,
)
return
# Check queue size, send message and exit in case of overflow
if self.queue_handler.request_response_queue.qsize() >= self.config.get("telegram").get("queue_max"):
await _send_safe(user_id, self.messages.get_message("queue_overflow", lang_id=lang_id), context)
return
# Format request timestamp (for data collecting)
request_timestamp = ""
if self.config.get("data_collecting").get("enabled"):
request_timestamp = datetime.datetime.now().strftime(
self.config.get("data_collecting").get("timestamp_format")
)
# Create container
logging.info("Creating new request-response container")
request_response = request_response_container.RequestResponseContainer(
user_id=user_id,
reply_message_id=reply_message_id,
module_name=module_name,
request_text=request_message,
request_image=image,
request_timestamp=request_timestamp,
)
# Add request to the queue
logging.info(f"Adding new request to {module_name} from {user_name} ({user_id}) to the queue")
queue_handler.put_container_to_queue(
self.queue_handler.request_response_queue,
self.queue_handler.lock,
request_response,
)
# Send queue position if queue size is more than 1
with self.queue_handler.lock:
queue_list = queue_handler.queue_to_list(self.queue_handler.request_response_queue)
if len(queue_list) > 1:
await _send_safe(
user_id,
self.messages.get_message("queue_accepted", lang_id=lang_id).format(
module_name=module_name_user,
queue_size=len(queue_list),
queue_max=self.config.get("telegram").get("queue_max"),
),
context,
reply_to_message_id=request_response.reply_message_id,
)
async def bot_command_restart(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""/restart command callback
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
"""
# Get user
banned, user = await self._user_get_check(update, context)
if user is None:
return
user_id = user.get("user_id")
user_name = self.users_handler.get_key(0, "user_name", "", user=user)
lang_id = self.users_handler.get_key(0, "lang_id", user=user)
# Log command
logging.info(f"/restart command from {user_name} ({user_id})")
# Exit if banned
if banned:
return
# Check for admin rules and send permissions and deny if user is not an admin
if not self.users_handler.get_key(0, "admin", False, user=user):
await _send_safe(user_id, self.messages.get_message("permissions_deny", lang_id=lang_id), context)
return
# Get requested module
requested_module = None
if context.args and len(context.args) >= 1:
try:
requested_module = context.args[0].strip().lower()
if self.modules.get(requested_module) is None:
raise Exception(f"No module named {requested_module}")
except Exception as e:
logging.error("Error retrieving requested module", exc_info=e)
await _send_safe(user_id, str(e), context)
return
# Send restarting message
logging.info("Restarting")
await _send_safe(user_id, self.messages.get_message("restarting", lang_id=lang_id), context)
# Make sure queue is empty
if self.queue_handler.request_response_queue.qsize() > 0:
logging.info("Waiting for all requests to finish")
while self.queue_handler.request_response_queue.qsize() > 0:
# Cancel all active containers (clear the queue)
self.queue_handler.lock.acquire(block=True)
queue_list = queue_handler.queue_to_list(self.queue_handler.request_response_queue)
for container in queue_list:
if container.processing_state != request_response_container.PROCESSING_STATE_ABORT:
container.processing_state = request_response_container.PROCESSING_STATE_ABORT
queue_handler.put_container_to_queue(
self.queue_handler.request_response_queue, None, container
)
self.queue_handler.lock.release()
# Check every 1s
time.sleep(1)
reload_logs = ""
# Unload selected module or all of them
for module_name, module in self.modules.items():
if module is None:
continue
if requested_module is not None and module_name != requested_module:
continue
logging.info(f"Trying to close and unload {module_name} module")
try:
module.on_exit()
self.modules[module_name] = None
reload_logs += f"Closed module {module_name}\n"
except Exception as e:
logging.error(f"Error closing {module_name} module", exc_info=e)
reload_logs += f"Error closing {module_name} module: {e}\n"
gc.collect()
# Reload configs
logging.info(f"Reloading config from {self.config_file} file")
try:
config_new = load_and_parse_config(self.config_file)
for key, value in config_new.items():
if requested_module is not None and key != requested_module:
continue
reload_logs += f"Reloaded config with key {key}\n"
self.config[key] = value
except Exception as e:
logging.error("Error reloading config", exc_info=e)
reload_logs += f"Error reloading config: {e}\n"
# Reload messages in global restart
if requested_module is None:
try:
self.messages.langs_load(self.config.get("files").get("messages_dir"))
reload_logs += "Languages reloaded\n"
except Exception as e:
logging.error("Error reloading messages", exc_info=e)
reload_logs += f"Error reloading messages: {e}\n"
# Try to load selected module or all of them
for module_name in self.config.get("modules").get("enabled"):
if requested_module is not None and module_name != requested_module:
continue
logging.info(f"Trying to load and initialize {module_name} module")
try:
use_web = (
module_name.startswith("lmao_")
and module_name in self.config.get("modules").get("lmao_web_for_modules", [])
and "lmao_web_api_url" in self.config.get("modules")
)
module = module_wrapper_global.ModuleWrapperGlobal(
module_name,
self.config,
self.messages,
self.users_handler,
self.logging_queue,
use_web=use_web,
web_cooldown_timer=self.web_cooldown_timer,
web_request_lock=self.web_request_lock,
)
self.modules[module_name] = module
reload_logs += f"Intialized and loaded {module_name} module\n"
except Exception as e:
logging.error(f"Error initializing {module_name} module: {e} Module will be ignored")
reload_logs += f"Error initializing {module_name} module: {e} Module will be ignored\n"
# Reload commands list
await self._set_bot_commands_list()
reload_logs += "Bot command description updated\n"
# Done?
logging.info("Restarting done")
await _send_safe(
user_id,
self.messages.get_message("restarting_done", lang_id=lang_id).format(reload_logs=f"```\n{reload_logs}```"),
context,
markdown=True,
)
async def bot_command_queue(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""/queue command callback
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
"""
# Get user
banned, user = await self._user_get_check(update, context)
if user is None:
return
user_id = user.get("user_id")
user_name = self.users_handler.get_key(0, "user_name", "", user=user)
lang_id = self.users_handler.get_key(0, "lang_id", user=user)
# Log command
logging.info(f"/queue command from {user_name} ({user_id})")
# Exit if banned
if banned:
return
# Check for admin rules and send permissions and deny if user is not an admin
if not self.users_handler.get_key(0, "admin", False, user=user):
await _send_safe(user_id, self.messages.get_message("permissions_deny", lang_id=lang_id), context)
return
# Get queue as list
with self.queue_handler.lock:
queue_list = queue_handler.queue_to_list(self.queue_handler.request_response_queue)
# Queue is empty
if len(queue_list) == 0:
await _send_safe(user["user_id"], self.messages.get_message("queue_empty", lang_id=lang_id), context)
return
# Format and send queue content
message = ""
counter = 1
for container in queue_list:
request_status = request_response_container.PROCESSING_STATE_NAMES[container.processing_state]
message_ = (
f"{counter} ({container.id}). {self.users_handler.get_key(container.user_id, 'user_name', '')} "
f"({container.user_id}) to {container.module_name} ({request_status}): {container.request_text}\n"
)
message += message_
counter += 1
# Send queue content with auto-splitting
request_response = request_response_container.RequestResponseContainer(
user_id=user_id,
reply_message_id=update.effective_message.id,
module_name="",
response_text=message,
)
await bot_sender.send_message_async(
self.config.get("telegram"), self.messages, request_response, end=True, plain_text=True
)
async def bot_command_clear(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""/clear commands callback
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
"""
# Get user
banned, user = await self._user_get_check(update, context)
if user is None:
return
user_id = user.get("user_id")
user_name = self.users_handler.get_key(0, "user_name", "", user=user)
lang_id = self.users_handler.get_key(0, "lang_id", user=user)
# Log command
logging.info(f"/clear command from {user_name} ({user_id})")
# Exit if banned
if banned:
return
# Get requested module
requested_module = None
if context.args and len(context.args) >= 1:
try:
requested_module = context.args[0].strip().lower()
if self.modules.get(requested_module) is None:
raise Exception(f"No module named {requested_module}")
except Exception as e:
logging.error("Error retrieving requested module", exc_info=e)
await _send_safe(
user_id,
self.messages.get_message("clear_error", lang_id=lang_id).format(error_text=e),
context,
)
return
# Clear
await self._bot_command_clear_raw(requested_module, user, context)
async def _bot_command_clear_raw(
self, module_name: str or None, user: Dict, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Clears conversation or asks user to select module to clear conversation of
Args:
module_name (str): name of module to clear conversation
user (Dict): ID of user
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback
"""
user_id = user.get("user_id")
lang_id = self.users_handler.get_key(0, "lang_id", user=user)
# Ask user
if not module_name:
module_icon_names = self.messages.get_message("modules", lang_id=lang_id)
# Build markup
buttons = []
for enabled_module_id, module in self.modules.items():
if module is None:
continue
if enabled_module_id not in module_wrapper_global.MODULES_WITH_HISTORY:
continue
buttons.append(
InlineKeyboardButton(
module_icon_names.get(enabled_module_id).get("icon")
+ " "
+ module_icon_names.get(enabled_module_id).get("name"),
callback_data=f"clear|{enabled_module_id}|",
)
)
# Send message if at least one module is available
if len(buttons) != 0:
await _send_safe(
user_id,
self.messages.get_message("clear_select_module", lang_id=lang_id),
context,
reply_markup=InlineKeyboardMarkup(bot_sender.build_menu(buttons)),
)
return
# Clear conversation
try:
logging.info(f"Trying to clear {module_name} conversation for user {user_id}")
self.modules.get(module_name).delete_conversation(user_id)
# Seems OK if no error was raised
module_icon_name = self.messages.get_message("modules", lang_id=lang_id).get(module_name)
module_name_user = f"{module_icon_name.get('icon')} {module_icon_name.get('name')}"
await _send_safe(
user_id,
self.messages.get_message("chat_cleared", lang_id=lang_id).format(module_name=module_name_user),
context,
)
# Error deleting conversation
except Exception as e:
logging.error("Error clearing conversation", exc_info=e)
await _send_safe(user_id, self.messages.get_message("clear_error").format(error_text=e), context)
async def bot_command_style(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""/style commands callback
Args:
update (Update): update object from bot's callback
context (ContextTypes.DEFAULT_TYPE): context object from bot's callback