-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathafxbot.py
1361 lines (1123 loc) · 49.6 KB
/
afxbot.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 python3
## coding=UTF-8
#
# AFX_bot: a simple Telegram bot in Python
# Copyright (C) 2016 Anfauglir Kz. <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = 'Anfauglir'
# TODO:
# 1. anti-flood timer.
# 2. REize all command handler. (optional)
import logging
import telegram
import re
import random
import json
import sqlite3
import string
import http
import hashlib
import urllib
import argparse
from datetime import date, datetime, timedelta
from pathlib import Path
class WashSnake:
"""
This object describes a anti-flood stat for given user.
Attributes:
firsttime (datetime):
content (str):
responded (bool):
repeattimes (Optional[int]):
"""
def __init__(self,
firsttime,
content,
repeattimes=0):
self.firsttime = firsttime
self.content = content
self.responded = False
self.repeattimes = repeattimes
class AFXBot:
"""
This object represents a working Telegram bot.
Arguments:
conf_file_name (Optional[str]):
Name of configuration file.
"""
def __init__(self,
conf_file_name = None,
**kwargs):
# Base. ;)
self.LAST_UPDATE_ID = None
self.NOW_HANDLING_UPDATE_ID = None
self.logger = logging.getLogger()
self.bot = None
self.motds = None
self.config = None
self.strs = None
# Keyword and Symptom lists.
self.kw_list = None
self.kw_list_get = None
self.symptom_tbl = None
self.symptom_get = None
# Unified with symptom entries.
self.unified_kw_list = None
self.unified_get_list = None
# Bot state
self.is_running = True
self.is_accepting_photos = False
# For wash snake
self.wash_record = dict()
# Hardcoded fortune...
self.fortune_strs = ['大凶', '凶', '平', '小吉', '大吉']
self.fortune_types = { '大前天': -3, '大後天': 3, \
'前天': -2, '昨日': -1, '昨天': -1, \
'今日': 0, '今天': 0,
'明日': 1, '明天': 1, '後天': 2}
self.fortune_keys = sorted(self.fortune_types.keys(), \
key = lambda x: len(x), reverse = True)
# Hardcoded Strings...
self.wash_snake_strs_unified = None
self.log_fmt_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# Parse command line params
arg_parser = argparse.ArgumentParser(description = 'AFX_bot, a simple Telegram bot in Python.')
arg_parser.add_argument('-l', '--logfile', help='Logfile Name', action='store_true')
args = arg_parser.parse_args()
if args.logfile:
logging.basicConfig( level=logging.DEBUG, format=self.log_fmt_str, filename=args.logfile)
else:
logging.basicConfig( level=logging.DEBUG, format=self.log_fmt_str)
self.logger = logging.getLogger('AFX_bot')
self.logger.setLevel(logging.DEBUG)
self.init_configuration(conf_file_name)
self.init_l10n_strings()
self.init_motd()
# Telegram Bot Authorization Token
self.bot = telegram.Bot(self.config['bot_token'])
self.register_callbacks()
self.recognition_list = []
def init_hanbao_pet_properties(self,
file_name = None):
if not file_name:
file_name = 'hanbao_pet.json'
try:
with open(file_name, 'r', encoding = 'utf8') as f:
self.config = json.loads(f.read())
# Check Configuration
#configs_check = ['bot_token', 'resp_db', 'adm_ids', 'operational_chats', 'strings_json']
#for c in configs_check:
# self.checkConfigEntry(c)
#list_configs_check = ['restricted_chats', 'motd_only_chats', 'invasive_washsnake_chats']
#for c in list_configs_check:
# self.checkConfigEntryOfList(c)
except FileNotFoundError:
logging.exception('hanbao_pet file not found!')
except ValueError:
logging.exception('hanbao_pet read error.')
except:
raise
def init_configuration(self,
file_name):
"""
Initialize configuration.
Arguments:
file_name (str):
Name of configuration file.
"""
# Load Configuration
if not file_name:
file_name = 'config.json'
try:
with open(file_name, 'r', encoding = 'utf8') as f:
self.config = json.loads(f.read())
# Check Configuration
configs_check = ['bot_token', 'resp_db', 'adm_ids', 'operational_chats', 'strings_json']
for c in configs_check:
self.check_config_entry(c)
list_configs_check = ['restricted_chats', 'motd_only_chats', 'invasive_washsnake_chats']
for c in list_configs_check:
self.check_config_entry_of_list(c)
self.init_resp()
except FileNotFoundError:
logging.exception('config file not found!')
raise
except ValueError:
logging.exception('config read error or item missing!')
raise
except:
raise
def init_l10n_strings(self,
file_name = None):
"""
Initialize L10N strings.
Arguments:
file_name (Optional[str]):
Name of L10N strings file.
"""
# Load L10N Strings (forced now)
if not file_name:
file_name = self.config['strings_json']
if not file_name:
raise Exception('L10N file not specified in neither config nor argument!')
try:
with open(self.config['strings_json'], 'r', encoding = 'utf8') as f:
self.strs = json.loads(f.read())
self.wash_snake_strs_unified = self.strs['r_wash_snake_strs'] + self.strs['r_invasive_wash_snake_strs']
except:
logging.exception('L10N Strings read error!')
raise
def init_motd(self,
file_name = 'motd.json'):
"""
Initialize MotD.
Arguments:
file_name (Optional[str]):
Name of MotD file.
"""
# Load MotD
try:
with open(file_name, 'r', encoding = 'utf8') as f:
self.motds = json.loads(f.read())
# str -> datetime
for k in self.motds.keys():
self.motds[k]['date'] = datetime.strptime(self.motds[k]['date'], '%Y-%m-%d').date()
except FileNotFoundError:
logging.exception('MOTD file not found!')
except ValueError:
logging.exception('MOTD read error!')
except:
raise
if not self.motds:
self.motds = dict()
def check_config_entry(self,
name):
"""
Check whether the config is sane.
"""
if not self.config[name]:
logging.error('config[\'{0}\'] is missing!')
raise ValueError
def check_config_entry_of_list(self,
name):
"""
Check whether the list in config is sane, or init a empty one.
"""
if not self.config[name]:
self.config[name] = []
def run(self):
"""
Run the bot: start the loop to fetch updates and handle.
"""
self.get_latest_update_id()
self.recoverStatus = False
while True:
# This will be our global variable to keep the latest update_id when requesting
# for updates. It starts with the latest update_id if available.
try:
if self.recoverStatus:
# try to reinit...
self.bot = telegram.Bot(self.config['bot_token'])
self.get_latest_update_id()
self.recoverStatus = False
self.get_mesg()
except KeyboardInterrupt:
exit()
except http.client.HTTPException:
logging.exception('!!! EXCEPTION HAS OCCURRED !!!')
self.recover()
except urllib.error.HTTPError:
logging.exception('!!! EXCEPTION HAS OCCURRED !!!')
self.recover()
except Exception as ex:
logging.exception('!!! EXCEPTION HAS OCCURRED !!!')
self.recover()
def recover(self):
"""
Recover the bot in next loop.
"""
self.recoverStatus = True
if self.NOW_HANDLING_UPDATE_ID:
self.LAST_UPDATE_ID = self.NOW_HANDLING_UPDATE_ID + 1
else:
self.LAST_UPDATE_ID = self.LAST_UPDATE_ID + 1
def json_serial(self,
obj):
"""
Returns:
String-serialized datetime or date object.
"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
if isinstance(obj, date):
serial = obj.isoformat()
return serial
raise TypeError ("Type not serializable")
def get_latest_update_id(self):
"""
Get latest update id from Telegram server.
Gonna ignore all previous updates... ;)
"""
try:
updates = self.bot.getUpdates(timeout = 10)
self.logger.debug('update length: {0}'.format(len(updates)))
if len(updates) == 1:
self.LAST_UPDATE_ID = updates[-1].update_id
else:
while(len(updates) > 1):
self.LAST_UPDATE_ID = updates[-1].update_id
updates = self.bot.getUpdates(offset=self.LAST_UPDATE_ID+1, timeout = 10)
self.logger.debug('update length: {0}'.format(len(updates)))
except:
self.logger.exception('!!! Get Last update ID Error !!!')
def init_resp(self):
"""
Read all keywords/symptoms from self.resp_db.
"""
self.logger.debug('Initializing response...')
self.resp_db = sqlite3.connect(self.config['resp_db'])
self.resp_db.row_factory = sqlite3.Row
c = self.resp_db.cursor()
self.kw_list = list()
c.execute('SELECT keyword FROM resp GROUP BY keyword ORDER BY RANDOM() DESC;')
for kw in c:
self.kw_list.append(kw['keyword'])
self.kw_list_get = list()
c.execute('SELECT keyword FROM resp_get GROUP BY keyword ORDER BY RANDOM() DESC;')
for kw in c:
self.kw_list_get.append(kw['keyword'])
self.symptom_tbl = dict()
c.execute('SELECT before, after FROM symptom ORDER BY LENGTH(before) DESC;')
for syms in c:
self.symptom_tbl[syms['before']] = syms['after']
self.symptom_get = dict()
c.execute('SELECT before, after FROM symptom_get ORDER BY LENGTH(before) DESC;')
for syms in c:
self.symptom_get[syms['before']] = syms['after']
self.unified_kw_list = self.kw_list + list(self.symptom_tbl.keys())
self.unified_get_list = self.kw_list_get + list(self.symptom_get.keys())
def send_generic_mesg(self,
chat_id,
text,
reply_to_message_id = None):
"""
For sending simple messages only including text (in most cases.)
"""
self.bot.sendMessage(chat_id = chat_id, text = text, reply_to_message_id = reply_to_message_id)
def get_mesg(self):
"""
Fetch updates from server for further processes.
"""
# Request updates after the last updated_id
for update in self.bot.getUpdates(offset=self.LAST_UPDATE_ID, timeout=10):
self.logger.info('Update: ' + str(update));
# chat_id is required to reply any message
chat_id = update.message.chat_id
message = update.message.text
mesg_id = update.message.message_id
user_id = update.message.from_user.id
self.NOW_HANDLING_UPDATE_ID = update.update_id
self.logger.debug('now handling update: {0}'.format(self.NOW_HANDLING_UPDATE_ID))
try:
if message:
# YOU SHALL NOT PASS!
# Only authorized group chats and users (admins) can access this bot.
if not self.do_augmented_auth(update.message.chat.id):
if '__FOR_RECOGNITION__' in message and not update.message.chat.id in self.recognition_list:
self.send_generic_mesg(chat_id, 'Please contact moderator to add following id into ACL.')
self.send_generic_mesg(chat_id, str(update.message.chat.id))
self.recognition_list.append(update.message.chat.id)
else:
self.logger.info('Access denied from: ' + str(update.message.chat.id))
elif self.handle_washsnake(update):
nothing_todo = 1
# Status querying.
elif self.strs['q_status_kw'] in message:
if self.is_running:
self.send_generic_mesg(chat_id, self.strs['qr_status_t'], mesg_id)
else:
self.send_generic_mesg(chat_id, self.strs['qr_status_f'], mesg_id)
# Only admins can re-enable bot.
elif not self.is_running and message.startswith(self.strs['s_status_t_kw']) and self.do_adm_auth(user_id):
self.send_generic_mesg(chat_id, self.strs['sr_status_t_ok'], mesg_id)
self.init_resp()
self.is_running = True
# MOTDs are necessary.
elif message.lower().startswith('/motd') or self.is_handle_motd(message):
self.handle_motd(update)
# Only MOTD for some special groups, otherwise...
elif self.is_running and self.do_operational_auth(update.message.chat.id):
# Batch update *.jpg in /images/
if message.startswith(self.strs['v_photo_bulkupload']) and self.do_adm_auth(user_id):
p = Path('images')
fl = list(p.glob('*.jpg'))
if len(fl) == 0:
self.send_generic_mesg(chat_id, self.strs['vr_photo_bulkupload_no_file'], mesg_id)
else:
for image_name in fl:
# for uploading new photos
with open(str(image_name), 'rb') as nn:
photo_res = self.bot.sendPhoto(chat_id = chat_id, photo = nn)
photo_mesg = photo_res.photo[-1].file_id
self.send_generic_mesg(chat_id, photo_mesg, photo_res.message_id)
# Reload keyword table
# Disable bot
# Enter/Exit photo upload mode
# Handle ADM cmd/Common cmd/Fortune tell
elif self.execute_callbacks(self.bot_callbacks, update):
nothing_todo = 1
# other...
else:
self.handle_response(update)
elif self.is_running and update.message.chat.id in self.config['restricted_chats']:
if self.execute_callbacks(self.bot_callbacks_restricted, update):
nothing_todo = 1
elif self.is_running:
self.logger.debug('Not handling, in motd_only chats?')
else:
self.logger.debug('Not running...')
# upload photo, adm only
elif update.message.photo and self.is_accepting_photos and self.do_adm_auth(user_id):
try:
self.logger.debug('PhotoContent: ' + update.message.photo[-1].file_id);
photo_mesg = update.message.photo[-1].file_id
photo_res = self.bot.sendPhoto(chat_id = chat_id, photo = photo_mesg)
photo_mesg = photo_res.photo[-1].file_id
self.send_generic_mesg(chat_id, photo_mesg, photo_res.message_id)
except:
nothing_todo = 1
#else:
# self.logger.debug('NotHandleContent: ' + str(update.message));
except:
if chat_id != None and mesg_id != None:
self.send_generic_mesg(chat_id, self.append_more_smiles('好像哪裡怪怪der '), mesg_id)
self.logger.exception('')
# Updates global offset to get the new updates
self.LAST_UPDATE_ID = self.NOW_HANDLING_UPDATE_ID + 1
def is_handle_motd(self,
mesg):
"""
Returns:
True when strings in self.strs['q_motd_kws'] found in mesg, otherwise False.
"""
for m in self.strs['q_motd_kws']:
if m in mesg:
return True
return False
def match_fortune_type(self,
mesg):
"""
Returns:
Strings in self.fortune_types found in mesg, otherwise None.
"""
for fs in self.fortune_keys:
if (fs + '運勢') in mesg:
return fs
return None
def do_adm_auth(self,
id):
"""
Returns:
Presence of id in self.config['adm_ids'].
"""
return id in self.config['adm_ids']
def do_operational_auth(self,
id):
"""
Returns:
Presence of id in self.config['operational_chats'],
self.config['adm_ids']
"""
return id in self.config['operational_chats'] \
or id in self.config['adm_ids']
def do_augmented_auth(self,
id):
"""
Returns:
Presence of id in self.config['operational_chats'],
self.config['adm_ids'],
self.config['restricted_chats'],
or self.config['motd_only_chats'].
"""
return id in self.config['operational_chats'] \
or id in self.config['adm_ids'] \
or id in self.config['restricted_chats'] \
or id in self.config['motd_only_chats']
def append_more_smiles(self,
str,
rl = 1,
ru = 3):
"""
Returns:
str with smiles in amount of random(rl, ru) appended on the tail.
"""
return str + '\U0001F603' * random.randint(rl, ru)
def handle_adm_cmd(self,
update):
"""
Handles all administrative commands.
Args:
update (telegram.update):
Update object to handle.
"""
chat_id = update.message.chat_id
mesg = update.message.text.strip()
mesg_id = update.message.message_id
cmd_toks = [x.strip() for x in mesg.split(' ')]
while '' in cmd_toks:
cmd_toks.remove('')
cmd_entity = cmd_toks[1].lower()
c = self.resp_db.cursor()
self.logger.debug('cmd_entity: ' + cmd_entity)
# 憨包來吃圖
if cmd_entity == 'begin_get':
self.set_is_accepting_photos(True)
# 憨包吃飽沒
elif cmd_entity == 'end_get':
self.set_is_accepting_photos(False)
elif cmd_entity == 'mk_get':
# for multi-group.
gid = chat_id
if gid > 0:
gid = -1
pic_id = cmd_toks[2]
kw = cmd_toks[3].lower()
if len(cmd_toks) > 4:
tag = cmd_toks[4].lower()
else:
tag = None
try:
self.logger.debug('Photo ID = ' + cmd_toks[2])
photo_res = self.bot.sendPhoto(chat_id = chat_id, reply_to_message_id = mesg_id, photo = cmd_toks[2]);
if kw in self.symptom_get.keys():
self.send_generic_mesg(chat_id, '({0} -> {1}) => {2}'.format(kw, self.symptom_get[kw], pic_id), photo_res.message_id)
kw = self.symptom_get[kw]
else:
self.send_generic_mesg(chat_id, '{0} => {1}'.format(kw, pic_id), photo_res.message_id)
c.execute('''INSERT INTO resp_get (keyword, cont, tag, gid) VALUES (?, ?, ?, ?) ''', ( kw, pic_id, tag, gid))
self.resp_db.commit()
self.init_resp()
except TelegramError:
self.send_generic_mesg(chat_id, 'ERROR ON : {0} => {1}'.format(kw, pic_id), photo_res.message_id)
elif cmd_entity == 'getpic_id':
pic_id = cmd_toks[2]
try:
photo_res = self.bot.sendPhoto(chat_id = chat_id, reply_to_message_id = mesg_id, photo = pic_id);
except TelegramError:
self.send_generic_mesg(chat_id, 'ERROR ON : {0}'.format(pic_id), photo_res.message_id)
elif cmd_entity == 'ed_get':
not_implemented = 1
# make get symptom -> keyword
elif cmd_entity == 'mk_get_sym':
if len(cmd_toks) > 3:
kw_before = cmd_toks[2].lower()
kw_after = cmd_toks[3].lower()
else:
not_implemented = 1
# list /get kw
elif cmd_entity == 'ls_get':
if len(cmd_toks) > 2:
outmesg = ''
kw = cmd_toks[2].lower()
if kw in self.symptom_get.keys():
outmesg += '({0} -> {1}) => \n'.format(kw, self.symptom_get[kw])
kw = self.symptom_get[kw]
else:
outmesg += '{0} => \n'.format(kw)
c.execute('''SELECT IIDX, cont, tag FROM resp_get WHERE keyword = ? ORDER BY IIDX ASC;''', (kw, ))
for conts in c:
if not conts['tag']:
outmesg += '/getid_' + str(conts['IIDX']) + ' : ' + conts['cont'][:8] + '...' + conts['cont'][-8:] + ' (N/A)\n'
else:
outmesg += '/getid_' + str(conts['IIDX']) + ' : ' + conts['cont'][:8] + '...' + conts['cont'][-8:] + '(' + conts['tag'] + ')\n'
self.send_generic_mesg(chat_id, outmesg, mesg_id)
else:
outmesg = 'Supported /get keywords:\n'
s_keys = self.symptom_get.keys()
for kw in self.unified_get_list:
if kw in s_keys:
outmesg = outmesg + kw + ' -> ' + self.symptom_get[kw] + '\n'
else:
outmesg = outmesg + kw + '\n'
self.send_generic_mesg(chat_id, outmesg, mesg_id)
# make keyword -> content
# ^/adm\s+mk_kw\s+([^\s]+)\s+(.+)$
elif cmd_entity == 'mk_kw':
if len(cmd_toks) > 3:
kw = cmd_toks[2].lower()
content = mesg[(mesg.find(cmd_toks[2]) + len(cmd_toks[2]) + 1):].strip()
if kw in self.symptom_tbl.keys():
self.send_generic_mesg(chat_id, '({0} -> {1}) => {2}'.format(kw, self.symptom_tbl[kw], content), mesg_id)
kw = self.symptom_tbl[kw]
else:
self.send_generic_mesg(chat_id, '{0} => {1}'.format(kw, content), mesg_id)
c.execute('''INSERT INTO resp (keyword, cont) VALUES (?, ?) ''', ( kw, content, ))
self.resp_db.commit()
self.init_resp()
else:
self.send_generic_mesg(chat_id, 'arglist err.', mesg_id)
# make symptom -> keyword
# ^/adm\s+mk_sym\s+([^\s]+)\s+([^\s]+).*$
elif cmd_entity == 'mk_sym':
if len(cmd_toks) > 3:
kw_before = cmd_toks[2].lower()
kw_after = cmd_toks[3].lower()
if kw_before in self.symptom_tbl.keys():
self.send_generic_mesg(chat_id, 'Already exists: ({0} -> …) => …'.format(kw_before), mesg_id)
elif kw_before in self.kw_list:
self.send_generic_mesg(chat_id, 'Already exists: {0} => …'.format(kw_before), mesg_id)
else:
self.send_generic_mesg(chat_id, '{0} => {1}'.format(kw_before, kw_after), mesg_id)
c.execute('''INSERT INTO symptom (before, after) VALUES (?, ?) ''', ( kw_before, kw_after, ))
self.resp_db.commit()
self.init_resp()
else:
self.send_generic_mesg(chat_id, 'arglist err.', mesg_id)
# make symptom -> keyword
# ^/adm\s+mk_sym\s+([^\s]+)\s+([^\s]+).*$
elif cmd_entity == 'mk_get_sym':
if len(cmd_toks) > 3:
kw_before = cmd_toks[2].lower()
kw_after = cmd_toks[3].lower()
self.send_generic_mesg(chat_id, 'Not implemented.\n({0} -> {1}) => …'.format(kw_before, kw_after), mesg_id)
else:
self.send_generic_mesg(chat_id, 'arglist err.', mesg_id)
# todo: assign index for each kw -> cont pair.
elif cmd_entity == 'rm_kw':
if len(cmd_toks) > 2:
try:
to_rm = int(cmd_toks[2].lower())
c.execute('''DELETE FROM resp WHERE IIDX = ? ''', ( to_rm, ))
self.resp_db.commit()
self.init_resp()
self.send_generic_mesg(chat_id, str(to_rm) + ' deleted.', mesg_id)
except ValueError:
self.send_generic_mesg(chat_id, 'arg err.', mesg_id)
else:
self.send_generic_mesg(chat_id, 'arglist err.', mesg_id)
elif cmd_entity == 'rm_get':
if len(cmd_toks) > 2:
try:
to_rm = int(cmd_toks[2].lower())
c.execute('''DELETE FROM resp_get WHERE IIDX = ? ''', ( to_rm, ))
self.resp_db.commit()
self.init_resp()
self.send_generic_mesg(chat_id, str(to_rm) + ' deleted.', mesg_id)
except ValueError:
self.send_generic_mesg(chat_id, 'arg err.', mesg_id)
else:
self.send_generic_mesg(chat_id, 'arglist err.', mesg_id)
elif cmd_entity == 'rm_get_sym':
not_implemented = 1
# list keyword
elif cmd_entity == 'ls_kw':
s_keys = self.symptom_tbl.keys()
if len(cmd_toks) > 2:
outmesg = ''
kw = cmd_toks[2].lower()
if kw in self.symptom_get.keys():
outmesg += '({0} -> {1}) => \n'.format(kw, self.symptom_tbl[kw])
kw = self.symptom_tbl[kw]
else:
outmesg += '{0} => \n'.format(kw)
c.execute('''SELECT IIDX, cont FROM resp WHERE keyword = ? ORDER BY IIDX ASC;''', (kw, ))
for conts in c:
outmesg += str(conts['IIDX']) + '. ' + conts['cont'] + '\n'
self.send_generic_mesg(chat_id, outmesg, mesg_id)
else:
outmesg = 'Supported keywords:\n'
for kw in self.unified_kw_list:
if kw in s_keys:
outmesg = outmesg + kw + ' -> ' + self.symptom_tbl[kw] + '\n'
else:
outmesg = outmesg + kw + '\n'
self.send_generic_mesg(chat_id, outmesg, mesg_id)
else:
self.send_generic_mesg(chat_id, 'adm what? owo', mesg_id)
def handle_cmd(self,
update):
"""
Handles all common commands.
Args:
update (telegram.update):
Update object to handle.
Returns:
True when the command is handled, otherwise False.
"""
chat_id = update.message.chat_id
restricted = not self.do_operational_auth(chat_id)
mesg = update.message.text
mesg_id = update.message.message_id
mesg_low = mesg.lower().replace('@afx_bot', '')
cmd_toks = [x.strip() for x in mesg.split(' ')]
while '' in cmd_toks:
cmd_toks.remove('')
if mesg_low.startswith('/get ') and not restricted:
keyword = cmd_toks[1].lower()
if len(cmd_toks) > 2:
tag = cmd_toks[2].lower()
self.logger.debug('keyword: ' + keyword)
self.logger.debug('tag: ' + tag)
else:
tag = None
self.logger.debug('keyword: ' + keyword)
if keyword in self.symptom_get.keys():
keyword = self.symptom_get[keyword]
if keyword in self.kw_list_get:
c = self.resp_db.cursor()
x = None
if tag :
c.execute('''SELECT cont FROM resp_get WHERE keyword = ? AND tag = ? ORDER BY RANDOM() LIMIT 1;''', ( keyword, tag, ))
x = c.fetchone()
if not x:
c.execute('''SELECT cont FROM resp_get WHERE keyword = ? ORDER BY RANDOM() LIMIT 1;''', ( keyword, ))
x = c.fetchone()
if x:
self.bot.sendPhoto(chat_id = chat_id, reply_to_message_id = mesg_id, photo = str(x['cont']));
else:
self.send_generic_mesg(chat_id, 'Something goes wrong! D:', mesg_id)
else:
self.send_generic_mesg(chat_id, self.append_more_smiles('You get nothing! '), mesg_id)
return True
# Get picture directly by given resp ID.
elif mesg_low.startswith('/getid') and not restricted:
if len(cmd_toks) > 1:
res_get_id = cmd_toks[1]
else:
res_get_id = mesg_low[7:]
c = self.resp_db.cursor()
c.execute('''SELECT cont FROM resp_get WHERE IIDX = ? LIMIT 1;''', (res_get_id,))
x = c.fetchone()
if x:
self.bot.sendPhoto(chat_id=chat_id, reply_to_message_id=mesg_id, photo=str(x['cont']));
else:
self.send_generic_mesg(chat_id, self.append_more_smiles('You get nothing! '), mesg_id)
return True
elif mesg == '/roll@AFX_bot':
self.send_generic_mesg(chat_id, self.strs['r_roll_cmd_help'], mesg_id)
return True
elif mesg_low.startswith('/roll ') or mesg_low == '/roll':
return self.handle_roll(update)
elif mesg == '/crash':
raise Exception('Crash!')
return False
def handle_response(self,
update):
"""
Handles all typical responses.
Args:
update (telegram.update):
Update object to handle.
Returns:
True when the command is handled, otherwise False.
"""
chat_id = update.message.chat_id
mesg = update.message.text
mesg_id = update.message.message_id
user_id = update.message.from_user.id
mesg_low = mesg.lower()
# hardcoded...
if 'ass' in mesg_low and not 'pass' in mesg_low:
self.send_generic_mesg(chat_id, 'Ood', mesg_id)
return True
if user_id == 99786298 and chat_id == -1001069764018:
self.send_generic_mesg(chat_id, '喔喔', mesg_id)
return True
if ('蕉姐' in mesg_low or '蕉姊' in mesg_low or '香蕉' in mesg_low) and ('幾' in mesg_low or '多少' in mesg_low) :
self.send_generic_mesg(chat_id, '3064', mesg_id)
return True
random.shuffle(self.unified_kw_list)
s_keys = self.symptom_tbl.keys()
# convert kw
for kw in self.unified_kw_list:
if kw in mesg_low:
if kw in s_keys:
unified_kw = self.symptom_tbl[kw]
self.logger.debug('keyword: ' + kw + ' -> ' + unified_kw)
else:
unified_kw = kw
self.logger.debug('keyword: ' + kw )
c = self.resp_db.cursor()
c.execute('''SELECT cont FROM resp WHERE keyword = ? ORDER BY RANDOM() LIMIT 1;''', ( unified_kw, ))
x = c.fetchone()
self.send_generic_mesg(chat_id, str(x['cont']), mesg_id)
return True
return False
def handle_roll(self,
update):
"""
Handles /roll commands.
Args:
update (telegram.update):
Update object to handle.
"""
chat_id = update.message.chat_id
mesg_low = update.message.text.lower()
mesg_id = update.message.message_id
if mesg_low == '/roll':
d_cmd = ''
else:
d_cmd = mesg_low[6:].strip()
# XdYsZ
res = re.match('([0-9]+)d([0-9]+)s([0-9]+)', d_cmd)
if res:
dn = int(res.group(1))
dt = int(res.group(2))
ds = int(res.group(3))
dstr = '('
succ = 0
if dn > 100: dn = 100
for i in range(dn):
val = random.randint(1, dt)
if val >= ds: succ += 1
dstr += str(val) + ', '
dstr = '{0}d{1}s{2} : {3}) >= {2}, 成功 {4} 次'.format(dn, dt, ds, dstr[:-2], succ);
self.send_generic_mesg(chat_id, dstr, mesg_id)
return True
# XdY[+-Z]
res = re.match('([0-9]+)d([0-9]+)([+-][0-9]+)?', d_cmd)
if res:
dn = int(res.group(1))
dt = int(res.group(2))
if res.group(3):
dm = int(res.group(3))
else:
dm = 0;
dstr = '('
sum = 0
if dn > 100: dn = 100
for i in range(dn):
val = random.randint(1, dt)
sum += val
dstr += str(val) + ', '
if dm == 0:
dstr = '{0}d{1} : {2}) = {3}'.format(dn, dt, dstr[:-2], sum);
else:
if dm > 0:
dm_str = '+' + str(dm)
else:
dm_str = str(dm)
dstr = '{0}d{1}{2} : {3}) {2} = {4} {2} = {5}'.format(dn, dt, dm_str, dstr[:-2], sum, sum+dm);
self.send_generic_mesg(chat_id, dstr, mesg_id)
return True
# X[-Y]
res = re.match('([0-9]+)(-([0-9]+))?', d_cmd)
if res:
if res.group(3):
dl = int(res.group(1))
du = int(res.group(3))
else:
dl = 1