-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tlgfwk.py
2002 lines (1528 loc) · 94.5 KB
/
tlgfwk.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------
__version__ = """1.0.4 Hotfix for false command not implemented"""
__todos__ = """
1.0.0 Scheduling tasks with APScheduler
"""
__change_log__ = """
0.6.3 Load just a specified plugin
0.6.4 Show to admin user which commands is common or admin
0.6.5 Add a command to show the bot configuration settings
0.6.7 Improve command handler to show the commands available to the user and admin
0.6.8 Show 👑 on the user list for the admin users
0.6.9 Show 👑 on the command help list for the admin commands
0.7.0 Add a command to show user´s balance
0.7.1 Add a command to manage user's balance
0.7.2 Initialize a minimum balance for new users
0.7.3 Set last message date for all commands
0.7.4 Fixed the show balance command and show all user´s data
0.7.5 Migrate user´s balance storage on the user data context
0.7.6 Fixed duplicate commands
0.7.7 Change payment tokens
0.7.8 Add user into the user list from the decorator of the command handler
0.8.6 Created an examples folder
0.9.2 Command to generate Paypal payment links
0.7.9 Command to Manage links
0.8.0 Manage TODO´s
0.8.1 Manage products
0.8.2 Manage commands
0.8.3 Send broadcast messages to all admin users and common users
0.8.4 Show description besides each link
0.8.5 Delete links from the .env file and add them to the bot configuration settings
0.8.7 Created the simplest example of a bot with the framework
0.9.0 Command to show how to create a simple bot and instantiate from token another on the fly
0.9.1 Sort command help by command name
0.9.3 Run in background the Flask webhook endpoint for receive paypal events0.9.4 Test with paypal Live/production environment and get token from .env file
0.9.4 List all paypal pending links
0.9.5 Command to remove paypal links
0.9.6 Command to switch between paypal live and sandbox environments
0.9.7 Echo command for testing with reply the same message received
0.9.8 Example of a simple echo bot using the framework
0.9.9 Optional disable to command not implemented yet
1.0.1 Scheduling tasks with APScheduler"""
from __init__ import *
# import re
class TlgBotFwk(Application):
# ------------- util functions ------------------
async def example_scheduled_function(callback_context: CallbackContext):
try:
args = callback_context.job.data['args']
tlg_bot_fwk: TlgBotFwk = args[0]
await tlg_bot_fwk.application.bot.send_message(chat_id=tlg_bot_fwk.bot_owner, text="Scheduled task executed!")
except Exception as e:
logger.error(f"Error executing scheduled task: {e}")
async def get_set_user_data(self, dict_name = 'user_status', user_id: int = None, user_item_name = 'balance', default_value = None, set_data = False, context = None):
try:
if not self.application.persistence:
return None
bot_data = await self.application.persistence.get_bot_data()
if dict_name in bot_data:
dict_data = bot_data[dict_name]
else:
dict_data = {dict_name: {}}
if user_id and user_id in dict_data:
user_data = dict_data[user_id]
else:
user_data[user_id] = {user_id: {}}
if user_item_name and user_item_name in user_data:
item_value = user_data[user_item_name]
else:
user_data[user_item_name] = default_value
if set_data:
user_data[user_item_name] = default_value
# await self.application.persistence.get_bot_data()[dict_name][user_id] = user_data
await self.application.persistence.update_bot_data(bot_data)
if context:
context.bot_data[dict_name] = dict_data
# TODO: update the user data on the context
context.user_data[user_item_name] = default_value
return user_data
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logger.error(f"Error getting user data in {fname} at line {exc_tb.tb_lineno}: {e}")
return f'Sorry, we have a problem getting user data: {e}'
async def force_persistence(self, update: Update, context: CallbackContext):
"""Force the bot to save the persistence file
Args:
update (Update): _description_
context (CallbackContext): _description_
"""
try:
# if the dictionary of users does not exist on bot_data, create it
if 'user_dict' not in context.bot_data:
context.bot_data['user_dict'] = {}
# Insert or update user on the bot_data dictionary
context.bot_data['user_dict'][update.effective_user.id] = update.effective_user
# force persistence of the bot_data dictionary
self.application.persistence.update_bot_data(context.bot_data) if self.application.persistence else None
# set effective language code
language_code = context.user_data['language_code'] if 'language_code' in context.user_data else update.effective_user.language_code
# force persistence update of the user data
await self.application.persistence.update_user_data(update.effective_user.id, context.user_data) if self.application.persistence else None
# get user data from persistence
user_data = await self.application.persistence.get_user_data() if self.application.persistence else None
except Exception as e:
logger.error(f"Error: {e}")
await update.message.reply_text(f"An error occurred: {e}")
async def get_init_message(self):
try:
post_init_message = f"""@{self.bot_name} *Started!*
_Version:_ `{__version__}`
_Host:_ `{self.hostname}`
_CWD:_ `{os.getcwd()}`
_Path:_
`{self.main_script_path}`"""
logger.info(f"{post_init_message}")
return post_init_message
except Exception as e:
logger.error(f"Error in get_init_message: {e}")
return f'Sorry, we encountered an error: {e}'
async def set_start_message(self, language_code:str, full_name:str, user_id:int): #, update, context):
try:
self.default_start_message = translations.get_translated_message(language_code, 'start_message', 'en', full_name, self.application.bot.name, self.application.bot.first_name)
# if self.bot_owner and user_id == self.bot_owner:
if user_id in self.admins_owner:
self.default_start_message += f"{os.linesep}{os.linesep}_You are one of the bot admins:_` {self.admins_owner}`"
self.default_start_message += f"{os.linesep}_User language code:_ `{language_code}`"
self.default_start_message += f"{os.linesep}_Default language code:_ `{self.default_language_code}`"
# language_code = context.user_data.get('language_code', update.effective_user.language_code)
self.default_start_message += f"{os.linesep}{os.linesep}{await self.get_help_text(language_code, user_id)}"
except Exception as e:
logger.error(f"Error in set_start_message: {e}")
return f'Sorry, we encountered an error: {e}'
async def set_admin_commands(self):
"""Set the admin commands to the bot menu
Args:
bot (_type_): _description_
admin_id_list (_type_): _description_
admin_commands (_type_): _description_
"""
try:
# remove from list self.all_commands the list of disabled commands
self.all_commands = [command for command in self.all_commands if command.command not in self.disable_commands_list]
# for all admin users set the scope of the commands to chat_id
for admin_id in self.admins_owner:
await self.application.bot.set_my_commands(self.all_commands, scope={'type': 'chat', 'chat_id': admin_id})
except Exception as e:
logger.error(f"Error setting admin commands: {e}")
return f'Sorry, we have a problem setting admin commands: {e}'
async def send_admins_message(self, message: str, *args, **kwargs):
"""Send a message to all admin users
Args:
message (str): _description_
"""
try:
# send message to all admin users
for admin_id in self.admins_owner:
await self.application.bot.send_message(chat_id=admin_id, text=message)
except Exception as e:
logger.error(f"Error sending message to admin users: {e}")
return f'Sorry, we have a problem sending message to admin users: {e}'
async def cmd_show_config(self, update: Update, context: CallbackContext, *args, **kwargs):
"""Show the bot configuration settings
Args:
update (Update): _description_
context (CallbackContext): _description_
"""
try:
self.links_string = os.environ.get('USEFUL_LINKS', '')
self.links_list = self.links_string.split(',') if self.links_string else []
self.show_config_message = f"""*Bot Configuration Settings*{os.linesep}
_Bot Name:_ `{self.bot_name}`
_Bot Owner:_ `{self.bot_owner}`
_Bot Admins:_ `{self.admin_id_string if self.admin_id_string else ''}`
_Default Language Code:_ `{self.default_language_code}`
_Decrypted Token:_ `{self.token}`
_Links:_
{self.links_string.replace(',', os.linesep)}"""
await update.message.reply_text(self.show_config_message, parse_mode=ParseMode.MARKDOWN)
except Exception as e:
logger.error(f"Error in cmd_show_config: {e}")
await update.message.reply_text(f"Sorry, we encountered an error: {e}")
async def cmd_show_env(self, update: Update, context: CallbackContext, *args, **kwargs):
"""Show the bot environment settings
Args:
update (Update): _description_
context (CallbackContext): _description_
"""
try:
# Load the .env file into a dictionary
env_vars = dotenv.dotenv_values(self.env_file)
# convert dictionary to string
env_vars_str = os.linesep.join([f"`{key}`=`{value}`" for key, value in env_vars.items()])
self.show_env_message = f"""*Bot Environment Settings*{os.linesep}
{env_vars_str}
{self.links_string.replace(',', os.linesep)}"""
await update.message.reply_text(self.show_env_message, parse_mode=ParseMode.MARKDOWN)
except Exception as e:
logger.error(f"Error in cmd_show_env: {e}")
await update.message.reply_text(f"Sorry, we encountered an error: {e}")
def add_or_update_env_setting(self, key, value):
"""Function to add or update a setting in the .env file
Args:
key (_type_): _description_
value (_type_): _description_
"""
# Read the existing .env file
if os.path.exists(self.env_file):
with open(self.env_file, 'r') as file:
lines = file.readlines()
else:
lines = []
# Check if the key already exists
key_exists = False
for i, line in enumerate(lines):
if line.startswith(f"{key}="):
lines[i] = f"{key}={value}\n"
key_exists = True
break
# If the key does not exist, add it
if not key_exists:
lines.append(f"{key}={value}\n")
# Write the updated content back to the .env file
with open(self.env_file, 'w') as file:
file.writelines(lines)
def get_command_handlers(self, *args, **kwargs):
command_dict = {}
try:
for handler_group in self.application.handlers.values():
for handler in handler_group:
try:
if isinstance(handler, CommandHandler):
command_name = list(handler.commands)[0]
command_description = handler.callback.__doc__.split("\n")[0] if handler.callback.__doc__ else command_name
command_filter = handler.filters
user_allowed = list(command_filter.user_ids)[0] if isinstance(command_filter, filters.User) else None
is_admin = True if isinstance(command_filter, filters.User) else False
command_dict[command_name] = {'command_description': command_description, 'is_admin': is_admin, 'user_allowed': user_allowed}
# yield handler
except Exception as e:
logger.error(f"Error getting command description: {e}")
continue
except Exception as e:
logger.error(f"Error getting command description: {e}")
return f'Sorry, we have a problem getting the command description: {e}'
return command_dict
async def get_help_text(self, language_code = None, current_user_id = None):
"""Generates a help text from bot commands already set and the command handlers
Args:
language_code (_type_, optional): _description_. Defaults to None.
current_user_id (_type_, optional): _description_. Defaults to None.
Returns:
_type_: _description_
"""
try:
# set admin commands
await self.set_admin_commands()
# get all commands from bot commands menu scope=BotCommandScopeDefault()
self.common_users_commands = await self.application.bot.get_my_commands()
self.admin_commands = await self.application.bot.get_my_commands(scope={'type': 'chat', 'chat_id': self.admins_owner[0]}) if self.admins_owner else []
self.all_commands = tuple(list(self.common_users_commands) + list(self.admin_commands))
# TODO: hotfix remove addjob and deletejob from the list of commands
# self.disable_commands_list = ['addjob', 'deletejob', 'lisjobs','listalljobs']
language_code = self.default_language_code if not language_code else language_code
self.help_text = translations.get_translated_message(language_code, 'help_message', self.default_language_code, self.application.bot.name)
for command in self.common_users_commands:
self.help_text += f"/{command.command} - {command.description}{os.linesep}"
# get a dictionary of command handlers
command_dict = self.get_command_handlers()
# convert the commands dictionary into help text and update command menu
for command_name, command_data in command_dict.items():
flag_admin = '👑' if command_data['is_admin'] else ' '
try:
if command_name not in [bot_command.command for bot_command in self.common_users_commands]:
if command_data['is_admin']:
if current_user_id in self.admins_owner:
self.help_text += f"/{command_name} {flag_admin} - {command_data['command_description']}{os.linesep}"
# add command got from command handler to telegram menu commands only to specific admin user
admin_commands_list = list(self.admin_commands)
admin_commands_list.append(BotCommand(command_name, command_data['command_description']))
self.admin_commands = tuple(admin_commands_list)
else:
command_description = command_data['command_description']
self.help_text += f"/{command_name} {flag_admin} - {command_description}{os.linesep}"
# Add command got from command handler to telegram menu commands
users_commands_list = list(self.common_users_commands)
users_commands_list.append(BotCommand(command_name, command_description))
self.common_users_commands = tuple(users_commands_list)
self.all_commands = tuple(list(self.common_users_commands) + list(self.admin_commands))
except Exception as e:
logger.error(f"Error adding command to menu: {e}")
continue
# if sort is enabled, convert help text to a list of strings and order list by command name
if self.sort_commands:
help_header = self.help_text.split(os.linesep)[0]
help_text_list = self.help_text.split(os.linesep)[1:]
help_text_list = sorted(help_text_list)
self.help_text = f'{help_header}{os.linesep}{os.linesep.join(help_text_list)}'
# remove from list self.all_commands the list of disabled commands
self.common_users_commands = [command for command in self.common_users_commands if command.command not in self.disable_commands_list]
self.all_commands = [command for command in self.all_commands if command.command not in self.disable_commands_list]
# set new commands to telegram bot menu
await self.application.bot.set_my_commands(self.common_users_commands)
# concatenate tuples of admin and user commands
await self.application.bot.set_my_commands(self.all_commands, scope={'type': 'chat', 'chat_id': self.bot_owner})
# for all admin users set the scope of the commands to chat_id
await self.set_admin_commands()
# double check
self.common_users_commands = await self.application.bot.get_my_commands()
self.all_commands = await self.application.bot.get_my_commands(scope={'type': 'chat', 'chat_id': self.bot_owner})
return self.help_text
except Exception as e:
logger.error(f"Error getting commands: {e}")
return f'Sorry, we have a problem getting the commands: {e}'
def validate_token(self, token: str = None, quit_if_error = True, input_token = True):
self.token_validated = False
self.bot_info = None
try:
bot = Bot(token=token)
self.loop = asyncio.get_event_loop()
self.bot_info = self.loop.run_until_complete(bot.get_me())
# loop.close()
self.token_validated = True
return True
except Exception as e:
logger.error(f"Error validating token: {e}")
if input_token:
token = input_with_timeout("You have 30 sec. to enter the bot token: ", 30)
if self.validate_token(token, quit_if_error, False):
self.token = token
# self.bot_owner = int(input_with_timeout("You have 30 sec. to enter the bot owner id: ", 30))
self.bot_owner = int(input_with_timeout("You have 30 sec. to enter the bot owner id: ", 30))
# clear entire .env file
os.remove(self.env_file)
open(self.env_file, 'w').close()
dotenv.set_key(self.env_file, 'DEFAULT_BOT_TOKEN', self.token)
# dotenv.set_key(self.env_file, 'DEFAULT_BOT_OWNER', int(self.bot_owner))
self.add_or_update_env_setting('DEFAULT_BOT_OWNER', self.bot_owner)
dotenv.load_dotenv(self.env_file)
return True
if quit_if_error:
input_with_timeout("Enter to close: ", 10)
quit()
return None
def check_encrypt(self, decrypted_token: str = None, decrypted_bot_owner: str = None, decrypt_key = None, encrypted_token: str = None, encrypted_bot_owner: str = None):
def decrypt(encrypted_token, key):
f = Fernet(key)
# key = base64.urlsafe_b64decode(key.encode()).decode()
# key = key.encode()
# # Decrypt the string
# decrypted_string = fernet.decrypt(encrypted_string).decode()
# decrypted_token = f.decrypt(token.encode()).decode()
decrypted_token = f.decrypt(encrypted_token).decode()
return decrypted_token
# encrypt the token and store it in the .env file
def encrypt(decrypted_token, key):
f = Fernet(key)
# Fernet key must be 32 url-safe base64-encoded bytes.
# key = base64.urlsafe_b64decode(key.encode())
# # Encrypt the string
# encrypted_string = fernet.encrypt(original_string.encode())
# encrypted_token = f.encrypt(decrypted_token.encode()).decode()
encrypted_token = f.encrypt(decrypted_token.encode())
return encrypted_token
self.encrypt_ascii_key = os.environ.get('ENCRYPT_KEY', None) if not decrypt_key else decrypt_key
# First time, if there is not a crypto key yet, generate it and encrypt the token and save back to the .env file
if not self.encrypt_ascii_key:
# Define a literal string
literal_string = "mysecretpassword1234567890123456" # Must be 32 characters
# Convert the literal string to bytes
key_bytes = literal_string.encode()
# Encode the byte string in URL-safe base64 format
key = base64.urlsafe_b64encode(key_bytes)
# Convert key_bytes back to string literal
key_string_literal = key_bytes.decode('utf-8')
# Encrypt a string
fernet = Fernet(key)
# ------------------------------
self.token = os.environ.get('DEFAULT_BOT_TOKEN', None) if not decrypted_token else decrypted_token
self.bot_owner = int(os.environ.get('DEFAULT_BOT_OWNER', None)) if not decrypted_bot_owner else int(decrypted_bot_owner)
self.encrypt_byte_key = key # Fernet.generate_key() # key
self.encrypt_ascii_key = base64.urlsafe_b64encode(self.encrypt_byte_key).decode()
# update the .env file with the encrypted token
self.encrypted_token = encrypt(self.token, self.encrypt_byte_key).decode()
dotenv.set_key(self.env_file, 'ENCRYPTED_BOT_TOKEN', self.encrypted_token)
# update the .env file with the encrypted bot owner and the key
self.encrypted_bot_owner = encrypt(str(self.bot_owner), self.encrypt_byte_key).decode()
dotenv.set_key(self.env_file, 'ENCRYPTED_BOT_OWNER', self.encrypted_bot_owner)
# save the new encryption key to the .env file
dotenv.set_key(self.env_file, 'ENCRYPT_KEY', self.encrypt_ascii_key)
# remove the decrypted token and the bot owner from the .env file
dotenv.unset_key(self.env_file, 'DEFAULT_BOT_TOKEN')
dotenv.unset_key(self.env_file, 'DEFAULT_BOT_OWNER')
else:
self.encrypted_token = os.environ.get('ENCRYPTED_BOT_TOKEN', None) if not encrypted_token else encrypted_token
self.encrypted_bot_owner = os.environ.get('ENCRYPTED_BOT_OWNER', None) if not encrypted_bot_owner else int(decrypted_bot_owner)
self.encrypt_byte_key = base64.urlsafe_b64decode(self.encrypt_ascii_key.encode())
# key_string_literal = key_bytes.decode('utf-8')
# Decrypt the token got from the .env file
self.token = decrypt(self.encrypted_token, self.encrypt_byte_key)
self.bot_owner = int(decrypt(str(self.encrypted_bot_owner), self.encrypt_byte_key))
# --------------- Init stop bot event handlers--------------------
async def post_init(self, application: Application) -> None:
try:
self.bot_name = application.bot.username
post_init_message = await self.get_init_message()
logger.info(f"{post_init_message}")
# Set the start message for all admin users
await self.set_start_message(self.default_language_code, 'Admin', self.admins_owner[0])
post_init_message += f"{os.linesep}{os.linesep}{self.default_start_message}"
self.common_users_commands = await application.bot.get_my_commands(scope=BotCommandScopeDefault())
logger.info(f"Get Current commands: {self.common_users_commands}")
# remove from the list of commands the list of disabled commands
self.common_users_commands = [command for command in self.common_users_commands if command.command not in self.disable_commands_list]
self.admin_commands = await application.bot.get_my_commands(scope={'type': 'chat', 'chat_id': self.admins_owner[0]}) if self.admins_owner else []
# remove from the list of admin commands the list of disabled commands
self.admin_commands = [command for command in self.admin_commands if command.command not in self.disable_commands_list]
self.all_commands = tuple(list(self.common_users_commands) + list(self.admin_commands))
# for all admin users set the scope of the commands to chat_id
await self.send_admins_message(message=post_init_message)
if self.external_post_init:
await self.external_post_init()
except Exception as e:
logger.error(f"Error: {e}")
async def post_stop(self, application: Application) -> None:
try:
# force persistence of all bot data
self.application.persistence.flush() if self.application.persistence else None
stop_message = f"_STOPPING_ @{self.bot_name} {os.linesep}`{self.hostname}`{os.linesep}`{__file__}` {self.bot_name}..."
logger.info(stop_message)
await self.send_admins_message(message=stop_message)
except Exception as e:
logger.error(f"Error: {e}")
sys.exit(0)
# --------------- Payment handlers --------------------
# after (optional) shipping, it's the pre-checkout
async def precheckout_callback(self, update: Update, context: CallbackContext) -> None:
try:
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
await query.answer(ok=False, error_message="Erro no processamento do pagamento!")
else:
await query.answer(ok=True)
# add new credits to the users balance inside persistent storage context user data
previous_balance = context.user_data['balance'] if 'balance' in context.user_data else 0
credit = int(query.total_amount / 100)
new_balance = previous_balance + credit
context.user_data['balance'] = new_balance
# TODO: add balance to context bot data
await self.get_set_user_data(dict_name='user_status', user_id=update.effective_user.id, user_item_name='balance', default_value=new_balance, set_data=True, context=context)
except Exception as e:
logger.error(f"Error in precheckout_callback: {e}")
await query.answer(ok=False, error_message="An unexpected error occurred during payment processing.")
def execute_payment_callback(self, payment, payment_id, payer_id):
try:
# get the bot context data persistence
bot_data = self.application.bot_data
# get paypal_link dictionary from bot context data
paypal_link = bot_data.get('paypal_links', {}) if bot_data else {}
# clone paypal links dictionary to another variable
paypal_link_copy = paypal_link.copy()
# for each paypal link in dictionary, warns user that a payment was detected
for link, user_id in paypal_link.items():
try:
# TODO: update user balance
# send a message to the user by raw telegram API
self.send_message_by_api(chat_id=user_id, message="Thanks! Payment detected! A credit of $5 was added to your balance!")
# and remove the item from the dictionary
# RuntimeError('dictionary changed size during iteration')
del paypal_link_copy[link]
except Exception as e:
logger.error(f"Error sending payment confirmation message: {e}")
# restore paypal links dictionary from the cloned
bot_data['paypal_links'] = paypal_link_copy
except Exception as e:
logger.error(f"Error in EXECUTE_PAYMENT_CALLBACK: {e}")
return f"An error occurred: {e}"
# ---------------- Bot constructor and initializers -------
def __init__(self,
token: str = None,
validate_token = True,
quit_if_error = True,
env_file: str = '.env',
bot_owner: str = None,
bot_defaults_build = Defaults(parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True),
disable_default_handlers = False,
default_language_code = None,
decrypt_key = None,
disable_encryption = True,
admin_id_list: list[int] = None,
links: list[str] = [],
persistence_file: str = None,
disable_persistence = False,
default_persistence_interval = 5,
logger = logger,
sort_commands = True,
enable_plugins = False,
admin_filters = None,
force_common_commands = [],
disable_commands_list = [],
disable_command_not_implemented = False,
disable_error_handler = False,
external_post_init = None
):
try:
self.hostname = socket.getfqdn()
self.main_script_path = sys.argv[0]
self.bot_name = None
self.env_file = env_file if env_file else '.env'
self.logger = logger
self.token = token if token else ''
self.bot_owner = bot_owner if bot_owner else ''
self.admin_id_string = admin_id_list if admin_id_list else os.environ.get('ADMIN_ID_LIST', '')
self.all_commands = []
self.sort_commands = sort_commands
self.default_persistence_interval = default_persistence_interval
# Create an empty .env file at run time if it does not exist
if self.env_file and not os.path.exists(self.env_file):
open(self.env_file, 'w').close()
# and add en empty line with token and bot owner
dotenv.set_key(self.env_file, 'DEFAULT_BOT_TOKEN',self.token)
# dotenv.set_key(self.env_file, 'DEFAULT_BOT_OWNER',self.bot_owner)
dotenv.load_dotenv(self.env_file)
# self.token = os.environ.get('DEFAULT_BOT_TOKEN') # , None) if not self.token else self.token
self.token = dotenv.get_key(self.env_file, 'DEFAULT_BOT_TOKEN', None) if not self.token else self.token
self.bot_owner = int(os.environ.get('DEFAULT_BOT_OWNER', 999999)) if not self.bot_owner else self.bot_owner
# read list of admin users from the .env file
default_list = [self.bot_owner] + [int(admin_id) for admin_id in (self.admin_id_string.split(',') if self.admin_id_string else [])]
default_str = ','.join(map(str, default_list))
self.admins_owner = [int(admin_id) for admin_id in os.environ.get('ADMIN_ID_LIST', default_str).split(',')]
if validate_token:
self.validate_token(self.token, quit_if_error)
if not disable_encryption:
# If there is a crypto key, decrypt the token and the bot_owner got from the .env file
self.check_encrypt(token, bot_owner, decrypt_key)
else:
self.token = os.environ.get('DEFAULT_BOT_TOKEN', None) if not self.token else self.token
self.bot_owner = int(os.environ.get('DEFAULT_BOT_OWNER', None)) if not self.bot_owner else int(self.bot_owner)
self.default_language_code = os.environ.get('DEFAULT_LANGUAGE_CODE', 'en-US') if not default_language_code else default_language_code
self.disable_default_handlers = os.environ.get('DISABLE_DEFAULT_HANDLERS', False) if not disable_default_handlers else disable_default_handlers
self.links_string=os.linesep.join(links) if links else os.environ.get('USEFUL_LINKS', '')
self.links_list = self.links_string.split(',') if self.links_string else []
dotenv.set_key(dotenv_path=self.env_file, key_to_set='USEFUL_LINKS', value_to_set=self.links_string)
self.bot_defaults_build = bot_defaults_build
self.admin_filters = admin_filters if admin_filters else filters.User(user_id=self.admins_owner)
self.force_common_commands = force_common_commands
self.disable_command_not_implemented = disable_command_not_implemented
self.disable_commands_list = disable_commands_list
self.disable_error_handler = disable_error_handler
self.external_post_init = external_post_init
# ---------- Build the bot application ------------
# Making bot persistant from the base class
# https://github.com/python-telegram-bot/python-telegram-bot/wiki/Making-your-bot-persistent
self.persistence_file = f"{script_path}{os.sep}{self.bot_info.username + '.pickle'}" if not persistence_file else persistence_file
persistence = PicklePersistence(filepath=self.persistence_file, update_interval=self.default_persistence_interval) if not disable_persistence else None
# Create an Application instance using the builder pattern
# ('To use `JobQueue`, PTB must be installed via `pip install "python-telegram-bot[job-queue]"`.',)
self.application = Application.builder().defaults(bot_defaults_build).token(self.token).post_init(self.post_init).post_stop(self.post_stop).persistence(persistence).job_queue(JobQueue()).build()
# --------------------------------------------------
# save botname to .env file
dotenv.set_key(self.env_file, 'BOT_NAME', self.bot_info.username)
self.initialize_handlers()
# -------------------------------------------
self.enable_plugins = enable_plugins
if enable_plugins:
try:
# self.plugin_manager = PluginManager(plugins_dir)
self.plugin_manager = PluginManager()
self.plugin_manager.load_plugins()
except Exception as e:
logger.error(f"Error in plugin manager: {e}")
# -------------------------------------------
# DOING: 0.9.3 Run in background the Flask webhook endpoint for receive paypal events
def run_app():
try:
# Run flask web server API
# paypal.app.run(debug=False)
paypal.app.run(host="0.0.0.0", debug=False) # listen to all IP addresses
except Exception as e:
logger.error(f"Error running Flask web server: {e}")
try:
# set callbacks for paypal events
paypal.execute_payment_callback = self.execute_payment_callback
# Run the app in a separate thread
# thread = threading.Thread(target=run_app)
thread = threading.Thread(target=paypal.main, kwargs={'host': '0.0.0.0', 'load_dotenv': True})
thread.start()
# sudo ss -tuln | grep :5000
except Exception as e:
logger.error(f"Error running PayPal app: {e}")
# -------------------------------------------
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logger.error(f"Error initializing bot in {fname} at line {exc_tb.tb_lineno}: {e}")
input_with_timeout("Enter to close: ", 10)
quit()
def initialize_handlers(self):
try:
# Clear previous command menus
self.application.bot.set_my_commands([])
# handles global errors if enabled
if not self.disable_error_handler:
self.application.add_error_handler(self.error_handler)
if not self.disable_default_handlers:
self.logger.info("Default handlers enabled")
# Adding a simple command handler for the /start command
start_handler = CommandHandler('start', self.default_start_handler)
self.application.add_handler(start_handler)
help_handler = CommandHandler('help', self.default_help_handler)
self.application.add_handler(help_handler)
else:
self.logger.info("Default handlers disabled")
# handler for the /lang command to set the default language code
set_language_code_handler = CommandHandler('lang', self.set_default_language, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(set_language_code_handler)
# add handler for the /userlang command to set the user language code
command_text = 'userlang'
if command_text not in self.disable_commands_list:
set_user_language_handler = CommandHandler(command_text, self.set_user_language)
self.application.add_handler(set_user_language_handler)
# add handler for the /git command to update the bot's code from a git repository
git_handler = CommandHandler('git', self.cmd_git, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(git_handler)
# add handler for the /restart command to restart the bot
restart_handler = CommandHandler('restart', self.restart_bot, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(restart_handler)
# add handler for the /stop command to stop the bot
stop_handler = CommandHandler('stop', self.stop_bot, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(stop_handler)
# add handler for the /showconfig command to show the bot configuration settings
show_config_handler = CommandHandler('showconfig', self.cmd_show_config, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(show_config_handler)
# add version command handler
command_text = 'version'
if command_text not in self.disable_commands_list:
version_handler = CommandHandler(command_text, self.cmd_version_handler, filters=self.admin_filters if 'version' not in self.force_common_commands else None)
self.application.add_handler(version_handler)
# add admin manage command handler
admin_manage_handler = CommandHandler('admin', self.cmd_manage_admin, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(admin_manage_handler)
# add useful links command handler
command_text = 'links'
if command_text not in self.disable_commands_list:
useful_links_handler = CommandHandler(command_text, self.cmd_manage_links)
self.application.add_handler(useful_links_handler)
# add show env command handler
show_env_handler = CommandHandler('showenv', self.cmd_show_env, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(show_env_handler)
# add show pickle command handler
show_pickle_handler = CommandHandler('showpickle', self.cmd_show_pickle, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(show_pickle_handler)
# add force persistence command handler
force_persistence_handler = CommandHandler('forcepersistence', self.cmd_force_persistence, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(force_persistence_handler)
# Add admin command to show users from persistence file
show_users_handler = CommandHandler('showusers', self.cmd_show_users, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(show_users_handler)
command_text = 'payment'
if command_text not in self.disable_commands_list:
self.application.add_handler(CommandHandler(command_text, self.cmd_payment))
# add handler for the /loadplugin command to load a plugin dynamically
load_plugin_handler = CommandHandler('loadplugin', self.cmd_load_plugin, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(load_plugin_handler)
# Add handler for the /showcommands command to show the commands available to the user and admin
show_commands_handler = CommandHandler('showcommands', self.cmd_show_commands, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(show_commands_handler)
# Add handler for the /showbalance command to show the current user's balance
command_text = 'showbalance'
if command_text not in self.disable_commands_list:
show_balance_handler = CommandHandler(command_text, self.cmd_show_balance)
self.application.add_handler(show_balance_handler)
# Pre-checkout handler to final check
self.application.add_handler(PreCheckoutQueryHandler(self.precheckout_callback))
# Add a command to manage user's balance
manage_balance_handler = CommandHandler('managebalance', self.cmd_manage_balance, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(manage_balance_handler)
# Add a command to manage the Stripe payment token
manage_stripe_token_handler = CommandHandler('paytoken', self.cmd_manage_stripe_token, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(manage_stripe_token_handler)
# Command to generate Paypal payment links
command_text = 'paypal'
if command_text not in self.disable_commands_list:
generate_paypal_link_handler = CommandHandler(command_text, self.cmd_generate_paypal_link)
self.application.add_handler(generate_paypal_link_handler)
# Add a command handler that lists all PayPal pending links, restricted to admin users
list_paypal_links_handler = CommandHandler('listpaypal', self.cmd_list_paypal_links, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(list_paypal_links_handler)
# Command to remove paypal links
remove_paypal_link_handler = CommandHandler('removepaypal', self.cmd_remove_paypal_link, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(remove_paypal_link_handler)
# Add a command handler that switches between PayPal live and sandbox environments
switch_paypal_env_command = 'switchpaypal'
switch_paypal_env_handler = CommandHandler(switch_paypal_env_command, self.cmd_switch_paypal_env, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(switch_paypal_env_handler)
# Add a command handler that schedules a function to run recurrently
schedule_function_command = 'schedule'
schedule_function_handler = CommandHandler(schedule_function_command, self.cmd_schedule_function, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(schedule_function_handler)
# add a command handler that unschedules a previously scheduled function
unschedule_function_command = 'unschedule'
unschedule_function_handler = CommandHandler(unschedule_function_command, self.cmd_unschedule_function, filters=filters.User(user_id=self.admins_owner))
self.application.add_handler(unschedule_function_handler)
if not self.disable_command_not_implemented:
self.application.add_handler(MessageHandler(filters.COMMAND, self.default_unknown_command))
except Exception as e:
logger.error(f"Error initializing handlers: {e}")
for admin_id in self.admins_owner:
try:
self.send_message_sync(chat_id=admin_id, message=f"Error initializing handlers: {e}")
except Exception as e:
logger.error(f"Error sending warning to admin {admin_id}: {e}")
return f'Sorry, we have a problem initializing handlers: {e}'
@with_writing_action_sync
def send_message_sync(self, chat_id: int, message: str):
"""Send a message synchronously
Args:
chat_id (int): _description_
message (str): _description_
"""
try:
try:
result = self.loop.run_until_complete(self.application.bot.send_message(chat_id=chat_id, text=message))
except Exception as e:
logger.error(f"Error sending message with markdown: {e}")
result = self.loop.run_until_complete(self.application.bot.send_message(chat_id=chat_id, text=message, parse_mode=None))
return result
except Exception as e:
logger.error(f"Error sending message: {e}")
return f'Sorry, we have a problem sending message: {e}'
# @with_writing_action
def send_message_by_api(self, chat_id: int, message: str):
"""Send a message by raw Telegram API
Args:
chat_id (int): Target telegram user ID to send message
message (str): text of message to send
Returns:
_type_: response of API
"""
response = None
try:
# Define the payload
payload = {
'chat_id': chat_id,
'text': message
}
# Construct the URL for the sendMessage endpoint
telegram_api_base_url = f'https://api.telegram.org/bot{self.token}/sendMessage' if self.token else None
# Send the POST request
response = requests.post(telegram_api_base_url, data=payload)
# Check the response