-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
1323 lines (1127 loc) · 53.1 KB
/
Copy pathbot.py
File metadata and controls
1323 lines (1127 loc) · 53.1 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
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 NGGT.LightKeeper. All Rights Reserved.
import time
import telebot
import os
import random
import json
import mysql.connector
import django
from django.utils import timezone
# Initialize Django settings
from pathlib import Path
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'telegram_bot_django.settings')
django.setup()
BASE_DIR = Path(__file__).resolve().parent
from telegram_bot_db.models import (
MessagesModel,
PendingMessagesModel,
ProfileModel,
AnimatedMessageModel,
)
from settings.settings import *
from telebot.types import (
InlineQueryResultArticle,
InputTextMessageContent,
InlineKeyboardButton,
InlineKeyboardMarkup,
)
from telebot import util
import re
from localization import translate, get_scramble_chars
bot = telebot.TeleBot(BOT_TOKEN)
# default delay between frames in seconds
DEFAULT_FRAME_DELAY = 1
# store user states for profile interactions
user_states = {}
# Animation types with translation keys
ANIMATION_TYPES = [
('1', 'animation_type_1'), # MID Inline query result # In AddFramesMessage # Used in InlineQueryResult and AddFramesMessage
('2', 'animation_type_2'), # # In AddFramesMessage # Used in AddFramesMessage
('3', 'animation_type_3'), # TEXT Inline query result # # Used in InlineQueryResult
('4', 'animation_type_4'), # TEXT Inline query result # # Used in InlineQueryResult
('5', 'animation_type_5'), # # In AddFramesMessage # Used in AddFramesMessage
('6', 'animation_type_6'), # # In AddFramesMessage # Used in AddFramesMessage
('7', 'animation_type_7'), # # In AddFramesMessage # Used in AddFramesMessage
('8', 'animation_type_8'), # # In AddFramesMessage # Used in AddFramesMessage
('101', 'animation_type_101'), # MID Inline query result # # Used in InlineQueryResult
('102', 'animation_type_102'), # # # Don't use
('103', 'animation_type_103'), # TEXT Inline query result # # Used in InlineQueryResult
('104', 'animation_type_104'), # TEXT Inline query result # # Used in InlineQueryResult
('105', 'animation_type_105'), # # # Don't use
('106', 'animation_type_106'), # # # Don't use
('107', 'animation_type_107'), # # # Don't use
('108', 'animation_type_108'), # # # Don't use
]
# Alternative names for animation types displayed only in add frames menu
ANIMATION_MENU = {
'1': 'animation_menu_1',
'2': 'animation_menu_2',
'3': 'animation_menu_3',
'4': 'animation_menu_4',
'5': 'animation_menu_5',
'6': 'animation_menu_6',
'7': 'animation_menu_7',
'8': 'animation_menu_8',
}
# Helpers to show localized animation type names while keeping numeric IDs
def animation_options(lang):
"""Return tuples of (id, translated title) for the first eight types.
Uses menu-specific names if available."""
options = []
for aid, key in ANIMATION_TYPES[:8]:
# Temporarily hide types 3 and 4 from the selection menu
if aid in {"3", "4"}:
continue
menu_key = ANIMATION_MENU.get(aid, key)
options.append((aid, translate(lang, menu_key)))
return options
# Resolve animation type by user input label
def resolve_animation_type(lang, label):
"""Return animation id for given user input label or None."""
for aid, key in ANIMATION_TYPES[:8]:
if (
label == aid
or label == translate(lang, key)
or label == translate(lang, ANIMATION_MENU.get(aid, key))
):
return aid
return None
# Working with MySQL database
class DataBase:
"""Helper methods for database access."""
# Save message to the database
def save_message(message, mid, text=None):
if hasattr(message, "chat"):
user_id = message.chat.id
else:
user_id = message
if text is None:
text = getattr(message, "text", "")
MessagesModel.objects.create(
user=str(user_id),
mid=mid,
message=text,
timestamp=timezone.now(),
)
# Profiles
@staticmethod
def get_or_create_profile(user):
"""Return existing profile or create a new one."""
profile, _ = ProfileModel.objects.get_or_create(
user_id=user.id,
defaults={
"first_name": user.first_name or "",
"username": user.username or "",
"language": "en",
},
)
return profile
# Save animated message
@staticmethod
def save_animated_message(profile, name, frames):
"""Store a new animated message for the user."""
AnimatedMessageModel.objects.create(
profile=profile,
name=name,
frames=frames,
)
# List and get animations
@staticmethod
def list_animations(profile):
"""Return all animations belonging to a profile."""
return AnimatedMessageModel.objects.filter(profile=profile)
# Get a single animation by primary key
@staticmethod
def get_animation(pk):
"""Fetch a single animation by primary key."""
return AnimatedMessageModel.objects.get(pk=pk)
# List and count user messages
@staticmethod
def list_user_messages(user_id):
"""List saved messages for a user ordered by time."""
return MessagesModel.objects.filter(user=str(user_id)).order_by('-timestamp')
# Count user messages and pending messages
@staticmethod
def count_user_messages(user_id):
"""Count how many messages a user saved."""
return MessagesModel.objects.filter(user=str(user_id)).count()
# Count user pending messages
@staticmethod
def count_user_sent(user_id):
"""Count how many pending messages a user sent."""
return PendingMessagesModel.objects.filter(user_id=str(user_id)).count()
# Delete a pending message by lmid
@staticmethod
def delete_pending(lmid: str):
"""Remove a pending message entry."""
PendingMessagesModel.objects.filter(lmid=lmid).delete()
# Load JSON frames from text
def load_json_frames(text):
"""Try to parse message text as frames JSON."""
try:
data = json.loads(text)
if isinstance(data, list) and all(
isinstance(f, dict) and 'text' in f and 'type' in f and 'delay' in f for f in data
):
return data
except Exception:
pass
return None
# Build paginated messages list
def build_messages_page(user_id, page: int = 1, per_page: int = 10, lang: str = "en"):
"""Create a paginated list of saved messages."""
messages = list(DataBase.list_user_messages(user_id))
total = len(messages)
# If no messages, return empty text and buttons
if total == 0:
text = translate(lang, 'no_messages')
markup = telebot.types.InlineKeyboardMarkup()
markup.add(
telebot.types.InlineKeyboardButton(text=translate(lang, 'add_message_btn'), callback_data='start_add_msg'),
telebot.types.InlineKeyboardButton(text=translate(lang, 'add_animation_btn'), callback_data='start_add_frames')
)
return text, markup
# Calculate pagination
pages = (total + per_page - 1) // per_page
page = max(1, min(page, pages))
start = (page - 1) * per_page
end = start + per_page
chunk = messages[start:end]
# Prepare text and buttons
markup = telebot.types.InlineKeyboardMarkup()
markup.add(
telebot.types.InlineKeyboardButton(text=translate(lang, 'add_message_btn'), callback_data='start_add_msg'),
telebot.types.InlineKeyboardButton(text=translate(lang, 'add_animation_btn'), callback_data='start_add_frames')
)
# Add buttons for each message in the chunk
row = []
for msg in chunk:
btn = telebot.types.InlineKeyboardButton(
text=str(msg.mid),
callback_data=f'viewmsg_{msg.id}_{page}_0'
)
row.append(btn)
if len(row) == 2:
markup.row(*row)
row = []
if row:
markup.row(*row)
# Add navigation buttons
nav = []
if page > 1:
nav.append(telebot.types.InlineKeyboardButton('⬅️', callback_data=f'msgs_page_{page-1}'))
nav.append(telebot.types.InlineKeyboardButton(f'{page}/{pages}', callback_data='noop'))
if page < pages:
nav.append(telebot.types.InlineKeyboardButton('➡️', callback_data=f'msgs_page_{page+1}'))
markup.row(*nav)
# Return text and markup
text = translate(lang, 'saved_messages_title').format(page=page, pages=pages)
return text, markup
# Build single message view with frames
def build_single_message(msg_id: int, page: int, frame_idx: int = 0, lang: str = "en"):
"""Prepare text and markup to display a single saved message."""
# Fetch the message by ID
try:
msg = MessagesModel.objects.get(pk=msg_id)
except MessagesModel.DoesNotExist:
return translate(lang, 'message_not_found'), telebot.types.InlineKeyboardMarkup()
# Load frames from message text
frames_json = load_json_frames(msg.message)
if frames_json is not None:
frames = frames_json
frame_text = frames[frame_idx % len(frames)]['text']
else:
frames = split_frame_message_into_array(msg.message)
frame_text = frames[frame_idx % len(frames)]
text = translate(lang, 'message_view_header').format(mid=msg.mid, text=frame_text)
# Prepare inline keyboard markup
markup = telebot.types.InlineKeyboardMarkup()
if len(frames) > 1:
nav = []
if frame_idx > 0:
nav.append(telebot.types.InlineKeyboardButton('⬅️', callback_data=f'viewmsg_{msg_id}_{page}_{frame_idx-1}'))
nav.append(telebot.types.InlineKeyboardButton(f'{frame_idx+1}/{len(frames)}', callback_data='noop'))
if frame_idx < len(frames) - 1:
nav.append(telebot.types.InlineKeyboardButton('➡️', callback_data=f'viewmsg_{msg_id}_{page}_{frame_idx+1}'))
markup.row(*nav)
# Add buttons for actions
markup.row(
telebot.types.InlineKeyboardButton(translate(lang, 'message_view_back_btn'), callback_data=f'msgs_page_{page}'),
telebot.types.InlineKeyboardButton(translate(lang, 'message_view_delete_btn'), callback_data=f'delmsg_{msg_id}_{page}')
)
return text, markup
# Run a single frame of an animation with optional delay
def run_single_frame(frame, inline_msg_id, user, custom_delays):
"""Show one frame of an animation with optional delay."""
# Check if frame is a dictionary with required keys
chosen_data = {
'result_id': str(frame['type']),
'from_user': {
'id': user.id,
'is_bot': user.is_bot,
'first_name': user.first_name,
'username': user.username,
'last_name': user.last_name,
},
'location': None,
'inline_message_id': inline_msg_id,
'query': frame['text'],
'from_frame': True,
'custom_delays': custom_delays,
'custom_delay': frame['delay'] if custom_delays else DEFAULT_FRAME_DELAY,
}
# Create a mock chosen object as a dictionary
class ChosenInlineResultObj:
def __init__(self, data):
self.result_id = data['result_id']
self.from_user = type('User', (), data['from_user'])
self.inline_message_id = data['inline_message_id']
self.query = data['query']
self.from_frame = data.get('from_frame', False)
self.custom_delays = data.get('custom_delays', False)
self.custom_delay = data['custom_delay']
# Convert to object-like structure for compatibility
chosen = ChosenInlineResultObj(chosen_data)
chosen_inline_result(chosen)
# Escape Markdown v2 characters
def escape_md_v2(text: str) -> str:
return re.sub(r'([\_\*\[\]\(\)\~\`\>\#\+\-\=\|\{\}\.\!])', r'\\\1', text)
# Function to split the message into an array of texts based on the specified rules
def split_frame_message_into_array(mess):
result = []
# If message doesn't start with '[', return whole message as single item
if not mess.startswith('['):
return [mess]
try:
current_pos = 1 # Skip initial '['
while current_pos < len(mess):
# Skip whitespace
while current_pos < len(mess) and mess[current_pos].isspace():
current_pos += 1
# Check for chunk start
if current_pos < len(mess) and mess[current_pos] == '{':
chunk_start = current_pos + 1
current_pos += 1
# Find closing '}'
brace_count = 1
while current_pos < len(mess) and brace_count > 0:
if mess[current_pos] == '{':
brace_count += 1
elif mess[current_pos] == '}':
brace_count -= 1
current_pos += 1
if brace_count == 0:
chunk = mess[chunk_start:current_pos-1]
result.append(chunk)
# Look for comma or closing bracket
while current_pos < len(mess) and mess[current_pos] not in ',]':
current_pos += 1
if current_pos < len(mess) and mess[current_pos] == ']':
break
elif current_pos < len(mess) and mess[current_pos] == ',':
current_pos += 1
continue
else:
break
# If we didn't find proper formatting, return original message
if not result:
return [mess]
return result
except Exception:
# If any error occurs, return original message
return [mess]
# Function to split the message into an array of texts based on the specified rules
def split_cf_message_into_array(mess):
result = []
# If message doesn't start with '[', return whole message as single item
if not mess.startswith('['):
return [mess]
try:
current_pos = 1 # Skip initial '['
while current_pos < len(mess):
# Skip whitespace
while current_pos < len(mess) and mess[current_pos].isspace():
current_pos += 1
# Check for chunk start
if current_pos < len(mess) and mess[current_pos] == '{':
chunk_start = current_pos + 1
current_pos += 1
# Find closing '}'
brace_count = 1
while current_pos < len(mess) and brace_count > 0:
if mess[current_pos] == '{':
brace_count += 1
elif mess[current_pos] == '}':
brace_count -= 1
current_pos += 1
if brace_count == 0:
chunk = mess[chunk_start:current_pos-1]
result.append(chunk)
# Look for comma or closing bracket
while current_pos < len(mess) and mess[current_pos] not in ',]':
current_pos += 1
if current_pos < len(mess) and mess[current_pos] == ']':
break
elif current_pos < len(mess) and mess[current_pos] == ',':
current_pos += 1
continue
else:
break
# If we didn't find proper formatting, return original message
if not result:
return [mess]
return result
except Exception:
# If any error occurs, return original message
return [mess]
# Handler start message
@bot.message_handler(commands=['start'])
def command_start(message):
"""Send greeting text and save the message."""
try:
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
text = translate(lang, 'greeting')
markup = telebot.types.InlineKeyboardMarkup()
btn_help = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_help'), callback_data="btn_help")
btn_support = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_support'), url=URL_SUPPORT)
markup.add(btn_help, btn_support)
bot.send_message(message.chat.id, text, reply_markup=markup, parse_mode='Markdown', disable_web_page_preview=True)
except Exception as e:
print(f"ERROR (command_start):\n{e}")
# Handler help message
@bot.message_handler(commands=['help'])
def command_help(message):
"""Display help information."""
try:
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
text = translate(lang, 'help')
markup = telebot.types.InlineKeyboardMarkup()
btn_support = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_support'), url=URL_SUPPORT)
markup.add(btn_support)
bot.send_message(message.chat.id, text, reply_markup=markup, parse_mode='Markdown', disable_web_page_preview=True)
except Exception as e:
print(f"ERROR (command_help):\n{e}")
# Handler language selection
@bot.message_handler(commands=['language'])
def command_language(message):
"""Allow the user to change language."""
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
markup = telebot.types.InlineKeyboardMarkup()
markup.add(
telebot.types.InlineKeyboardButton('English', callback_data='setlang_en'),
telebot.types.InlineKeyboardButton('Русский', callback_data='setlang_ru'),
telebot.types.InlineKeyboardButton('Қазақша', callback_data='setlang_kk'),
telebot.types.InlineKeyboardButton('हिन्दी', callback_data='setlang_hi'),
telebot.types.InlineKeyboardButton('中文', callback_data='setlang_zh'),
telebot.types.InlineKeyboardButton('Español', callback_data='setlang_es'),
telebot.types.InlineKeyboardButton('العربية', callback_data='setlang_ar'),
telebot.types.InlineKeyboardButton('Français', callback_data='setlang_fr'),
telebot.types.InlineKeyboardButton('Português', callback_data='setlang_pt'),
)
bot.send_message(message.chat.id, translate(lang, 'language_prompt'), reply_markup=markup)
# Handler profile management
@bot.message_handler(commands=['profile'])
def command_profile(message):
"""Show profile statistics and menu."""
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
added = DataBase.count_user_messages(message.from_user.id)
sent = DataBase.count_user_sent(message.from_user.id)
text = translate(lang, 'profile_template').format(
username=message.from_user.username or '-',
first=message.from_user.first_name or '-',
last=message.from_user.last_name or '-',
language=profile.language,
added=added,
sent=sent,
)
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text=translate(lang, 'saved_messages_button'), callback_data='msgs_page_1'))
bot.send_message(message.chat.id, text, reply_markup=markup)
# Handler messages list
@bot.message_handler(commands=['messages'])
def command_messages(message):
"""List user's saved messages."""
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
text, markup = build_messages_page(message.from_user.id, 1, lang=lang)
bot.send_message(message.chat.id, text, reply_markup=markup)
# Handler add message
@bot.message_handler(commands=['addmessage'])
def command_addmessage(message):
"""Start the flow for saving a simple message."""
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
user_states[message.chat.id] = {'state': 'await_new_message'}
bot.send_message(message.chat.id, translate(lang, 'addmessage_prompt'))
# Handler add frames message
@bot.message_handler(commands=['addframesmessage'])
def command_addframesmessage(message):
"""Start the flow for saving an animated message."""
profile = DataBase.get_or_create_profile(message.from_user)
lang = profile.language
user_states[message.chat.id] = {'state': 'await_new_frame', 'frames': []}
bot.send_message(message.chat.id, translate(lang, 'addframes_prompt'))
# Handler other messages
@bot.message_handler(func=lambda message: True)
def message(message):
"""Handle all other messages depending on interaction state."""
try:
# Check if user is in an interactive state
if message.chat.id in user_states:
st = user_states[message.chat.id]
# Profile menu
if st.get('state') == 'profile_menu':
lang = st.get('profile').language
if message.text == translate(lang, 'add_animation_btn'):
st['state'] = 'await_name'
bot.send_message(message.chat.id, translate(lang, 'prompt_animation_name'))
return
elif message.text == translate(lang, 'my_animations_btn'):
st['state'] = 'idle'
markup = telebot.types.InlineKeyboardMarkup()
for anim in DataBase.list_animations(st['profile']):
markup.add(
telebot.types.InlineKeyboardButton(
text=anim.name,
callback_data=f"useanim_{anim.id}",
),
telebot.types.InlineKeyboardButton(
text='❌', callback_data=f"delanim_{anim.id}"
),
)
bot.send_message(message.chat.id, translate(lang, 'your_animations'), reply_markup=markup)
return
# Add animated message
elif st.get('state') == 'await_name':
lang = st.get('profile').language
st['name'] = message.text
st['frames'] = []
st['state'] = 'await_frame'
bot.send_message(message.chat.id, translate(lang, 'new_frame_prompt'))
return
# Add frames to animated message
elif st.get('state') == 'await_frame':
lang = st.get('profile').language
if message.text == '/done':
DataBase.save_animated_message(st['profile'], st['name'], st['frames'])
bot.send_message(message.chat.id, translate(lang, 'animation_saved'), reply_markup=telebot.types.ReplyKeyboardRemove())
user_states.pop(message.chat.id, None)
return
st['current_frame'] = message.text
st['state'] = 'await_frame_type'
markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
for aid, title in animation_options(lang):
markup.add(title)
bot.send_message(message.chat.id, translate(lang, 'select_animation_type'), reply_markup=markup)
return
# Add frames to pending message
elif st.get('state') == 'await_frame_type':
lang = st.get('profile').language
anim_id = resolve_animation_type(lang, message.text)
if anim_id is None:
bot.send_message(message.chat.id, translate(lang, 'invalid_type'))
return
st['current_type'] = anim_id
st['state'] = 'await_frame_delay'
markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(translate(lang, 'default_delay_btn'))
for i in range(1, 11):
markup.add(str(i))
bot.send_message(message.chat.id, translate(lang, 'choose_delay'), reply_markup=markup)
return
# Add frame delay
elif st.get('state') == 'await_frame_delay':
lang = st.get('profile').language
delay = DEFAULT_FRAME_DELAY
if message.text.isdigit() and 1 <= int(message.text) <= 10:
delay = int(message.text)
st['frames'].append({'text': st['current_frame'], 'type': st['current_type'], 'delay': delay})
st['state'] = 'await_frame'
bot.send_message(message.chat.id, translate(lang, 'frame_saved'))
return
# Add new message or frames message
elif st.get('state') == 'await_new_message':
lang = DataBase.get_or_create_profile(message.from_user).language
if message.text == '/addframesmessage':
st['frames'] = []
st['state'] = 'await_new_frame'
bot.send_message(message.chat.id, translate(lang, 'addframes_prompt'))
return
mid = random.randint(1000000000, 9999999999)
frames = [{"text": message.text, "type": "3"}]
DataBase.save_message(message, mid, json.dumps(frames, ensure_ascii=False))
bot.send_message(message.chat.id, translate(lang, 'message_saved').format(mid=mid))
user_states.pop(message.chat.id, None)
return
# Add new frames message
elif st.get('state') == 'await_new_frame':
lang = DataBase.get_or_create_profile(message.from_user).language
if message.text == '/done':
mid = random.randint(1000000000, 9999999999)
DataBase.save_message(message.chat.id, mid, json.dumps(st["frames"], ensure_ascii=False))
bot.send_message(message.chat.id, translate(lang, 'message_saved').format(mid=mid))
user_states.pop(message.chat.id, None)
return
st['current_frame'] = message.text
st['state'] = 'await_new_frame_type'
markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
for aid, title in animation_options(lang):
markup.add(title)
bot.send_message(message.chat.id, translate(lang, 'select_animation_type'), reply_markup=markup)
return
# Add new frames type
elif st.get('state') == 'await_new_frame_type':
lang = DataBase.get_or_create_profile(message.from_user).language
anim_id = resolve_animation_type(lang, message.text)
if anim_id is None:
bot.send_message(message.chat.id, translate(lang, 'invalid_type'))
return
st['current_type'] = anim_id
st['state'] = 'await_new_frame_delay'
markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(translate(lang, 'default_delay_btn'))
for i in range(1, 11):
markup.add(str(i))
bot.send_message(message.chat.id, translate(lang, 'choose_delay'), reply_markup=markup)
return
# Add new frame delay
elif st.get('state') == 'await_new_frame_delay':
lang = DataBase.get_or_create_profile(message.from_user).language
delay = DEFAULT_FRAME_DELAY
if message.text.isdigit() and 1 <= int(message.text) <= 10:
delay = int(message.text)
st['frames'].append({'text': st['current_frame'], 'type': st['current_type'], 'delay': delay})
st['state'] = 'await_new_frame'
bot.send_message(message.chat.id, translate(lang, 'frame_saved'))
return
# Ignore messages outside of interactive states
except Exception as e:
print(f"ERROR (message):\n{e}")
# Callback query handler
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
"""Process inline keyboard callbacks."""
try:
# Check if user is in an interactive state
markup = telebot.types.InlineKeyboardMarkup()
is_done = False
# Handle different callback data
if 'startanimation' in call.data:
# Get PMID
parts = call.data.split('_')
if len(parts) == 2:
pmid = parts[1]
# Get message from database
try:
pend = PendingMessagesModel.objects.filter(lmid=pmid).first()
if not pend:
return
chosen_id = pend.chosen_id
inline_message_id = pend.inline_message_id
mess = pend.message
# Animation
# Create a mock chosen object as a dictionary
chosen_data = {
'result_id': chosen_id,
'from_user': {
'id': call.from_user.id,
'is_bot': call.from_user.is_bot,
'first_name': call.from_user.first_name,
'username': call.from_user.username,
'last_name': call.from_user.last_name
},
'location': None,
'inline_message_id': inline_message_id,
'query': mess
}
# Convert to object-like structure for compatibility
class ChosenInlineResult:
def __init__(self, data):
self.result_id = data['result_id']
self.from_user = type('User', (), data['from_user'])
self.inline_message_id = data['inline_message_id']
self.query = data['query']
chosen = ChosenInlineResult(chosen_data)
chosen_inline_result(chosen)
DataBase.delete_pending(pmid)
except Exception:
return
return
# Handle messages page navigation
elif call.data.startswith('msgs_page_'):
page = int(call.data.split('_')[2])
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
text, markup = build_messages_page(call.from_user.id, page, lang=lang)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=text,
reply_markup=markup,
)
return
# Handle viewing a single message
elif call.data.startswith('viewmsg_'):
parts = call.data.split('_')
msg_id = int(parts[1])
page = int(parts[2])
frame = int(parts[3])
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
text, markup = build_single_message(msg_id, page, frame, lang)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=text,
reply_markup=markup,
)
return
# Handle deleting a message
elif call.data.startswith('delmsg_'):
parts = call.data.split('_')
msg_id = int(parts[1])
page = int(parts[2])
try:
MessagesModel.objects.get(pk=msg_id).delete()
except Exception:
pass
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
text, markup = build_messages_page(call.from_user.id, page, lang=lang)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=text,
reply_markup=markup,
)
return
# Handle using an animation
elif call.data == 'start_add_msg':
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
user_states[call.message.chat.id] = {'state': 'await_new_message'}
bot.send_message(
call.message.chat.id,
translate(lang, 'addmessage_prompt')
)
return
# Handle starting to add frames
elif call.data == 'start_add_frames':
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
user_states[call.message.chat.id] = {'state': 'await_new_frame', 'frames': []}
bot.send_message(call.message.chat.id, translate(lang, 'addframes_prompt'))
return
# Handle using an existing animation
elif call.data == 'start_add_anim':
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
user_states[call.message.chat.id] = {'state': 'await_name', 'profile': profile}
bot.send_message(call.message.chat.id, translate(lang, 'prompt_animation_name'))
return
# Handle using an existing animation
elif call.data.startswith('delanim_'):
aid = int(call.data.split('_')[1])
try:
anim = AnimatedMessageModel.objects.get(pk=aid)
anim.delete()
bot.answer_callback_query(call.id, translate(profile.language, 'deleted'))
bot.edit_message_reply_markup(chat_id=call.message.chat.id,
message_id=call.message.message_id,
reply_markup=None)
except Exception:
pass
return
# Handle language change
elif call.data.startswith('setlang_'):
lang = call.data.split('_')[1]
profile = DataBase.get_or_create_profile(call.from_user)
profile.language = lang
profile.save()
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=translate(lang, 'language_updated'),
)
return
# Handle using an existing animation
elif call.data == 'btn_back_to_start':
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
text = translate(lang, 'greeting')
btn_help = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_help'), callback_data="btn_help")
btn_support = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_support'), url=URL_SUPPORT)
markup.add(btn_help, btn_support)
is_done = True
# Handle help button
elif call.data == 'btn_help':
profile = DataBase.get_or_create_profile(call.from_user)
lang = profile.language
text = translate(lang, 'help')
btn_start_back = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_back'), callback_data="btn_back_to_start")
btn_support = telebot.types.InlineKeyboardButton(text=translate(lang, 'button_support'), url=URL_SUPPORT)
markup.add(btn_start_back, btn_support)
is_done = True
if is_done:
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=text, reply_markup=markup, parse_mode='Markdown', disable_web_page_preview=True)
except Exception as e:
print(f"ERROR (callback):\n{e}")
# Inline query handler
@bot.inline_handler(lambda query: True)
def inline_query_handler(inline_query):
"""Handle inline queries from users."""
# Check if the query is empty
text = inline_query.query.strip()
profile = DataBase.get_or_create_profile(inline_query.from_user)
lang = profile.language
results = []
# If the query is empty, show options for animations
if text:
# Check if the text is a digit (Message ID) or not
if text.isdigit():
ids = ['1', '101']
else:
ids = ['3', '4', '103', '104']
# Add animation types to results
anim_map = {aid: title for aid, title in ANIMATION_TYPES}
for anim_id in ids:
anim_title = translate(lang, anim_map.get(anim_id, anim_id))
markup = InlineKeyboardMarkup().add(
InlineKeyboardButton(text=translate(lang, 'start_btn'), callback_data="startanimation")
)
results.append(
InlineQueryResultArticle(
id=anim_id,
title=f"{anim_title}",
input_message_content=InputTextMessageContent(translate(lang, 'please_wait')),
reply_markup=markup,
)
)
# Add custom animations from the database
for anim in DataBase.list_animations(profile):
markup = InlineKeyboardMarkup().add(
InlineKeyboardButton(text=translate(lang, 'start_btn'), callback_data="startanimation")
)
results.append(
InlineQueryResultArticle(
id=f"cust_{anim.id}",
title=f"{anim.name}",
input_message_content=InputTextMessageContent(translate(lang, 'please_wait')),
reply_markup=markup,
)
)
# If the query is empty, show an empty result
else:
results.append(
InlineQueryResultArticle(
id='empty',
title=translate(lang, 'inline_enter_text_title'),
input_message_content=InputTextMessageContent(translate(lang, 'inline_enter_text_content')),
)
)
bot.answer_inline_query(inline_query.id, results, cache_time=0)
# Animation handler
@bot.chosen_inline_handler(func=lambda chosen: True)
def chosen_inline_result(chosen):
"""Execute the selected inline animation."""
custom_delays = False
custom_delay = DEFAULT_FRAME_DELAY
# Check inline message ID
inline_msg_id = getattr(chosen, 'inline_message_id', None)
text = chosen.query.strip()
if not inline_msg_id:
return
# If the chosen result ID starts with 'cust_', it is a custom animation
if str(chosen.result_id).startswith('cust_'):
try:
aid = int(str(chosen.result_id).split('_')[1])
anim = AnimatedMessageModel.objects.get(pk=aid)
for frame in anim.frames:
run_single_frame(frame, inline_msg_id, chosen.from_user, custom_delays)
return
except Exception:
return
# Check type message ( PENDING or ANIMATION )
# PENDING
if len(chosen.result_id) > 2:
pmid = random.randint(100000000000, 999999999999)
callback_data = "startanimation_" + str(pmid)