forked from F33RNI/GPT-Telegramus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BotHandler.py
1693 lines (1431 loc) · 73 KB
/
BotHandler.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) 2022 Fern Lane, GPT-Telegramus
Licensed under the GNU Affero General Public License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/agpl-3.0.en.html
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
import asyncio
import datetime
import logging
import multiprocessing
import threading
import time
from typing import List, Dict
import telegram
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters, CallbackQueryHandler
import LoggingHandler
import ProxyAutomation
import QueueHandler
import RequestResponseContainer
import UsersHandler
from main import __version__
# User commands
BOT_COMMAND_START = "start"
BOT_COMMAND_HELP = "help"
BOT_COMMAND_CHATGPT = "chatgpt"
BOT_COMMAND_EDGEGPT = "bing"
BOT_COMMAND_DALLE = "dalle"
BOT_COMMAND_BARD = "bard"
BOT_COMMAND_BING_IMAGEGEN = "bingigen"
BOT_COMMAND_MODULE = "module"
BOT_COMMAND_STYLE = "style"
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"
# List of markdown chars to escape with \\
MARKDOWN_ESCAPE = ["_", "*", "[", "]", "(", ")", "~", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"]
MARKDOWN_ESCAPE_MINIMUM = ["_", "[", "]", "(", ")", "~", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"]
MARKDOWN_MODE_ESCAPE_NONE = 0
MARKDOWN_MODE_ESCAPE_MINIMUM = 1
MARKDOWN_MODE_ESCAPE_ALL = 2
MARKDOWN_MODE_NO_MARKDOWN = 3
# After how many seconds restart bot polling if error occurs
RESTART_ON_ERROR_DELAY = 30
# How long to wait to clear conversation
CLEAR_CONVERSATION_TIMEOUT_S = 20
def build_menu(buttons, n_cols=1, header_buttons=None, footer_buttons=None):
"""
Returns a list of inline buttons used to generate inlinekeyboard responses
:param buttons: list of InlineKeyboardButton
:param n_cols: Number of columns (number of list of buttons)
:param header_buttons: First button value
:param footer_buttons: Last button value
:return: list of inline buttons
"""
buttons = [button for button in buttons if button is not None]
menu = [buttons[i: i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if footer_buttons:
menu.append(footer_buttons)
return menu
def async_helper(awaitable_) -> None:
"""
Runs async function inside sync
:param awaitable_:
:return:
"""
# Try to get current event loop
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
# Check it
if loop and loop.is_running():
loop.create_task(awaitable_)
# We need new event loop
else:
asyncio.run(awaitable_)
async def send_message_async(config: dict, messages: List[Dict],
request_response: RequestResponseContainer.RequestResponseContainer,
end=False):
"""
Sends new message or edits current one
:param config:
:param messages:
:param request_response:
:param end:
:return:
"""
try:
# Get user language
lang = UsersHandler.get_key_or_none(request_response.user, "lang", 0)
# Fix empty message
if end:
if not request_response.response \
or (type(request_response.response) == list and len(request_response.response) == 0) \
or (type(request_response.response) == str and len(request_response.response.strip()) <= 0):
request_response.response = messages[lang]["empty_message"]
# Reset message parts if new response is smaller than previous one (EdgeGPT API bug)
# TODO: Fix API code instead
if len(request_response.response) < request_response.response_raw_len_last:
request_response.response_part_positions = [0]
request_response.response_part_counter = 0
request_response.response_raw_len_last = len(request_response.response)
# Split large response into parts (by index)
if type(request_response.response) == str and len(request_response.response) > 0:
while True:
index_start = request_response.response_part_positions[-1]
response_part_length = len(request_response.response[index_start:])
if response_part_length > config["telegram"]["one_message_limit"]:
request_response.response_part_positions \
.append(index_start + config["telegram"]["one_message_limit"])
else:
break
# The last message
if end:
# Generate regenerate button
button_regenerate = InlineKeyboardButton(messages[lang]["button_regenerate"],
callback_data="{0}_regenerate_{1}".format(
request_response.request_type,
request_response.reply_message_id))
buttons = [button_regenerate]
# Generate continue button (for ChatGPT only)
if request_response.request_type == RequestResponseContainer.REQUEST_TYPE_CHATGPT:
# Check if there is no error
if not request_response.error:
button_continue = InlineKeyboardButton(messages[lang]["button_continue"],
callback_data="{0}_continue_{1}".format(
request_response.request_type,
request_response.reply_message_id))
buttons.append(button_continue)
# Add clear button for all modules except DALL-E and Bing ImageGen
if not request_response.request_type == RequestResponseContainer.REQUEST_TYPE_DALLE \
and not request_response.request_type == RequestResponseContainer.REQUEST_TYPE_BING_IMAGEGEN:
button_clear = InlineKeyboardButton(messages[lang]["button_clear"],
callback_data="{0}_clear_{1}".format(
request_response.request_type,
request_response.reply_message_id))
buttons.append(button_clear)
# Add change style button for EdgeGPT
if request_response.request_type == RequestResponseContainer.REQUEST_TYPE_EDGEGPT:
button_style = InlineKeyboardButton(messages[lang]["button_style_change"],
callback_data="{0}_style_{1}".format(
request_response.request_type,
request_response.reply_message_id))
buttons.append(button_style)
# Add change module button for all modules
button_module = InlineKeyboardButton(messages[lang]["button_module"],
callback_data="-1_module_{0}".format(
request_response.reply_message_id))
buttons.append(button_module)
# Construct markup
request_response.reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=2))
# Send message as image
if (request_response.request_type == RequestResponseContainer.REQUEST_TYPE_DALLE
or request_response.request_type == RequestResponseContainer.REQUEST_TYPE_BING_IMAGEGEN) \
and not request_response.error:
# Single photo
if type(request_response.response) == str:
request_response.message_id = (await (telegram.Bot(config["telegram"]["api_key"]).sendPhoto(
chat_id=request_response.user["user_id"],
photo=request_response.response,
reply_to_message_id=request_response
.reply_message_id,
reply_markup=request_response.reply_markup))) \
.message_id
# Multiple photos (send media group + markup as seperate messages)
else:
# Collect media group
media_group = []
for url in request_response.response:
media_group.append(InputMediaPhoto(media=url))
# Send it
media_group_message_id = (await (telegram.Bot(config["telegram"]["api_key"]).sendMediaGroup(
chat_id=request_response.user["user_id"],
media=media_group,
reply_to_message_id=request_response.reply_message_id)))[0].message_id
# Send reply markup and get message ID
request_response.message_id = await send_reply(config["telegram"]["api_key"],
request_response.user["user_id"],
messages[lang]["media_group_response"]
.format(request_response.request),
media_group_message_id,
markdown=False,
reply_markup=request_response.reply_markup,
edit_message_id=request_response.message_id)
# Send message as text
else:
await _send_text_async_split(config, request_response, end)
# First or any other message (text only)
else:
# Get current time
time_current = time.time()
# It's time to edit message, and we have any text to send, and we have new text
if time_current - request_response.response_send_timestamp_last \
>= config["telegram"]["edit_message_every_seconds_num"] \
and len(request_response.response.strip()) > 0 \
and (request_response.response_len_last <= 0 or len(request_response.response.strip())
!= request_response.response_len_last):
# Generate stop button if it's the first message
if request_response.message_id is None or request_response.message_id < 0:
button_stop = InlineKeyboardButton(messages[lang]["button_stop_generating"],
callback_data="{0}_stop_{1}".format(
request_response.request_type,
request_response.reply_message_id))
request_response.reply_markup = InlineKeyboardMarkup(build_menu([button_stop]))
await _send_text_async_split(config, request_response, end)
# Save new data
request_response.response_len_last = len(request_response.response.strip())
request_response.response_send_timestamp_last = time_current
# Error?
except Exception as e:
logging.warning("Error sending message!", exc_info=e)
# Save current timestamp to container
request_response.response_timestamp = time.time()
async def _send_text_async_split(config: dict,
request_response: RequestResponseContainer.RequestResponseContainer,
end=False):
"""
Sends text in multiple messages if needed (must be previously split)
:param config:
:param request_response:
:param end:
:return:
"""
# Send all parts of message
response_part_counter_init = request_response.response_part_counter
while True:
# Get current part of response
response_part_index_start \
= request_response.response_part_positions[request_response.response_part_counter]
response_part_index_stop = len(request_response.response)
if request_response.response_part_counter < len(request_response.response_part_positions) - 1:
response_part_index_stop \
= request_response.response_part_positions[request_response.response_part_counter + 1]
response_part \
= request_response.response[response_part_index_start:response_part_index_stop].strip()
# Get message ID to reply to
reply_to_id = request_response.reply_message_id
if request_response.message_id >= 0 and request_response.response_part_counter > 0:
reply_to_id = request_response.message_id
edit_id = None
# Edit last message if first loop enter
if response_part_counter_init == request_response.response_part_counter:
edit_id = request_response.message_id
# Check if it is not empty
if len(response_part) > 0:
# Send with markup and exit from loop if it's the last part
if response_part_index_stop == len(request_response.response):
# Add cursor symbol?
if not end and config["telegram"]["add_cursor_symbol"]:
response_part += config["telegram"]["cursor_symbol"]
request_response.message_id = await send_reply(config["telegram"]["api_key"],
request_response.user["user_id"],
response_part,
reply_to_id,
markdown=True,
reply_markup=request_response.reply_markup,
edit_message_id=edit_id)
break
# Send as new message without markup and increment counter
else:
request_response.message_id = await send_reply(config["telegram"]["api_key"],
request_response.user["user_id"],
response_part,
reply_to_id,
markdown=True,
reply_markup=None,
edit_message_id=edit_id)
request_response.response_part_counter += 1
# Exit from loop if no response in current part
else:
break
async def send_reply(api_key: str, chat_id: int, message: str, reply_to_message_id: int | None,
markdown=False, reply_markup=None, edit_message_id=None):
"""
Sends reply to chat
:param api_key: Telegram bot API key
:param chat_id: Chat id to send to
:param message: Message to send
:param reply_to_message_id: Message ID to reply on
:param markdown: True to parse as markdown
:param reply_markup: Buttons
:param edit_message_id: Set message id to edit it instead of sending a new one
:return: message_id if sent correctly, or None if not
"""
# Send as markdown
if markdown:
# MARKDOWN_MODE_ESCAPE_NONE
message_id = await _send_parse(api_key, chat_id, message, reply_to_message_id,
MARKDOWN_MODE_ESCAPE_NONE, reply_markup, edit_message_id)
if message_id is None or message_id < 0:
# MARKDOWN_MODE_ESCAPE_MINIMUM
message_id = await _send_parse(api_key, chat_id, message, reply_to_message_id,
MARKDOWN_MODE_ESCAPE_MINIMUM, reply_markup, edit_message_id)
if message_id is None or message_id < 0:
# MARKDOWN_MODE_ESCAPE_ALL
message_id = await _send_parse(api_key, chat_id, message, reply_to_message_id,
MARKDOWN_MODE_ESCAPE_ALL, reply_markup, edit_message_id)
if message_id is None or message_id < 0:
# MARKDOWN_MODE_NO_MARKDOWN
message_id = await _send_parse(api_key, chat_id, message, reply_to_message_id,
MARKDOWN_MODE_NO_MARKDOWN, reply_markup, edit_message_id)
if message_id is None or message_id < 0:
raise Exception("Unable to send message in any markdown escape mode!")
else:
return message_id
else:
return message_id
else:
return message_id
else:
return message_id
# Markdown parsing is disabled - send as plain message
else:
return await _send_parse(api_key, chat_id, message, reply_to_message_id,
MARKDOWN_MODE_NO_MARKDOWN, reply_markup, edit_message_id)
async def _send_parse(api_key: str, chat_id: int, message: str, reply_to_message_id: int | None, escape_mode: int,
reply_markup, edit_message_id):
"""
Parses message and sends it as reply
:param api_key:
:param chat_id:
:param message:
:param reply_to_message_id:
:param escape_mode:
:param reply_markup:
:param edit_message_id:
:return: message_id if sent correctly, or None if not
"""
try:
# Escape some chars
if escape_mode == MARKDOWN_MODE_ESCAPE_MINIMUM:
for i in range(len(MARKDOWN_ESCAPE_MINIMUM)):
escape_char = MARKDOWN_ESCAPE_MINIMUM[i]
message = message.replace(escape_char, "\\" + escape_char)
# Escape all chars
elif escape_mode == MARKDOWN_MODE_ESCAPE_ALL:
for i in range(len(MARKDOWN_ESCAPE)):
escape_char = MARKDOWN_ESCAPE[i]
message = message.replace(escape_char, "\\" + escape_char)
# Create parse mode
parse_mode = None if escape_mode == MARKDOWN_MODE_NO_MARKDOWN else "MarkdownV2"
# Send as new message
if edit_message_id is None or edit_message_id < 0:
message_id = (await telegram.Bot(api_key).sendMessage(chat_id=chat_id,
text=message,
reply_to_message_id=reply_to_message_id,
parse_mode=parse_mode,
reply_markup=reply_markup,
disable_web_page_preview=True)).message_id
# Edit current message
else:
message_id = (await telegram.Bot(api_key).editMessageText(chat_id=chat_id,
text=message,
message_id=edit_message_id,
parse_mode=parse_mode,
reply_markup=reply_markup,
disable_web_page_preview=True)).message_id
# Seems OK
return message_id
except Exception as e:
if escape_mode < MARKDOWN_MODE_NO_MARKDOWN:
logging.warning("Error sending reply with escape_mode {0}: {1}\t You can ignore this message"
.format(escape_mode, str(e)))
else:
logging.error("Error sending reply with escape_mode {}!".format(escape_mode), exc_info=e)
return None
async def _send_safe(chat_id: int, text: str, context: ContextTypes.DEFAULT_TYPE,
reply_to_message_id=None, reply_markup=None):
"""
Sends message without raising any error
:param chat_id:
:param text:
:param context:
:param reply_to_message_id:
:param reply_markup:
:return:
"""
try:
await context.bot.send_message(chat_id=chat_id,
text=text.replace("\\n", "\n").replace("\\t", "\t"),
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup,
disable_web_page_preview=True)
except Exception as e:
logging.error("Error sending {0} to {1}!".format(text.replace("\\n", "\n").replace("\\t", "\t"), chat_id),
exc_info=e)
def clear_conversation_process(logging_queue: multiprocessing.Queue, str_or_exception_queue: multiprocessing.Queue,
request_type: int, config: dict, messages: List[Dict], proxy: str,
users_handler, user: dict, chatgpt_module, bard_module, edgegpt_module) -> None:
"""
Clears conversation with user (must be called in new process)
:param logging_queue:
:param str_or_exception_queue:
:param request_type:
:param config:
:param messages:
:param proxy:
:param users_handler:
:param user:
:param chatgpt_module:
:param bard_module:
:param edgegpt_module:
:return:
"""
# Setup logging for current process
LoggingHandler.worker_configurer(logging_queue)
try:
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Clear ChatGPT
if request_type == RequestResponseContainer.REQUEST_TYPE_CHATGPT:
requested_module = messages[lang]["modules"][0]
if not chatgpt_module.processing_flag.value:
proxy_ = None
if proxy and config["chatgpt"]["proxy"] == "auto":
proxy_ = proxy
chatgpt_module.initialize(proxy_)
chatgpt_module.clear_conversation_for_user(users_handler, user)
chatgpt_module.exit()
else:
raise Exception("The module is busy. Please try again later!")
# Clear EdgeGPT
elif request_type == RequestResponseContainer.REQUEST_TYPE_EDGEGPT:
requested_module = messages[lang]["modules"][2]
if not edgegpt_module.processing_flag.value:
edgegpt_module.clear_conversation_for_user(user)
else:
raise Exception("The module is busy. Please try again later!")
# Clear Bard
elif request_type == RequestResponseContainer.REQUEST_TYPE_BARD:
requested_module = messages[lang]["modules"][3]
if not bard_module.processing_flag.value:
bard_module.clear_conversation_for_user(user)
else:
raise Exception("The module is busy. Please try again later!")
# Wrong module
else:
raise Exception("Wrong module type: {}".format(request_type))
# Return module name if everything is OK
str_or_exception_queue.put(requested_module)
# Return exception
except Exception as e:
str_or_exception_queue.put(e)
class BotHandler:
def __init__(self, config: dict, messages: List[Dict],
users_handler: UsersHandler.UsersHandler,
queue_handler: QueueHandler.QueueHandler,
proxy_automation: ProxyAutomation.ProxyAutomation,
logging_queue: multiprocessing.Queue,
chatgpt_module, bard_module, edgegpt_module):
self.config = config
self.messages = messages
self.users_handler = users_handler
self.queue_handler = queue_handler
self.proxy_automation = proxy_automation
self.logging_queue = logging_queue
self.chatgpt_module = chatgpt_module
self.bard_module = bard_module
self.edgegpt_module = edgegpt_module
self._application = None
self._event_loop = None
self._restart_requested_flag = False
self._exit_flag = False
self._response_loop_thread = None
def start_bot(self):
"""
Starts bot (blocking)
:return:
"""
# Start response_loop as thread
# self._response_loop_thread = threading.Thread(target=self._response_loop)
# self._response_loop_thread.start()
# logging.info("response_loop thread: {0}".format(self._response_loop_thread.name))
# Start telegram bot polling
logging.info("Starting telegram bot")
while True:
try:
# Build bot
builder = ApplicationBuilder().token(self.config["telegram"]["api_key"])
self._application = builder.build()
# User commands
self._application.add_handler(CommandHandler(BOT_COMMAND_START, self.bot_command_start))
self._application.add_handler(CommandHandler(BOT_COMMAND_HELP, self.bot_command_help))
self._application.add_handler(CommandHandler(BOT_COMMAND_CHATGPT, self.bot_command_chatgpt))
self._application.add_handler(CommandHandler(BOT_COMMAND_EDGEGPT, self.bot_command_edgegpt))
self._application.add_handler(CommandHandler(BOT_COMMAND_DALLE, self.bot_command_dalle))
self._application.add_handler(CommandHandler(BOT_COMMAND_BARD, self.bot_command_bard))
self._application.add_handler(CommandHandler(BOT_COMMAND_BING_IMAGEGEN, self.bot_command_bing_imagegen))
self._application.add_handler(CommandHandler(BOT_COMMAND_MODULE, self.bot_command_module))
self._application.add_handler(CommandHandler(BOT_COMMAND_STYLE, self.bot_command_style))
self._application.add_handler(CommandHandler(BOT_COMMAND_CLEAR, self.bot_command_clear))
self._application.add_handler(CommandHandler(BOT_COMMAND_LANG, self.bot_command_lang))
self._application.add_handler(CommandHandler(BOT_COMMAND_CHAT_ID, self.bot_command_chatid))
# Handle requests as messages
if self.config["telegram"]["reply_to_messages"]:
self._application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), self.bot_message))
self._application.add_handler(MessageHandler(filters.PHOTO & (~filters.COMMAND), self.bot_message))
# Admin commands
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
self._application.add_handler(MessageHandler(filters.COMMAND, self.bot_command_help))
# Add buttons handler
self._application.add_handler(CallbackQueryHandler(self.query_callback))
# Start bot
self._event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._event_loop)
self._event_loop.run_until_complete(self._application.run_polling())
# Exit requested
except KeyboardInterrupt:
logging.warning("KeyboardInterrupt @ bot_start")
break
# Bot error?
except Exception as e:
if "Event loop is closed" in str(e):
if not self._restart_requested_flag:
logging.warning("Stopping telegram bot")
break
else:
logging.error("Telegram bot error!", exc_info=e)
# Wait before restarting if needed
if not self._restart_requested_flag:
logging.info("Restarting bot polling after {0} seconds".format(RESTART_ON_ERROR_DELAY))
try:
time.sleep(RESTART_ON_ERROR_DELAY)
# Exit requested while waiting for restart
except KeyboardInterrupt:
logging.warning("KeyboardInterrupt @ bot_start")
break
# Restart bot
logging.info("Restarting bot polling")
self._restart_requested_flag = False
# If we're here, exit requested
logging.warning("Telegram bot stopped")
async def query_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""
reply_markup buttons callback
:param update:
:param context:
:return:
"""
try:
telegram_chat_id = update.effective_chat.id
data_ = update.callback_query.data
if telegram_chat_id and data_:
# Parse data from button
data_splitted = data_.split("_")
request_type = int(data_splitted[0])
action = data_splitted[1]
reply_message_id = int(data_splitted[2])
# Get user
user = self.users_handler.get_user_by_id(telegram_chat_id)
# Exit if banned
if user["banned"]:
return
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Regenerate request
if action == "regenerate":
# Get last message ID
reply_message_id_last = UsersHandler.get_key_or_none(user, "reply_message_id_last")
# Check if it is last message
if reply_message_id_last and reply_message_id_last == reply_message_id:
# Get request
request = UsersHandler.get_key_or_none(user, "request_last")
# Check if we have the last request
if request:
# Ask
request_image_url = UsersHandler.get_key_or_none(user, "request_last_image_url")
await self.bot_command_or_message_request_raw(request_type,
request,
user,
reply_message_id_last,
context,
request_image_url)
# No or empty request
else:
await _send_safe(user["user_id"], self.messages[lang]["regenerate_error_empty"], context)
# Message is not the last one
else:
await _send_safe(user["user_id"], self.messages[lang]["regenerate_error_not_last"], context)
# Continue generating (for ChatGPT)
elif action == "continue":
# Get last message ID
reply_message_id_last = UsersHandler.get_key_or_none(user, "reply_message_id_last")
# Check if it is last message
if reply_message_id_last and reply_message_id_last == reply_message_id:
# Ask
await self.bot_command_or_message_request_raw(request_type,
self.config["chatgpt"]["continue_request_text"],
user,
reply_message_id_last,
context)
# Message is not the last one
else:
await _send_safe(user["user_id"], self.messages[lang]["continue_error_not_last"], context)
# Stop generating
elif action == "stop":
# Get last message ID
reply_message_id_last = UsersHandler.get_key_or_none(user, "reply_message_id_last")
# Check if it is last message
if reply_message_id_last and reply_message_id_last == reply_message_id:
# Get queue as list
with self.queue_handler.lock:
queue_list = QueueHandler.queue_to_list(self.queue_handler.request_response_queue)
# Try to find out container
aborted = False
for container in queue_list:
if container.user["user_id"] == user["user_id"] \
and container.reply_message_id == reply_message_id_last:
# Change state to aborted
logging.info("Requested container {} abort".format(container.id))
container.processing_state = RequestResponseContainer.PROCESSING_STATE_CANCEL
QueueHandler.put_container_to_queue(self.queue_handler.request_response_queue,
self.queue_handler.lock, container)
aborted = True
break
# Check if we aborted request
if not aborted:
await _send_safe(user["user_id"], self.messages[lang]["stop_error"], context)
# Message is not the last one
else:
await _send_safe(user["user_id"], self.messages[lang]["stop_error_not_last"], context)
# Clear chat
elif action == "clear":
await self.bot_command_clear_raw(request_type, user, context)
# Change module
elif action == "module":
await self.bot_command_module_raw(request_type, user, context)
# Change style
elif action == "style":
await self.bot_command_style_raw(reply_message_id, user, context)
# Change language
elif action == "lang":
await self.bot_command_lang_raw(request_type, user, context)
# Error parsing data?
except Exception as e:
logging.error("Query callback error!", exc_info=e)
async def bot_command_broadcast(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""
/broadcast command
:param update:
:param context:
:return:
"""
# Get user
user = await self._user_check_get(update, context)
# Log command
logging.info("/broadcast command from {0} ({1})".format(user["user_name"], user["user_id"]))
# Exit if banned
if user["banned"]:
return
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Check for admin rules
if not user["admin"]:
await _send_safe(user["user_id"], self.messages[lang]["permissions_deny"], context)
return
# Check for message
if not context.args or len(context.args) < 1:
await _send_safe(user["user_id"], self.messages[lang]["broadcast_no_message"], context)
return
# Send initial message
await _send_safe(user["user_id"], self.messages[lang]["broadcast_initiated"], context)
# Get message
broadcast_message = str(" ".join(context.args)).strip()
# Get list of users
users = self.users_handler.read_users()
# List of successful users
broadcast_ok_users = []
# Broadcast to non-banned users
for broadcast_user in users:
if not broadcast_user["banned"]:
try:
# Try to send message and get message ID
message_id = (await telegram.Bot(self.config["telegram"]["api_key"]).sendMessage(
chat_id=broadcast_user["user_id"],
text=self.messages[lang]["broadcast"].replace("\\n", "\n").format(
broadcast_message))).message_id
# Check
if message_id is not None and message_id != 0:
logging.info("Message sent to: {0} ({1})".format(broadcast_user["user_name"],
broadcast_user["user_id"]))
broadcast_ok_users.append(broadcast_user["user_name"])
# Wait some time
time.sleep(self.config["telegram"]["broadcast_delay_per_user_seconds"])
except Exception as e:
logging.warning("Error sending message to {}!".format(broadcast_user["user_id"]), exc_info=e)
# Send final message
await _send_safe(user["user_id"],
self.messages[lang]["broadcast_done"].format("\n".join(broadcast_ok_users)),
context)
async def bot_command_ban(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await self.bot_command_ban_unban(True, update, context)
async def bot_command_unban(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await self.bot_command_ban_unban(False, update, context)
async def bot_command_ban_unban(self, ban: bool, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""
/ban, /unban commands
:param ban: True to ban, False to unban
:param update:
:param context:
:return:
"""
# Get user
user = await self._user_check_get(update, context)
# Log command
logging.info("/{0} command from {1} ({2})".format("ban" if ban else "unban",
user["user_name"],
user["user_id"]))
# Exit if banned
if user["banned"]:
return
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Check for admin rules
if not user["admin"]:
await _send_safe(user["user_id"], self.messages[lang]["permissions_deny"], context)
return
# Check user_id to ban
if not context.args or len(context.args) < 1:
await _send_safe(user["user_id"], self.messages[lang]["ban_no_user_id"], context)
return
try:
ban_user_id = int(str(context.args[0]).strip())
except Exception as e:
await _send_safe(user["user_id"], str(e), context)
return
# Get ban reason
reason = self.messages[lang]["ban_reason_default"].replace("\\n", "\n")
if len(context.args) > 1:
reason = str(" ".join(context.args[1:])).strip()
# Get user to ban
banned_user = self.users_handler.get_user_by_id(ban_user_id)
# Ban / unban
banned_user["banned"] = ban
banned_user["ban_reason"] = reason
# Save user
self.users_handler.save_user(banned_user)
# Send confirmation
if ban:
await _send_safe(user["user_id"],
self.messages[lang]["ban_message_admin"].format("{0} ({1})"
.format(banned_user["user_name"],
banned_user["user_id"]), reason),
context)
else:
await _send_safe(user["user_id"],
self.messages[lang]["unban_message_admin"].format("{0} ({1})"
.format(banned_user["user_name"],
banned_user["user_id"])),
context)
async def bot_command_users(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""
/users command
:param update:
:param context:
:return:
"""
# Get user
user = await self._user_check_get(update, context)
# Log command
logging.info("/users command from {0} ({1})".format(user["user_name"], user["user_id"]))
# Exit if banned
if user["banned"]:
return
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Check for admin rules
if not user["admin"]:
await _send_safe(user["user_id"], self.messages[lang]["permissions_deny"], context)
return
# Get list of users
users = self.users_handler.read_users()
# Sort by number of requests
users = sorted(users, key=lambda u: u["requests_total"], reverse=True)
# Add them to message
message = ""
for user_info in users:
# Banned?
if user_info["banned"]:
message += "B "
else:
message += " "
# Admin?
if user_info["admin"]:
message += "A "
else:
message += " "
# Language
message += self.messages[UsersHandler.get_key_or_none(user_info, "lang", 0)]["language_icon"] + " "
# Module
message += self.messages[0]["module_icons"][UsersHandler.get_key_or_none(user_info, "module", 0)] + " "
# User ID, name, total requests
message += "{0} ({1}) - {2}\n".format(user_info["user_id"], user_info["user_name"],
user_info["requests_total"])
# Parse as monospace
message = self.messages[lang]["users_admin"].format(message).replace("\\t", "\t").replace("\\n", "\n")
message = "```\n" + message + "\n```"
# Send list of users as markdown
await send_reply(self.config["telegram"]["api_key"],
user["user_id"],
message,
None,
markdown=True)
async def bot_command_restart(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
/restart command
:param update:
:param context:
:return:
"""
# Get user
user = await self._user_check_get(update, context)
# Log command
logging.info("/restart command from {0} ({1})".format(user["user_name"], user["user_id"]))
# Exit if banned
if user["banned"]:
return
# Get user language
lang = UsersHandler.get_key_or_none(user, "lang", 0)
# Check for admin rules
if not user["admin"]: