-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWindows-WB.py
1894 lines (1630 loc) · 53.5 KB
/
Windows-WB.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
# -*- coding:utf-8 -*-
import websocket,json,requests,rel,sqlite3,subprocess
import random,traceback
import sys
from datetime import datetime
from pytz import timezone
from threading import Thread
from bs4 import BeautifulSoup
from colorama import init
from Functions.gosenchoyen.generator import genImage
from Functions.arcaea.arcaea import *
from Functions.pjsk.pjsk import *
from Functions.maiCN.maimaiDX import *
from Functions.rss.rssPush import *
websocket._logging._logger.level = -99
init(autoreset = True)
'''Initialize Autohibernate'''
undisturbed_hb = 0
'''Initialize TickScheduler'''
global_event_tick = 0
'''Local Resource Path'''
project_path = os.path.join(os.path.dirname(__file__))
resource_path = os.path.join(project_path,'Resources')
'''Initialize Bot Config'''
try:
wb_config_path = os.path.join(project_path,'config.json')
json.load(open(wb_config_path))
except FileNotFoundError:
# Generate WB config file
with open(wb_config_path, 'w', encoding = 'utf-8') as f:
init_config = { "botName": "YOUR TRIGGER FOR GROUPCHAT",
"botDMTrigger": "YOUR TRIGGER FOR DM",
"Sudoers": ["YOUR WXID"],
"wxIP": "127.0.0.1",
"wxPort": "5555"}
f.write(json.dumps(init_config,ensure_ascii = False, indent = 4))
print("Assuming running for the first time. Generating WB Config")
time.sleep(5)
sys.exit()
'''WindBot Config'''
wb_config = json.load(open(wb_config_path))
BOT_NAME = wb_config["botName"]
BOT_GC_TRIGGER = f"@{BOT_NAME}"
BOT_DM_TRIGGER = wb_config["botDMTrigger"]
SUDO_LIST = wb_config["Sudoers"]
FUNTOOL_IP = wb_config["wxIP"]
FUNTOOL_PORT = wb_config["wxPort"]
'''Msg Codes'''
SERVER = f"ws://{FUNTOOL_IP}:{FUNTOOL_PORT}"
HEART_BEAT = 5005
RECV_TXT_MSG = 1
RECV_TXT_CITE_MSG = 49
RECV_PIC_MSG = 3
USER_LIST = 5000
GET_USER_LIST_SUCCSESS = 5001
GET_USER_LIST_FAIL = 5002
TXT_MSG = 555
PIC_MSG = 500
AT_MSG = 550
CHATROOM_MEMBER = 5010
CHATROOM_MEMBER_NICK = 5020
PERSONAL_INFO = 6500
DEBUG_SWITCH = 6000
PERSONAL_DETAIL = 6550
DESTROY_ALL = 9999
STATUS_MSG = 10000
ATTATCH_FILE = 5003
# 'type':49 带引用的消息
'''Recent Logs List'''
latest_logs = []
################################# OUTPUT&SQL ################################
def getid():
return time.strftime("%Y%m%d%H%M%S")
def output(msg,logtype = 'SYSTEM',mode = 'DEFAULT',background = 'DEFAULT'):
LogColor = {
'SYSTEM': '034',
'ERROR': '037',
'GROUPCHAT': '036',
'DM' : '033',
'HEART_BEAT': '035',
'PAT': '037',
'SEND': '032',
'CALL' : '031',
'WARNING': '031',
'CREATE_LINK':'032',
'STOP_LINK':'031',
'RSS': '037'
}
LogMode = {
'DEFAULT': '0',
'HIGHLIGHT': '1',
'UNDERLINE': '4'
}
LogBG = {
'DEFAULT': '',
'RED' : ';41',
'YELLOW' : ';43',
'BLUE' : ';44',
'WHITE' : ';47',
'GREEN' : ';42',
'MINT' : ';46',
'PURPLE' : ';45'
}
color = LogColor.get(logtype)
mode = LogMode.get(mode)
bg = LogBG.get(background)
now = time.strftime("%Y-%m-%d %X")
# Shorten logs of too long messages
line_cnt = msg.count('\n') + 1
if line_cnt > 10 and logtype != 'ERROR':
msg = "\n".join(msg.split("\n")[:10])
msg += '\n......'
print(f"[{now} \033[{mode};{color}{bg}m{logtype}\033[0m] {msg}")
# Write Error Logs on to Local File
if logtype == 'ERROR':
error_log_file = open('ErrorLog.txt','a')
error_log_file.write(f"[{now} {logtype}] {msg}\n")
error_log_file.close()
# Store Log into latest_logs list
if logtype != 'HEART_BEAT':
if len(latest_logs) == 20:
latest_logs.pop(0)
latest_logs.append(f"[{now} {logtype}] {msg}")
# print("["+f"{color}[1;35m{LogType}{color}[0m"+"]"+' Success')
def sql_insert(db,dbcur,\
table: str,\
rows: list,\
values: list):
'''
Pre-Process
'''
# table = f'r{table[:-9]}'
test_row = rows[-1]
test_value = values[-1]
rows = str(rows)[1:-1].replace('\'','')
values = str(values)[1:-1]
'''
Check if line exsists
'''
if isinstance(test_value,str):
check_txt = f"SELECT 1 FROM {table} WHERE {test_row}='{test_value}'"
else:
check_txt = f"SELECT 1 FROM {table} WHERE {test_row}={test_value}"
# output(check_txt)
dbcur.execute(check_txt)
result = dbcur.fetchone()
# output(result,mode = 'HIGHLIGHT')
'''
Value Exists or not
'''
if result:
# output('Skipping This Insert Because Column Exists','WARNING')
return
else:
insert_txt = f"INSERT INTO {table}({rows}) VALUES({values})"
# print(insert_txt)
db.execute(insert_txt)
db.commit()
def sql_update(db, table: str, col: str, value: str, condition: str = None):
# table = f'r{table[:-9]}'
# col = str(col).replace('\'','')
if isinstance(value,str):
if condition:
update_txt = f"UPDATE {table} SET {col} = '{value}' WHERE {condition}"
else:
update_txt = f"UPDATE {table} SET {col} = '{value}'"
else:
if condition:
update_txt = f"UPDATE {table} SET {col} = {value} WHERE {condition}"
else:
update_txt = f"UPDATE {table} SET {col} = {value}"
# output(update_txt,mode = 'HIGHLIGHT')
db.execute(update_txt)
db.commit()
def sql_fetch(dbcur, table: str, cols: list = None, condition: str = None):
if not cols:
cols = ['*']
cols = str(cols)[1:-1].replace('\'','')
if condition:
fetch_txt = f"SELECT {cols} FROM {table} WHERE {condition}"
else:
fetch_txt = f"SELECT {cols} FROM {table}"
# output(fetch_txt,mode = 'HIGHLIGHT')
dbcur.execute(fetch_txt)
result = dbcur.fetchall()
return [i for i in result]
def sql_match(db,dbcur,\
table: str,\
cols: list = ['*'],\
conditionCol = None,\
keyword = None):
if not keyword:
return ['-1']
elif not conditionCol:
return ['-1']
source = db
db = sqlite3.connect(":memory:")
db.backup(source)
dbcur = db.cursor()
dbcur.execute('DROP TABLE IF EXISTS fuzzysearch')
fetchcols = cols
fetchcols.append(conditionCol)
origin_data = sql_fetch(dbcur,table,fetchcols)
# output(origin_data)
cols = str(cols)[1:-1].replace('\'','')
fetchcols_str = str(fetchcols)[1:-1].replace('\'','')
dbcur.execute(f'create virtual table fuzzysearch using fts5({fetchcols_str}, tokenize="porter unicode61");')
for row in origin_data:
# output(str(row)[1:-1])
dbcur.execute(f'insert into fuzzysearch ({fetchcols_str}) values ({str(row)[1:-1]});')
db.commit()
if isinstance(keyword,str):
match_txt = f"SELECT {cols} FROM fuzzysearch WHERE {conditionCol} MATCH '{keyword}*'"
else:
match_txt = f"SELECT {cols} FROM fuzzysearch WHERE {conditionCol} MATCH {keyword}*"
# output(match_txt)
result = dbcur.execute(match_txt).fetchall()
# output(result)
dbcur.execute('DROP TABLE IF EXISTS fuzzysearch')
db.commit()
return [i for i in result]
def sql_destroy(db,table: str):
destroy_txt = f"DROP TABLE {table}"
db.execute(destroy_txt)
db.commit()
def sql_delete(db, table: str, condition: str = None):
if not condition:
output('Did not specify which delete condition.','WARNING',\
background = "WHITE")
return ['-1']
delete_txt = f"DELETE FROM {table} WHERE {condition}"
db.execute(delete_txt)
db.commit()
################################### HTTP ####################################
def send(uri,data):
base_data={
'id':getid(),
'type':'null',
'roomid':'null',
'wxid':'null',
'content':'null',
'nickname':'null',
'ext':'null',
}
base_data.update(data)
url=f'http://{ip}:{port}/{uri}'
res=requests.post(url,json={'para':base_data},timeout=5)
return res.json()
def get_member_nick(roomid = 'null',wxid = None):
# 获取指定群的成员的昵称 或 微信好友的昵称
uri='api/getmembernick'
data={
'type':CHATROOM_MEMBER_NICK,
'wxid':wxid,
'roomid':roomid or 'null'
}
respJson=send(uri,data)
return json.loads(respJson['content'])['nick']
################################# websocket #################################
def debug_switch():
qs={
'id':getid(),
'type':DEBUG_SWITCH,
'content':'off',
'wxid':'ROOT',
}
return json.dumps(qs)
def get_chat_nick_p(wxid,roomid):
qs={
'id':getid(),
'type':CHATROOM_MEMBER_NICK,
'wxid': wxid,
'roomid' : f'{roomid}@chatroom',
'content' : 'null',
'nickname':'null',
'ext':'null'
}
return json.dumps(qs)
def handle_chat_nick(j):
data=eval(j['content'])
nickname = data['nick']
wxid = data['wxid']
roomid = data['roomid']
sql_update(conn,f'r{roomid[:-9]}','groupUsrName',nickname,\
f"wxid = '{wxid}'")
def get_chatroom_memberlist(roomid = 'null'):
qs={
'id':getid(),
'type':CHATROOM_MEMBER,
'roomid': roomid,
'wxid':'null',
'content':'op:list member',
'nickname':'null',
'ext':'null'
}
# 'content':'op:list member',
return json.dumps(qs)
def handle_memberlist(j):
data=j['content']
for d in data:
roomid = d['room_id']
room_num = roomid[:-9]
# output(f'roomid:{roomid}')
members = d['member']
sql_initialize_group(f'r{room_num}')
for m in members:
sql_insert(conn,cur,f'r{room_num}',['wxid'],[m])
sql_insert(conn,cur,'Users',['wxid'],[m])
ws.send(get_chat_nick_p(m,room_num))
def get_personal_detail(wxid):
qs={
'id':getid(),
'type':PERSONAL_DETAIL,
# 'content':'op:personal detail',
'wxid': wxid,
'roomid':'null',
'content':'null',
'nickname':'null',
'ext':'null',
}
return json.dumps(qs)
def handle_personal_detail(j):
output(j)
def get_personal_info():
qs={
'id':getid(),
'type':PERSONAL_INFO,
'content':'null',
'wxid': wxid,
'roomid':'null',
'content':'null',
'nickname':'null',
'ext':'null',
}
return json.dumps(qs)
def handle_personal_info(j):
output(j)
def send_wxuser_list():
'''
获取微信通讯录用户名字和wxid
'''
qs={
'id':getid(),
'type':USER_LIST,
'roomid':'null',
'wxid':'null',
'content':'null',
'nickname':'null',
'ext':'null',
}
return json.dumps(qs)
def handle_wxuser_list(j):
i=0
for item in j['content']:
i+=1
output(f"[{i}] {item['wxid']} {item['name']}")
# If item is chatroom
if item['wxid'][-8:] == 'chatroom':
room_id = item['wxid'][:-9]
group_name = item['name']
# Get if groupchat exist in record
res = sql_fetch(cur,'Groupchats',['*'],f"roomid = '{room_id}'")
# Does not exist, insert groupchat info into record
if len(res) == 0:
sql_insert(conn,cur,'Groupchats',\
['roomid','groupname','announce','rssPush'],\
[room_id,group_name,1,0])
# Exists, update groupchat infomation
else:
sql_update(conn,'Groupchats','groupname',group_name,\
f"roomid = '{room_id}'")
# If item is single user
else:
sql_insert(conn,cur,'Users',['wxid','wxcode','realUsrName'],\
[item['wxid'],item['wxcode'],item['name']])
# Recursively start to update chatroom's members
ws.send(get_chatroom_memberlist(item['wxid']))
################################# INITIALIZE ###############################
# Hearbeat every min
def heartbeat_trigger(msgJson):
global undisturbed_hb, global_event_tick
undisturbed_hb += 1
global_event_tick += 1
# Local Log of Heartbeat
if undisturbed_hb < 5:
output('Success','HEART_BEAT','HIGHLIGHT')
elif undisturbed_hb == 5:
output('Undisturbed in 5 min. Hiding heartbeat logs. zZZ',logtype = 'HEART_BEAT',mode = 'HIGHLIGHT')
# Every 60 min, Trigger a User Database Refresh
if global_event_tick % 60 == 0 and global_event_tick != 0:
ws.send(send_wxuser_list())
global_event_tick = 0
# Every 30 min, Trigger a rss fetch
if global_event_tick % 30 == 0 and global_event_tick != 0:
tRss = Thread(target = rss_trigger, args = ())
tRss.start()
# Every 15 min, Trigger a battery check
if global_event_tick % 15 == 0 and global_event_tick != 0:
tBtry = Thread(target = btry_check_auto, args = ())
tBtry.start()
# When windbot is ran
def on_open(ws):
#初始化 更新用户数据
ws.send(send_wxuser_list())
# Update Global Admin List
for wxid in SUDO_LIST:
sql_update(conn,'Users','powerLevel',3,f"wxid = '{wxid}'")
now=time.strftime("%Y-%m-%d %X")
ws.send(send_txt_msg(f'启动完成\n{now}',SUDO_LIST[0]))
# ASCII Art Credit: FigLet & Me
start_ascii_art = """
#######################################################
# ___ ______ ________________ _____ #
# __ | / /__(_)____________ /__ __ )_______ /_ #
# __ | /| / /__ /__ __ \ __ /__ __ | __ \ __/ #
# __ |/ |/ / _ / _ / / / /_/ / _ /_/ // /_/ / /_ #
# ____/|__/ /_/ /_/ /_/\__,_/ /_____/ \____/\__/ #
# #
#######################################################
"""
print(start_ascii_art)
# Windbot Connection Error (unlikely)
def on_error(ws,error):
output(f"on_error:{error}",'ERROR','HIGHLIGHT','RED')
# Windbot Connection Close (very unlikely)
def on_close(ws,signal,status):
output("Server Closed",'WARNING','HIGHLIGHT','WHITE')
# Initialize the SQL Structures. Group-Specific Table
def sql_initialize_group(roomid):
initialize_group = f'''CREATE TABLE IF NOT EXISTS {roomid}
(wxid TEXT,
groupUsrName TEXT);'''
conn.execute(initialize_group)
conn.commit()
# Initialize the SQL Structures. Users Table
def sql_initialize_users():
initialize_users = f'''CREATE TABLE IF NOT EXISTS Users
(wxid TEXT,
wxcode TEXT,
realUsrName TEXT,
patTimes NUMBER NOT NULL DEFAULT 0,
patAction TEXT NOT NULL DEFAULT -1,
arcID NUMBER NOT NULL DEFAULT -1,
qqID NUMBER NOT NULL DEFAULT -1,
pjskID NUMBER NOT NULL DEFAULT -1,
maiID TEXT NOT NULL DEFAULT -1,
powerLevel NUMBER NULL DEFAULT 0,
banned NUMBER NOT NULL DEFAULT 0);'''
conn.execute(initialize_users)
conn.commit()
# Initialize the SQL Structures. Groupchats Table
def sql_initialize_groupnames():
initialize_gn = f'''CREATE TABLE IF NOT EXISTS Groupchats
(roomid TEXT,
groupname TEXT
announce BOOL NOT NULL DEFAULT 0,
rssPush BOOL NOT NULL DEFAULT 1);'''
conn.execute(initialize_gn)
conn.commit()
################################# SEND MSG #################################
def destroy_all():
qs={
'id':getid(),
'type':DESTROY_ALL,
'content':'none',
'wxid':'node',
}
return json.dumps(qs)
# Tell websocket wxapi to send a text message
def send_txt_msg(msg,wxid='null'):
if msg.endswith('.png'):
msg_type=PIC_MSG
else:
msg_type=TXT_MSG
qs={
'id':getid(),
'type':msg_type,
'wxid':wxid,
'roomid':'null',
'content':msg,
'nickname':'null',
'ext':'null'
}
output(f'{msg} -> {wxid}','SEND')
return json.dumps(qs)
# Tell websocket wxapi to send an attachment
def send_attatch(filepath,wxid = 'null'):
qs={
'id':getid(),
'type':ATTATCH_FILE,
'wxid':wxid,
'roomid':'null',
'content':filepath,
'nickname':'null',
'ext':'null'
}
output(f'File @ {filepath} -> {wxid}','SEND')
return json.dumps(qs)
# Tell websocket wxapi to send an attachment.
def send_pic(filepath,wxid = 'null'):
qs={
'id':getid(),
'type':PIC_MSG,
'wxid':wxid,
'roomid':'null',
'content':filepath,
'nickname':'null',
'ext':'null'
}
output(f"Media @ {filepath} -> {wxid}",'SEND')
return json.dumps(qs)
############################## HANDLES #####################################
# wxapi: handle status message
def handle_status_msg(msgJson):
vis_content = msgJson['content']['content']
if '拍了拍我' in vis_content:
output(vis_content,'PAT',background = 'MINT')
pat_wb(msgJson)
elif '邀请' in vis_content and '加入群聊' in vis_content:
ws.send(send_wxuser_list())
roomid=msgJson['content']['id1']
ws.send(send_txt_msg(f'欢迎进群',wxid=roomid))
# wxapi: handle sent message
def handle_sent_msg(msgJson):
output(msgJson['content'],mode = 'HIGHLIGHT')
# wxapi: handle xml message *Very Broken :(
def handle_xml_msg(msgJson):
# 处理带引用的文字消息和转发链接
msgXml=msgJson['content']['content'].replace('&','&').replace('<','<').replace('>','>')
soup=BeautifulSoup(msgXml,features="xml")
if soup.appname.string == '哔哩哔哩':
output(f'Video from BiliBili: {soup.title.string} URL: {soup.url.string}',logtype = 'GROUPCHAT')
return
refmsg = soup.refermsg
msgJson={
'content':soup.select_one('title').text,
'refcontent': refmsg.select_one('content').text,
'refnick': refmsg.select_one('displayname').text,
'id':msgJson['id'],
'id1':msgJson['content']['id2'],
'id2': refmsg.select_one('chatusr').text,
'id3':'',
'srvid':msgJson['srvid'],
'time':msgJson['time'],
'type':msgJson['type'],
'wxid':msgJson['content']['id1']
}
handle_recv_msg(msgJson)
# wxapi: handle at message * Doesn't Work
def handle_at_msg(msgJson):
output(msgJson)
output('AT_msg')
# wxapi: handle picture message
def handle_recv_pic(msgJson):
msgJson = msgJson['content']
if msgJson['id2']:
roomid=msgJson['id1'] #群id
senderid=msgJson['id2'] #个人id
nickname = sql_fetch(cur,f'r{roomid[:-9]}',['groupUsrName'],f"wxid = '{senderid}'")[0][0]
roomname = sql_fetch(cur,'Groupchats',['groupname'],f'roomid = {roomid[:-9]}')[0][0]
'''
Terminal Log
'''
output(f'{roomname}-{nickname}: [IMAGE]','GROUPCHAT')
else:
senderid=msgJson['id1'] #个人id
nickname = sql_fetch(cur,'Users',['realUsrName'],\
f"wxid = '{senderid}'")[0][0]
'''
Terminal Log
'''
output(f'{nickname}: [IMAGE]','DM')
# Call detected in received text message
def handle_recv_call(keyword, callerid, destination):
caller_isbanned = sql_fetch(cur,'Users',['banned'],\
f"wxid = '{callerid}'")
if caller_isbanned[0][0] == 1:
return
call_data = stringQ2B(keyword.strip()).split(' ')
if len(call_data) == 0:
ws.send('请指明需要调用的功能。')
return
# Handle Mobile @
if len(call_data) > 1 and call_data[0] == '':
call_data = call_data[1:]
### HBD EASTER EGG ###
if call_data == ['minfo', '11391', 'mas', 'cb', '555']:
ws.send(send_txt_msg("HAPPY BIRTHDAY!!!",destination))
return
### HBD EASTER EGG ###
'''
Call individual function
'''
func_name = call_data[0].lower()
real_data = call_data[1:]
# MAIMAI Best 50 runs on a seperate thread
if func_name == 'mb50':
ws.send(send_txt_msg('正在获取',destination))
elif func_name == 'help':
help_path = os.path.join(resource_path,"Help")
ws.send(send_attatch(os.path.join(help_path,"WindbotHelpGC.jpeg"),\
destination))
return
execute_call(func_name,real_data,callerid,destination)
# Helper of handle_recv_call
def execute_call(func_name, real_data, callerid, destination):
# Depreciated Functions
if func_name in DEPRECIATED_FUNC_DICT:
ws.send(send_txt_msg(DEPRECIATED_FUNC_DICT[func_name],destination))
return
# Functions that runs on a independent thread
elif func_name in THREADED_FUNC_DICT:
tFunc = Thread(target = THREADED_FUNC_DICT[func_name],\
args = (real_data,callerid,destination))
tFunc.start()
return
# Normal Functions
elif func_name in WB_FUNC_DICT:
try:
ansList = WB_FUNC_DICT.get(func_name)\
(real_data,callerid,destination)
# Error Happened. Push Error Msg to destination
except Exception as e:
output(f'ERROR ON CALL: {e}','ERROR','HIGHLIGHT','RED')
output(traceback.format_exc(),'ERROR','HIGHLIGHT','RED')
ws.send(send_txt_msg(f"出错了_| ̄|○\n指令: {func_name}\n错误细节: {e}\n请尝试检查指令参数,调用help或把WDS@出来",destination))
return
# No Error Happened
ws.send(send_txt_msg(ansList[0],destination))
return
# Non-Existent Function
else:
output('Called non-existent function','WARNING',background = 'WHITE')
ws.send(send_txt_msg(f"没有该指令: {func_name}",destination))
return
# wxapi: handle text message
def handle_recv_msg(msgJson):
global undisturbed_hb
undisturbed_hb = 0
# output(msgJson)
isCite = False
# If msg is a cite message
if msgJson.get('refnick',-1) != -1 and \
msgJson.get('refcontent',-1) != -1:
isCite = True
if '@chatroom' in msgJson['wxid']:
roomid=msgJson['wxid'] #群id
senderid=msgJson['id1'] #个人id
nickname = sql_fetch(cur,f'r{roomid[:-9]}',['groupUsrName'],\
f"wxid = '{senderid}'")[0][0]
roomname = sql_fetch(cur,'Groupchats',['groupname'],\
f'roomid = {roomid[:-9]}')[0][0]
# Handle User Calls
keyword=msgJson['content'].replace('\u2005','')
if keyword[:8] == BOT_GC_TRIGGER:
output(f'{roomname}-{nickname}: {keyword[8:]}','CALL','HIGHLIGHT')
handle_recv_call(keyword[8:],senderid,roomid)
return
# Terminal Log Normal Messages
if not isCite:
output(f'{roomname}-{nickname}: {keyword}','GROUPCHAT')
else:
# little patch that makes no sense at all
refcontent = msgJson['refcontent'].split("\n")
if len(refcontent) > 1:
refcontent = refcontent[4]
else:
refcontent = refcontent[0]
output(f"{roomname}-{nickname}: {keyword}\n\
「-> {msgJson['refnick']} : {refcontent}",\
'GROUPCHAT')
else:
roomid = None
senderid=msgJson['wxid'] #个人id
destination = senderid
nickname = sql_fetch(cur,'Users',['realUsrName'],\
f"wxid = '{senderid}'")[0][0]
# Handle User Calls
keyword=msgJson['content'].replace('\u2005','')
if keyword[:2] == BOT_DM_TRIGGER:
output(f'{nickname}: {keyword}','CALL','HIGHLIGHT')
handle_recv_call(keyword[2:],senderid,senderid)
return
# Terminal Log Normal Messages
if not isCite:
output(f'{nickname}: {keyword}','DM')
else:
output(f"{nickname}: {keyword}\n\
「-> {msgJson['refnick']} : {msgJson['refcontent']}",'DM')
'''
RESPOND TO KEYWORD
'''
if keyword == 'help':
help_path = os.path.join(resource_path,"Help")
if roomid:
ws.send(send_attatch(os.path.join(help_path,"WindbotHelpGC.jpeg"),\
msgJson['wxid']))
else:
ws.send(send_attatch(os.path.join(help_path,"WindbotHelpDM.jpeg"),\
msgJson['wxid']))
elif keyword == 'ding':
ws.send(send_txt_msg('dong', wxid = msgJson['wxid']))
elif keyword == 'dong':
ws.send(send_txt_msg('ding', wxid = msgJson['wxid']))
elif keyword == 'bing':
ws.send(send_txt_msg('bong', wxid = msgJson['wxid']))
elif keyword == 'bong':
ws.send(send_txt_msg('bing', wxid = msgJson['wxid']))
elif keyword == 'BONG':
ws.send(send_txt_msg('DONG', wxid = msgJson['wxid']))
elif keyword == '6':
if roomid:
ws.send(send_txt_msg('WB很不喜欢单走一个6哦',wxid=msgJson['wxid']))
# ban([msgJson['id1']],SUDO_LIST[0],msgJson['wxid'])
elif keyword == '':
resp_list = ['',\
'全ては一つの幸福に集约された。今日という日は人类が真の幸切った辉かしい历史の転换である']
ws.send(send_txt_msg(random.choice(resp_list),wxid=msgJson['wxid']))
elif keyword == '':
reply_txt = "₂ₓ"
ws.send(send_txt_msg(reply_txt, wxid = msgJson['wxid']))
elif keyword == '∩':
reply_txt = ''
ws.send(send_txt_msg(reply_txt, wxid = msgJson['wxid']))
elif keyword.lower() == 'wb':
resp_list = ["您好!","我可以帮到您些什么?"]
ws.send(send_txt_msg(random.choice(resp_list),wxid = msgJson['wxid']))
# Character Q2B
def Q2B(uchar):
"""单个字符 全角转半角"""
inside_code = ord(uchar)
if inside_code == 0x3000:
inside_code = 0x0020
else:
inside_code -= 0xfee0
if inside_code < 0x0020 or inside_code > 0x7e: #转完之后不是半角字符返回原来的字符
return uchar
return chr(inside_code)
# String Q2B
def stringQ2B(ustring):
"""把字符串全角转半角"""
return "".join([Q2B(uchar) for uchar in ustring])
######################### ON MSG SWITCH #####################################
# Call handlers when received message from the wxapi
def on_localapi_message(ws,message):
j=json.loads(message)
resp_type=j['type']
# output(j)
# output(resp_type)
# switch结构
action={
CHATROOM_MEMBER_NICK:handle_chat_nick,
PERSONAL_DETAIL:handle_personal_detail,
AT_MSG:handle_at_msg,
DEBUG_SWITCH:handle_recv_msg,
PERSONAL_INFO:handle_personal_info,
PERSONAL_DETAIL:handle_personal_detail,
TXT_MSG:handle_sent_msg,
PIC_MSG:handle_sent_msg,
ATTATCH_FILE:handle_sent_msg,
CHATROOM_MEMBER:handle_memberlist,
RECV_PIC_MSG:handle_recv_pic,
RECV_TXT_MSG:handle_recv_msg,
RECV_TXT_CITE_MSG:handle_xml_msg,
HEART_BEAT:heartbeat_trigger,
USER_LIST:handle_wxuser_list,
GET_USER_LIST_SUCCSESS:handle_wxuser_list,
GET_USER_LIST_FAIL:handle_wxuser_list,
STATUS_MSG:handle_status_msg,
}
action.get(resp_type,print)(j)
########################## USER FUNCTIONS ###################################
# Do nothing
def no_op(datalist,callerid,roomid = None):
return ['']
# Randomly select from given data
def rand_item(datalist,callerid,roomid = None):
data_len = len(list(set(datalist)))
if data_len < 1:
reply_txt = "您没有提供随机清单。"
elif data_len == 1:
reply_txt = "您知道吗?他们曾经说WB做决策的时候很困难,但是现在WB不确定了。"
else:
reply_txt = f"WB为您随机(1/{data_len})挑选了:\n"
reply_txt += random.choice(datalist)
return [reply_txt]
# List all Functions from the global function dict
def list_functions(datalist,callerid,roomid = None):
date = time.strftime("%Y-%m-%d")
reply_txt = f"WB的目前可用指令({date}):\n"
for func_name in WB_FUNC_DICT:
reply_txt += f"{func_name}\n"
for func_name in THREADED_FUNC_DICT:
reply_txt += f"{func_name}\n"
return [reply_txt]
# Bind user with provided data in SQL / check binded data
def bind(datalist,callerid,roomid = None):
bind_categories = {
'arc': 'arcID',
# 'qq': 'qqID', # For Now, QQID Serves no purpose.
'pjsk': 'pjskID',
'mai': 'maiID',
'pat': 'patAction'
}
if len(datalist) == 0:
return ["请指明需要绑定的项目类型和内容。"]
reply_txt = ""
keyword = datalist[0]
# bind view
if keyword == "view":
reply_txt = bind_view(callerid)
# Category not found
elif keyword not in bind_categories:
reply_txt = f"没有该项目: {datalist[0]}"
# bind xxx yyyy
else:
app = datalist[0]
content = stringQ2B(" ".join(datalist[1:]).strip())
app_sql_ID = bind_categories.get(app)
# For Game IDs
if app_sql_ID != 'patAction':
reply_txt = f"已绑定至 {app_sql_ID}: {content}"
# For PatAction
else:
if len(content) > 30:
reply_txt = "您的PatAction超过了30个字符。"
return [reply_txt]
elif content.isspace() or content == "":
reply_txt = "请提供PatAction。"
return [reply_txt]
elif "bind" in content:
reply_txt = "https://www.google.com/search?q=recursion"
return [reply_txt]
elif "patstat" in content:
reply_txt = "为了解决WB对群聊具有高度侵入性的情况,您不可以将patstat绑定为PatAction。谢谢您的理解。"
return [reply_txt]
else:
reply_txt = f"已将PatAction设置为: {content}"
# Bind User's content to corresponding app_sql_ID item
sql_update(conn, 'Users', app_sql_ID, content, f"wxid = '{callerid}'")
return [reply_txt]
# Helper for bind Function
def bind_view(callerid:str) -> str:
# Format: [(arcID,maiID,pjskID,funccall)]
usrInfo = sql_fetch(cur,'Users',['arcID','maiID','pjskID','patAction'],\
f"wxid = '{callerid}'")[0]
id_type = ['Arcaea','maimai查分器','pjsk','PatAction指令']
reply_txt = ""
unbound_cnt = 0
# For Game IDs
for i in range(len(usrInfo)-1):
if str(usrInfo[i]) != '-1':
reply_txt += f'已绑定的{id_type[i]}ID: {usrInfo[i]}\n'
else:
unbound_cnt += 1
reply_txt += f'您没有绑定{id_type[i]}ID\n'
# For patAction
if usrInfo[-1] == '-1':