-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1291 lines (1201 loc) · 68.2 KB
/
app.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
#from selectors import EpollSelector
#heroku labs:enable log-runtime-metrics #開啟log
#heroku labs:disable log-runtime-metrics
#heroku restart
#v507 全面改用 chrome_type=ChromeType.BRAVE瀏覽器
from flask import Flask, request, abort, render_template, send_file#基本上web app就是靠flask
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import *
from lxml import etree #find with xpath
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import requests
import time
import os
import datetime #倒數 星期幾
import random
import psycopg2
import discord
import json
import ast #str to mapping
from modules.to_do_list_variable import variable_separator, variable_block, variable_main_construct
from modules.qr_code import qr_code_decode
from modules.translate import AI
mode = "stable"
GOOGLE_CHROME_PATH = '/app/.apt/usr/bin/google_chrome'
CHROMEDRIVER_PATH = '/app/.chromedriver/bin/chromedriver'
DATABASE_URL = os.environ['DATABASE_URL']
if mode == "test":
LINE_CHANNEL_ACCESS_TOKEN = os.environ['TEST_LINE_CHANNEL_ACCESS_TOKEN']
LINE_CHANNEL_SECRET = os.environ['TEST_LINE_CHANNEL_SECRET']
else:
LINE_CHANNEL_ACCESS_TOKEN = os.environ['LINE_CHANNEL_ACCESS_TOKEN']
LINE_CHANNEL_SECRET = os.environ['LINE_CHANNEL_SECRET']
DISCORD_WEBHOOK = os.environ['DISCORD_WEBHOOK']
OPUUID = os.environ['LINE_OP_UUID']
changelog = "mem leak fixed、qrdecoder\n新增指令:\n/點名未到"#還有成績指令沒寫完、簽到未開放的對列quene、未點名的紀錄
client = discord.Client()
app = Flask(__name__)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('user-agent=Mozilla/5.0')
chrome_options.add_argument('ignore-certificate-errors')
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--example-flag")
wd = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.BRAVE).install()),options=chrome_options) #version="104.0.5112.79",
EAT = (["全家","7-11","中原夜市","鍋燒意麵","肉羹","拉麵","炒飯","賣麵庄","雞腿便當","摩斯漢堡","麥當勞","烤肉飯","肯德基","石二鍋",
"五花馬","燒肉","咖哩飯","牛排","肉燥飯","SUKIYA","霸味薑母鴨","高雄黑輪","丼飯","薩利亞","mint","火雞肉飯","品田牧場","滷味","Mr.三明治",
"雞柳飯","肉骨茶麵","泡麵","水餃","煎餃","包子","炒麵","鐵板燒","披薩","悟饕","河粉","肉圓","黑宅拉麵","壽司","牛肉麵","鹹酥雞","橋下無名控肉便當",
"赤麵廠","早到晚到","大時鐘天香麵","豚骨麻辣燙","後站無名麵店","阿倫炒羊肉","炸螃蟹","烤肉","雞蛋糕","阿燁麵線","重慶酸辣粉"])
WHALE =(["\n\n\n\n\n·_______________·","\n\n\n\n\n@_______________@","\n\n\n\n\nX_______________X","\n\n\n\n\nO_______________O","\n\n\n\n\n^_______________^",
"\n\n\n\n\n*_______________*","\n\n\n⠀⠀⠀⠀⠀∞\n\n·_______________·","\n\n\n\n\n·_______________·"])
CHICKEN =(["➖➖➖➖\uD83D\uDFE5\n➖➖➖⬜️⬜️\n➖➖➖⬜️\uD83D\uDD33\uD83D\uDFE7\n⬜️➖➖⬜️⬜️\uD83D\uDFE5\n⬜️⬜️⬜️⬜️⬜️\n⬜️⬛️⬛️⬜️⬜️\n➖⬜️⬜️⬜️\n➖➖\uD83D\uDFE8",
"➖➖➖➖\uD83D\uDFE5\n➖➖➖\uD83D\uDFE7\uD83D\uDFE7\n➖➖➖\uD83D\uDFE7\uD83D\uDD33\uD83D\uDFE8\n\uD83D\uDFE6➖➖\uD83D\uDFE7\uD83D\uDFE7\uD83D\uDFE5\n\uD83D\uDFEB⬜️\uD83D\uDFEB\uD83D\uDFEB\uD83D\uDFEB\n\uD83D\uDFEB\uD83D\uDFE5\uD83D\uDFE5\uD83D\uDFEB\uD83D\uDFEB\n➖\uD83D\uDFEB\uD83D\uDFEB\uD83D\uDFEB\n➖➖\uD83D\uDFE8"])
STICKER_LIST = {'465400171':'ㄌㄩㄝ','465400158':'才不美','465400159':'Woooooooow','465400160':'不可以','465400161':'怎樣啦 輸贏啦','465400163':'假K孝濂給',
'465400165':'累屁','465400166':'聽話 讓我看看','465400169':'到底??????','465400172':'他在已讀你','465400173':'大概24小時後才會回你','13744852':'哼',
'349572675':'可憐哪','352138078':'吃屎阿','464946842':'對咩對咩','464946834':'ㄏㄏ','464946841':'亂講','435674449':'嘿嘿','435674452':'兇屁'}
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)# Channel Access Token
handler = WebhookHandler(LINE_CHANNEL_SECRET)# Channel Secret
discord_webhook = DISCORD_WEBHOOK
grouptoken = ["4C0ZkJflAfexSpelBcoEYVobqbbSD0aGFNvpGAVcdUX","vUQ1xrf4cIp7kFlWifowMJf4XHdtUSHeXi1QeUKARa9","WCIuPhhETZysoA6qjdx59kblgzbc6gQuVscBKS91Fi5"]#公開的
groupId = ['Cc97a91380e09611261010e4c5c682711','C0041b628a8712ace35095f505520c0bd','Cdebd7e16f5b52db01c3efd20b12ddd35']#公開的
#recived = "已收到網址,正在點名中,請靜待約20~30秒,若看見此訊息後請盡量不要重複傳送相同的訊息,以免造成系統塞車"
recived = "警告,機器人已停止更新,將不會進行點名動作"
done = '點名結束\n每次過程將會持續20~30秒\n(視點名人數及當前礙觸摸網路狀況而定)\n仍在測試中,不建議將此系統作為正式使用,在系統回覆點名狀態前建議不要離開本對話框,以免失效時來不及通知其他人手動點名\n▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n'
announce = '▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n由於line bot官方限制緣故,每個月對於機器人傳送訊息有一定的限額,如超過系統配額,此機器人將會失效\n▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n'
msgbuffer = ""
public_msgbuffer = ""
success_login_status = 0
fail_login_status = 0
global not_send_msg
not_send_msg = False
def get_all_user():#turn raw data into 4 argument lists
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
cursor.execute("SELECT * FROM all_info")#choose all the data of target
global all_user_buffer_list
global userlist
global pwlist
global namelist
global useridlist
all_user_buffer_list = cursor.fetchall()#start fetch and become a list
userlist = []
pwlist = []
namelist = []
useridlist = []
for i in range(len(all_user_buffer_list)):
userlist.append(all_user_buffer_list[i][3])
print(userlist)
for i in range(len(all_user_buffer_list)):
pwlist.append(all_user_buffer_list[i][4])
print(pwlist)
for i in range(len(all_user_buffer_list)):
namelist.append(all_user_buffer_list[i][1])
print(namelist)
for i in range(len(all_user_buffer_list)):
useridlist.append(all_user_buffer_list[i][2])
print(useridlist)
count = cursor.rowcount
print(count, "筆資料已進入伺服器")
cursor.close()
conn.close()
def get_now_all_user_status():#turn raw data into 4 argument lists
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
cursor.execute("SELECT * FROM all_info")#choose all the data of target
all_list = cursor.fetchall()#fetch
cursor.close()
conn.close()
return str(all_list)
@app.route("/time_quene")#post#未完成
def time_quene():
print("加入對列")
return
@app.route("/msg.html")#快速回復
def quick_msg():
arg_msg = request.args.get('訊息傳出')
if(str(arg_msg)!="None"):
line_bot_api.push_message("U008144522397487153eba2310067b66f", TextSendMessage("【此為機器人節省流量傳送】" + str(arg_msg)))#離九lineuuid
print("已傳出" + str(arg_msg))
return render_template('msg.html')
@app.route("/chinese_ans")#國文的主網頁
def chinese_ans():
ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr)
if "147.92.179" not in ip: #忽略Line的固定式ip
my_msg("【進入chinese_ans的ip】" + ip)#傳給我手機點進來的Ip,HTTP_X_REAL_IP不起作用,會變成heroku內部ip
return render_template('chinese_ans.html')
def quene(url,time):#將未開始的點名加入對列#未完成
print("已成功加入")
def url_login(msg,event,force):
try:
global not_send_msg
not_send_msg = False
now_unix_time = int(event.timestamp/1000)#強制將unix時間取整
wd = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.BRAVE).install()), options=chrome_options)
start_time = time.time()
url = str(msg).replace("&afterLogin=true","")
messageout = ""
success_login_status = 0
global fail_login_status
fail_login_status = 0
wd.get(url)
#time.sleep(1)
not_open = "未開放 QRCODE簽到功能" in wd.page_source
xpath = '/html/body/div/div[2]/p'
time_and_classname = str(wd.find_element(by=By.XPATH, value=xpath).text).replace("課程點名", "").replace(" ", " ")
#xpath = '/html/body/div/div[2]/p/text()[4]'
#curriculum_name = str(wd.find_element(by=By.XPATH, value=xpath).text)
if not_open:
fail_login_status = len(userlist)
messageout = "🟥警告❌,點名並沒有開放,請稍後再試或自行手點,全數點名失敗\n"
not_send_msg = True
with open("json/limited_class.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"msg_1" : "偵測到課程點名失敗,是否需要重新點名?" , "unix_time" : now_unix_time , "force_url_login" : url })
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
not_send_msg = False
#break
else:
if (("英文" in time_and_classname or "化學實驗" in time_and_classname) and force != True):
with open("json/limited_class.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"msg_1" : "此課程不建議全體點名,確定要點名?" , "unix_time" : now_unix_time , "force_url_login" : url })
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg不建議全體點名")
line_bot_api.reply_message(event.reply_token, flex_message)
not_send_msg = True
else:#確認所有條件都適合點名
#my_msg(url)
for i in range(0,len(userlist),1):
wd.execute_script("window.open('');")#取一 我也不知道差在哪
#wd.switch_to.new_window('tab')#但是這個就是會當掉,run到登入完頁面就會停止
wd.switch_to.window(wd.window_handles[i+1])
wd.get(url)#打開所有對應數量的分頁並到網址
print("已打開第"+ str(i) + "個分頁")
for i in range(0,len(userlist),1):#輸入帳號密碼 並登入
wd.switch_to.window(wd.window_handles[i+1])#先跑到對應的視窗
usr = userlist[i]
pwd = pwlist[i]
name = namelist[i]
wd.execute_script('document.getElementById("UserNm").value ="' + usr + '"')
wd.execute_script('document.getElementById("UserPasswd").value ="' + pwd + '"')
wd.execute_script('document.getElementsByClassName("w3-button w3-block w3-green w3-section w3-padding")[0].click();')
print("已登入第"+ str(i) + "個分頁")
for i in range(0,len(userlist),1):
usr = userlist[i]#之後的訊息要顯示
pwd = pwlist[i]
name = namelist[i]
wd.switch_to.window(wd.window_handles[i+1])#先跑到對應的視窗
password_wrong = EC.alert_is_present()(wd)#如果有錯誤訊息#不太確定要先切換視窗再按確認還是反過來
if password_wrong:
failmsg = password_wrong.text
password_wrong.accept()
messageout = (messageout + "學號:" + usr + "\n🟥點名失敗❌\n錯誤訊息:密碼錯誤" + failmsg +'\n\n')#error login
print("密碼錯誤\n------------------\n" + messageout)
fail_login_status = fail_login_status +1
else:
try:#嘗試找尋失敗#D06079
wd.find_element(By.CSS_SELECTOR, "[stroke='#D06079']")#第一次用cssselector 如果沒有紅色就會是成功訊息
fail_msg = str(wd.find_element(By.XPATH,"/html/body/div[1]/div[3]/div").text)
messageout = (messageout + "\n🟥點名失敗❌,"+ name +"好可憐喔😱\n失敗訊息:" + fail_msg +'\n\n')
print("點名失敗\n------------------\n" + messageout)
fail_login_status = fail_login_status +1
if "簽到未開放" in fail_msg:
messageout = "🟥警告❌,點名尚未開始,請稍後再試,全數點名失敗\n"
fail_login_status = len(userlist)
print("🟥警告❌,點名尚未開始")
break
except NoSuchElementException:#找不到#D06079就會是成功#73AF55
detailmsg = wd.find_element(By.XPATH,"/html/body/div[1]/div[3]/div").text
messageout = (messageout + "\n🟩點名成功✅,"+ name +"會非常感謝你\n成功訊息:" + detailmsg.replace('月','月').replace('日','日').replace(':',':').replace('<br>','\n')+'\n\n')
print("點名成功\n------------------\n" + messageout)
success_login_status = success_login_status +1
messageout = (messageout + '▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n' + "本次點名人數:" + str(len(userlist)) + "人\n" + "成功點名人數:" + str(success_login_status) + "人\n"+ "失敗點名人數:" + str(fail_login_status)+ "人\n" + str(time_and_classname))
messageout = (messageout + '\n▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n' + "最近一次更新:" + os.environ['HEROKU_RELEASE_CREATED_AT'].replace("Z","").replace("T"," ") + "GMT+0\n" + "版本:" + os.environ['HEROKU_RELEASE_VERSION']+ "\n此次點名耗費時間:" + str(round(time.time() - start_time)+2) +"秒" +"\n更新日誌:" + changelog)
wd.close()
except IndexError:
messageout = "🟥🟥FATAL ERROR🟥🟥\n可能是由ilearning網頁故障或是輸入錯誤的網址所引起\n請盡快手點和連繫我"
#except Exception:#記得有Bug的時候一定要把它撤下來 不然會吐不出錯誤訊息
#messageout = "🟥🟥UNKNOWN ERROR🟥🟥\n可能是由輸入錯誤的網址所引起、整體系統出錯,或是傳送的網址為限制的課程,如有問題請聯絡我"
#print('不知道怎麼了,反正發生錯誤')
return messageout
@handler.add(PostbackEvent)
def handle_postback(event):
global public_msgbuffer
postback_msg = event.postback.data
get_now_user_id = event.source.user_id
now_unix_time = int(event.timestamp/1000)#強制將unix時間取整
time_end = now_unix_time
print("現在時間:" + str(now_unix_time))
if '/changepassword' in postback_msg :
if get_now_user_id in useridlist:#帳號存在
change_password = postback_msg.replace("/changepassword","").replace(" ","")
change_password_via_uuid(change_password , get_now_user_id)
with open("json/changed_password.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
elif("/deleteall" in postback_msg):
get_now_name = namelist[useridlist.index(get_now_user_id)]
get_now_user = userlist[useridlist.index(get_now_user_id)]
get_now_user_id = postback_msg.replace("/deleteall","").replace(" ","")
delete_on_database_via_uuid(get_now_user_id)
respond = "已成功清除" + get_now_user + get_now_name + "的資料" + ",如需重新綁定,請輸入「/開始綁定」"
print(respond)
my_msg(respond)
line_bot_api.push_message(event.source.user_id, TextSendMessage(respond))
elif("/force_url_login " in postback_msg):
get_now_name = namelist[useridlist.index(get_now_user_id)]
get_now_user = userlist[useridlist.index(get_now_user_id)]
time_start = int((postback_msg.replace("/force_url_login ","").replace(" ",""))[0:10])
url = postback_msg.replace("/force_url_login ","").replace(" ","").replace(str(time_start),"")
print("標記時間:" + str(time_start))
print("相扣時間:" + str(time_end-time_start))
print("Raw data:" + postback_msg)
print(url)
if (event.source.type == "group") :
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
if(time_end-time_start<=1800):
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n觸發者:" + get_now_name + "\n" +recived })#翹課大魔王
msgbuffer = url_login(url,event,force = True)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
else:
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n觸發者:" + get_now_name + "\n" + "按鈕時效已過期" })#翹課大魔王
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
if(time_end-time_start<=1800):
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n" + recived })#秘密基地
msgbuffer = url_login(url,event,force = True)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
else:
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n觸發者:" + get_now_name + "\n" + "按鈕時效已過期" })#秘密基地
else:
print("有不知名的群組")
elif(event.source.type == "user") :
if(time_end-time_start<=1800):
line_bot_api.reply_message(event.reply_token, TextSendMessage(recived))
#person_not_send_msg_func(not_send_msg,event.source.user_id,TextSendMessage(recived))
msgbuffer = url_login(url,event,force=True)
public_msgbuffer = (done + msgbuffer)
line_bot_api.push_message(event.source.user_id, TextSendMessage(distinguish(public_msgbuffer)))
else:
line_bot_api.push_message(event.source.user_id, TextSendMessage("按鈕時效已過期"))
else:
print("ERROR:invalid source type during force login")
elif("/delete_to_do_list " in postback_msg):
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
name = "'" + postback_msg.replace("/delete_to_do_list ","") + "'"
postgres_delete_query = "DELETE FROM shoplist WHERE name = " + name
cursor.execute(postgres_delete_query)
conn.commit()
cursor.close()
conn.close()
to_do_list_show(event)
else:
print("ERROR:invalid postback event")
def push_msg(event,msg):
not_send_msg = False
if(event.source.type == "group"):
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
payload = {'message': msg }
group_not_send_msg_func(not_send_msg,headers,payload)
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
payload = {'message': msg }
group_not_send_msg_func(not_send_msg,headers,payload)
elif(event.source.group_id == groupId[2]):
headers= {
"Authorization": "Bearer " + grouptoken[2],
}
payload = {'message': msg }
group_not_send_msg_func(not_send_msg,headers,payload)
else:
print("有不知名的群組")
elif(event.source.type == "user"):
line_bot_api.push_message(event.source.user_id, TextSendMessage(msg))
else:
print("ERROR:invalid source type")
# 監聽所有來自 /callback 的 Post Request
@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
print("訊息從line進入:\n" + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
print("嚴重失敗!")
abort(400)
return 'OK'
@app.route("/")
def activate():
print("強迫喚醒成功")
return '強迫喚醒成功'
def deliver_data(public_msgbuffer, event, text=None) -> dict:
if (event.source.type == "user"):
profile = line_bot_api.get_profile(event.source.user_id)
request_data = {
"content":"------------------------------------------\n\n" + "傳入機器人的訊息:\n" + text + "\n" + "傳出的訊息:\n" + public_msgbuffer + "\n\n------------------------------------------" ,
"username":"<line 同步訊息><個人使用> " + profile.display_name,
"avatar_url":profile.picture_url
}
elif (event.source.type == "group"):
profile = line_bot_api.get_group_member_profile(event.source.group_id,event.source.user_id)
request_data = {
"content":"------------------------------------------\n\n" + "傳入機器人的訊息:\n" + text + "\n" + "傳出的訊息:\n" + public_msgbuffer + "\n\n------------------------------------------" ,
"username":"<line 同步訊息><群組訊息> " + profile.display_name,
"avatar_url":profile.picture_url
}
return request_data
def distinguish(msgbuffer):
if "ERROR" in msgbuffer:
msgbuffer = msgbuffer.replace(done,"")#將多產生的點名訊息再刪掉
else:
if (fail_login_status > 0):
msgbuffer = "🟥\n" + msgbuffer
else:
msgbuffer = "🟩\n" + msgbuffer
return msgbuffer
def get_curriculum_pros(get_now_user,get_now_pwd):
curriculum_list = []
classroom_list = []
url="https://itouch.cycu.edu.tw/active_system/login/loginfailt.jsp?User_url=/active_system/quary/s_query_course_list.jsp"
wd = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.BRAVE).install()),options=chrome_options)
wd.get(url)
wd.execute_script('document.getElementById("UserNm").value ="' + get_now_user + '"')
wd.execute_script('document.getElementById("UserPasswd").value ="' + get_now_pwd + '"')
xpath = "/html/body/div[3]/form/table/tbody/tr[1]/td/table/tbody/tr[4]/td/div[1]/input"
wd.find_element(by=By.XPATH, value=xpath).click()
wd.get("https://itouch.cycu.edu.tw/active_system/quary/s_query_course_list.jsp");
soup = BeautifulSoup(wd.page_source, 'html.parser')
dom = etree.HTML(str(soup))
for j in range(3,10,1):#星期
for i in range(3,32,2):#一天14節課
a = dom.xpath('/html/body/table[1]/tbody/tr['+ str(i) + ']/td[' + str(j) + ']')[0].text#課程名
if a != None:#有課
try:
b = dom.xpath('/html/body/table[1]/tbody/tr['+ str(i) +']/td[' + str(j) +']/font')[0].text#如果有課程,課程的教室
except IndexError: #有課程但是沒教室
print("")
b = ""
else:#沒課
b = ""
a = ""
classroom_list.append(str(b))
curriculum_list.append(str(a))
for item in soup:
item.decompose()
wd.quit
return curriculum_list,classroom_list
def curriculum(event):
get_now_user_id = event.source.user_id
if get_now_user_id in useridlist:#帳號存在
get_now_user = userlist[useridlist.index(get_now_user_id)]
get_now_pwd = pwlist[useridlist.index(get_now_user_id)]
curriculum_list,classroom_list = get_curriculum_pros(get_now_user,get_now_pwd)
with open("json/curriculum.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage("你尚未綁定帳號"))
return
def today_curriculum(event):
get_now_user_id = event.source.user_id
day_list_num = (datetime.datetime.today().isoweekday()*14)-14
if get_now_user_id in useridlist:#帳號存在
get_now_user = userlist[useridlist.index(get_now_user_id)]
get_now_pwd = pwlist[useridlist.index(get_now_user_id)]
curriculum_list,classroom_list = get_curriculum_pros(get_now_user,get_now_pwd)
print(classroom_list)
print(curriculum_list)
switcher = { "1": '"星期一"', "2": '"星期二"', "3": '"星期三"', "4": '"星期四"', "5": '"星期五"', "6": '"星期六"', "7": '"星期日"'}
substitute = '"day" : ' + switcher.get(str(datetime.datetime.today().isoweekday()))
for k in range(day_list_num , day_list_num+15 , 1):
substitute = (substitute + ',' + '"curriculum_' + str(k - day_list_num + 1) + '" : "' + curriculum_list[k] + ' ",' + '"place_' + str(k - day_list_num + 1) + '" : "' +classroom_list[k] + ' "')
substitute = "{" + substitute + "}"
#print(substitute)
#print(type(substitute))
substitute = ast.literal_eval(substitute)
#print(substitute)
#print(type(substitute))
with open("json/today_curriculum.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % substitute)
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage("你尚未綁定帳號"))
return
def group_not_send_msg_func(not_send_msg,headers,payload):
if not_send_msg == True:
print()
else:
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)
return
def person_not_send_msg_func(not_send_msg,user_id,payload):
if not_send_msg == True:
print()
else:
line_bot_api.push_message(user_id, payload)
return
def roll_call_fail(username,password):#全學年點名未到
wd = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.BRAVE).install()),options=chrome_options)
url = "https://itouch.cycu.edu.tw/active_system/login/loginfailt.jsp?User_url=/active_system/query_data/board/s_history_course_board.jsp"
wd.get(url)
wd.execute_script("document.getElementById('UserNm').value =" + "'" + username + "'")
wd.execute_script("document.getElementById('UserPasswd').value =" + "'" + password + "'")
wd.execute_script("document.getElementsByClassName('button12')[0].click();")
url = "https://itouch.cycu.edu.tw/active_system/query_data/board/s_history_course_board.jsp"
wd.get(url)
msg = "的未到清單\n"
order = 2
while(True):
try:
i=2#從表格的第二個開始偵測
xpath = "/html/body/table/tbody/tr[" + str(order) + "]/td[7]/div/a"#點名按鍵 #如果是索引呢
a = wd.find_element(by=By.XPATH, value=xpath).text
wd.find_element(by=By.XPATH, value=xpath).click()#點進去頁面了
#print(wd.current_url)
while(True):
try:
xpath = "/html/body/table/tbody/tr[" + str(i) + "]/td[3]"
a = str(wd.find_element(by=By.XPATH, value=xpath).text)
xpath = "/html/body/table/tbody/tr[" + str(i) + "]/td[5]"
b = str(wd.find_element(by=By.XPATH, value=xpath).text)
if "未到" == a:#如果未到
print("抓到未到的")
xpath = "/html/body/h3[1]"#去抓未到的課程
a = str((wd.find_element(by=By.XPATH, value=xpath).text).replace("課程名稱:","").replace("學年期",""))
if len(a)>4:
a = a[0:9] + "..."
print(a)
msg = msg + a
xpath = "/html/body/table/tbody/tr[" + str(i) + "]/td[1]"#去抓未到的日期
a = wd.find_element(by=By.XPATH, value=xpath).text
print(a)
msg = msg + a
xpath = "/html/body/table/tbody/tr[" + str(i) + "]/td[2]"#去抓未到的節數
a = wd.find_element(by=By.XPATH, value=xpath).text
print(a)
msg = msg + " " + a + "節"
if b != "":#如果已准假就在後面標記
msg = msg + "(已准假)\n"
else:
msg = msg + "\n"
i += 1
#沒有else
except NoSuchElementException:
#url = "https://itouch.cycu.edu.tw/active_system/query_data/board/s_history_course_board.jsp"
#wd.get(url)
wd.back()#變快46%
break
order += 1
except NoSuchElementException:
#print("碰到沒有按鍵的")
try:
if "學年課程清單" in wd.find_element(by=By.XPATH, value="/html/body/table/tbody/tr[" + str(order) + "]/td").text:
a = str(wd.find_element(by=By.XPATH, value="/html/body/table/tbody/tr[" + str(order) + "]/td").text).replace("清單","點名未到")
msg = msg + "----------\n" + a + ":\n"
order += 1
print("學年課程清單")
elif "課程" in wd.find_element(by=By.XPATH, value="/html/body/table/tbody/tr[" + str(order) + "]/td[7]/div").text:#如果div有東西,div/a沒有 那就是忽略 繼續
order += 1
print("碰到索引 繼續")
except NoSuchElementException:
print("結束")
break#真的已經到表格最底部了 #跳脫while
#print(msg)
wd.quit()
return msg
def roll_call_activity(msg,event):
if 'learning_activity' in msg :
if (event.source.type == "group") :
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n" + recived })#翹課大魔王
msgbuffer = url_login(msg,event,force=False)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n" + recived })#秘密基地
msgbuffer = url_login(msg,event,force=False)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(recived))
msgbuffer = url_login(msg,event,force=False)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
print("有不知名的群組")
line_bot_api.push_message(event.source.group_id, TextSendMessage(distinguish(public_msgbuffer)))#除了以上兩個群組
elif(event.source.type == "user") :
line_bot_api.push_message(event.source.user_id, TextSendMessage(recived))
msgbuffer = url_login(msg,event,force=False)
public_msgbuffer = (done + msgbuffer)
person_not_send_msg_func(not_send_msg,event.source.user_id,TextSendMessage(distinguish(public_msgbuffer)))
else:
print("錯誤:偵測不到itouch網址訊息類型")
line_bot_api.reply_message(event.reply_token, TextSendMessage("偵測不到itouch網址類型,請再試一次"))
else:
public_msgbuffer = ('請輸入正確的點名網址')
line_bot_api.reply_message(event.reply_token, TextSendMessage(public_msgbuffer))
return
#warning! reply token would expired after send msg about 30seconds. use push msg!
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event) :
public_msgbuffer = ""
msg = event.message.text
msg_type = event.message.type
#now_unix_time = int(event.timestamp/1000)#強制將unix時間取整
print(msg_type)
if 'itouch.cycu.edu.tw' in msg and '/force_url_login' not in msg:
roll_call_activity(msg,event)#整串轉移到513行roll_call_activity
elif '/' in msg and msg[0] == "/":#all command
command(msg,event)
elif 'https://' in msg or '.com' in msg :
public_msgbuffer = (announce + '此非itouch網域')
if (event.source.type == "group") :
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
#requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': public_msgbuffer })#翹課大魔王
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n好像有人傳了網址還是怎麼樣的" })#秘密基地
elif(event.source.group_id == groupId[2]):
headers= {
"Authorization": "Bearer " + grouptoken[2],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n好像有人傳了網址還是怎麼樣的" })#小歐陽機器人
else:
public_msgbuffer = (announce + '此非itouch網域')
line_bot_api.reply_message(event.reply_token, TextSendMessage(public_msgbuffer))
elif '要吃什麼' in msg or msg == '吃什麼' or msg == 't gk6ak7' or msg == 't g86' or msg == 'ul4t g86':
line_bot_api.reply_message(event.reply_token, TextSendMessage(EAT[random.randint(0,len(EAT)-1)]))
elif '要吃啥' in msg or msg == '吃啥':
line_bot_api.reply_message(event.reply_token, TextSendMessage(EAT[random.randint(0,len(EAT)-1)]))
elif '陪我' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("我不想跟你欸"))
elif '在一次' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("再啦幹"))
elif '我失戀了' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("反正你小王那麼多"))
elif '暈了' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("寶"))
elif 'ok' in msg and 'book' not in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("ok"))
elif '有沒有人' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("沒有"))
elif '大鯨魚' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage(WHALE[random.randint(0,len(WHALE)-1)]))
elif '雞' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage(CHICKEN[random.randint(0,len(CHICKEN)-1)]))
elif '怪咖' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("對阿你很怪"))#'笑死' in msg or
elif '習近平' in msg or '習大大' in msg or '習維尼' in msg or '維尼' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("哈哈很好笑\n⣿⣿⣿⠟⠋⠄⠄⠄⠄⠄⠄⠄⢁⠈⢻⢿⣿⣿⣿⣿⣿\n⣿⣿⣿⠃⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⡀⠭⢿⣿⣿\n⣿⣿⡟⠄⢀⣾⣿⣿⣿⣷⣶⣿⣷⣶⣶⡆⠄⠄⠄⣿⣿\n⣿⣿⡇⢀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠄⠄⢸⣿⣿\n⣿⣿⣇⣼⣿⣿⠿⠶⠙⣿⡟⠡⣴⣿⣽⣿⣧⠄⢸⣿⣿\n⣿⣿⣿⣾⣿⣿⣟⣭⣾⣿⣷⣶⣶⣴⣶⣿⣿⢄⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⡟⣩⣿⣿⣿⡏⢻⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣹⡋⠘⠷⣦⣀⣠⡶⠁⠈⠁⠄⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣍⠃⣴⣶⡔⠒⠄⣠⢀⠄⠄⠄⡨⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣦⡘⠿⣷⣿⠿⠟⠃⠄⠄⣠⡇⠈⠻⣿⣿\n⣿⣿⡿⠟⠋⢁⣷⣠⠄⠄⠄⠄⣀⣠⣾⡟⠄⠄⠄⠄⠉\n⠋⠁⠄⠄⠄⢸⣿⣿⡯⢓⣴⣾⣿⣿⡟⠄⠄⠄⠄⠄⠄\n⠄⠄⠄⠄⠄⣿⡟⣷⠄⠹⣿⣿⣿⡿⠁⠄⠄⠄⠄⠄⠄\n⠄⠄⠄⠄⣿⣿⠃⣦⣄⣿⣿⣿⠇⠄⠄⠄⠄⠄⠄⠄⠄\n⠄⠄⠄⢸⣿⠗⢈⡶⣷⣿⣿⡏⠄⠄⠄⠄⠄⠄⠄⠄⠄\n去新疆"))
elif '烏克蘭' in msg or '普丁' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("⣿⣿⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣵⣿⣿⣿⠿⡟⣛⣧⣿⣯⣿⣝⡻⢿⣿⣿⣿⣿⣿\n⣿⣿⣿⠋⠁⣴⣶⣿⣿⣿⣿⣿⣿⣿⣦⣍⢿⣿⣿⣿\n⣿⣿⢷⠄⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣏⢼⣿⣿\n⣿⢻⠎⠔⣛⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⣿⣿\n⣿⠇⡶⠄⣿⣿⠿⠟⡛⠛⠻⣿⡿⠿⠿⣿⣗⢣⣿⣿\n⣿⡿⣷⣾⣿⣿⣿⣾⣶⣶⣶⣿⣁⣔⣤⣀⣼⢲⣿⣿\n⣿⣿⣿⣾⣟⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⢟⣾⣿⣿\n⣿⣿⣿⡷⣿⣿⣿⣿⣿⣮⣽⠛⢻⣽⣿⡇⣾⣿⣿⣿\n⣿⣿⣿⡷⠻⢻⡻⣯⣝⢿⣟⣛⣛⣛⠝⢻⣿⣿⣿⣿\n⣿⣿⡟⣹⣦⠄⠋⠻⢿⣶⣶⣶⡾⠃⡂⢾⣿⣿⣿⣿\n⠟⠋⠄⢻⣿⣧⣲⡀⡀⠄⠉⠱⣠⣾⡇⠄⠉⠛⢿⣿\n⠄⠄⠄⠈⣿⣿⣿⣷⣿⣿⢾⣾⣿⣿⣇⠄⠄⠄⠄⠄\n⠄⠄⠄⠄⠸⣿⣿⠟⠃⠄⠄⢈⣻⣿⣿⠄⠄⠄⠄⠄\n⠄⠄⠄⠄⠄⢿⣿⣾⣷⡄⠄⢾⣿⣿⣿⡄⠄⠄⠄⠄\n⠄⠄⠄⠄⠄⠸⣿⣿⣿⠃⠄⠈⢿⣿⣿⠄⠄⠄⠄⠄\nСука блядь"))
elif '都已讀' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("沒有 是你太邊緣"))
elif 'peko' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("好油喔"))
elif '女朋友' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("你沒有女朋友啦幹"))
elif '瑟瑟' in msg or '色色' in msg or '要色色' in msg or '澀澀' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("不可以澀澀"))
elif '閉嘴' in msg or 'b嘴' in msg or 'B嘴' in msg or 'b最' in msg or 'B最' in msg or '惦惦' in msg or '安靜啦' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("你好兇喔"))
elif '歐陽' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("嗨"))
elif '約' in msg :
line_bot_api.reply_message(event.reply_token, TextSendMessage("又要約又要約"))
elif 'waku waku' in msg or 'Waku waku' in msg or 'Wakuwaku' in msg or 'wakuwaku' in msg or 'Waku Waku' in msg:
img_url = "https://raw.githubusercontent.com/brianoy/auto_roll_call/main/S__16023675.jpg"
lowqlty_img_url = "https://raw.githubusercontent.com/brianoy/auto_roll_call/main/lowqlty_S__16023675.jpg"
line_bot_api.reply_message(event.reply_token, ImageSendMessage(original_content_url=img_url, preview_image_url=lowqlty_img_url))#傳圖片
elif 'spy' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("waku waku"))
elif '可以啦幹' in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("我就覺得不可以咩"))
elif '8+9' == msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("17"))
elif '三小' in msg or "幹你娘"in msg or "幹妳娘"in msg or "幹您娘"in msg or "耖機掰"in msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage("好兇"))
elif '王顥' in msg and '單身' in msg:
days = datetime.datetime.today()-datetime.datetime(2019,4,30,16)
days = str(days)[0:4]
days = days + "天"
with open("json/wong_how.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"single" : days})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
sendbuffer = "小提醒:王顥已單身"+ days +"天"
print(sendbuffer)
elif '/' == msg:#fastreply
if (event.source.type == "group") :
quick_reply(event.source.group_id)
if (event.source.type == "user") :
user_quick_reply(event.source.user_id)
elif '查看清單' in msg or '要買啥' in msg or '買啥' in msg or '要買什麼' in msg or '購物清單' in msg or 'list' in msg:
if(event.source.type == "group" and event.source.group_id == groupId[1]):
to_do_list_show(event)
elif '要買' in msg :
if(event.source.type == "group" and event.source.group_id == groupId[1]):
to_do_list_insert(msg,event)
to_do_list_show(event)
elif '嘿寶貝' in msg :#AI機器人
if len(msg) > 3:
line_bot_api.reply_message(event.reply_token, TextSendMessage(AI(msg.replace("嘿寶貝","").replace("?","").replace("\n","").replace("。",""))))
else:
public_msgbuffer = (announce + '無法對這則訊息做出任何動作\n如要完成點名,請傳送該網址即可\n▀▀▀▀▀▀▀▀▀▀▀▀▀▀')
if (event.source.type == "group") :
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
#requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': public_msgbuffer })#翹課大魔王
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': (public_msgbuffer) })#秘密基地
elif(event.source.group_id == groupId[2]):
headers= {
"Authorization": "Bearer " + grouptoken[2],
}
#requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': (public_msgbuffer) })#煤船組
else:
print("有不知名的群組傳送了非相關訊息")
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(public_msgbuffer))
request_data = deliver_data(public_msgbuffer, event, event.message.text)
requests.post(url=discord_webhook, data=request_data)
if (event.source.type == "group") :
#if (event.source.group_id == groupId[0]) :
#quick_reply(groupId[0])
#elif (event.source.group_id == groupId[1]) :
#quick_reply(groupId[1])
print("限制使用quick reply")
elif (event.source.type == "user") :
user_quick_reply(event.source.user_id)
else:
print("不做quick_reply")
return
def command(msg,event):
if '/重新抓取資料庫' == msg :
get_all_user()
respond = "已重新抓取"
print(respond)
not_send_msg = False
person_not_send_msg_func(not_send_msg,event.source.user_id,TextSendMessage(respond))
elif '/我的uuid' == msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage(event.source.user_id))
elif '/資料庫' == msg and event.source.user_id == OPUUID :
respond = ""
for x in range(0,len(all_user_buffer_list),1):
respond = respond + str("\n")
for y in range(0,len(all_user_buffer_list[x]),1):
respond = respond + str(all_user_buffer_list[x][y])
respond = respond + str("\n")
my_msg(str(respond))
elif '/請假紀錄' == msg or '/請假' == msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage(day_off(event)))
elif '/你今天被實驗助教搞了嗎' == msg or '/實驗課成績' == msg:
line_bot_api.reply_message(event.reply_token, TextSendMessage(experiment_course_score(event)))
elif '/我的帳號' == msg:
get_now_user_id = event.source.user_id
if get_now_user_id in useridlist:#帳號存在
get_now_name = namelist[useridlist.index(get_now_user_id)]
get_now_user = userlist[useridlist.index(get_now_user_id)]
with open("json/my_account.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id,"get_now_name" : get_now_name,"get_now_user" : get_now_user})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
else:#帳號不存在
with open("json/account_not_exist.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
elif '/help' == msg or '/幫助' == msg or '/開始綁定帳號' == msg or '/我要綁定帳號' == msg or '/我想要綁定帳號' == msg or '指令列表' == msg or '/指令' == msg or '/指令列表' == msg:
with open("json/help.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read())
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
elif("/force_url_login" in msg):#以明語訊息強制把訊息force_login
not_send_msg = False #要傳訊息 在flexmsg彈出時才會變為true
get_now_user_id = event.source.user_id
get_now_name = namelist[useridlist.index(get_now_user_id)]
get_now_user = userlist[useridlist.index(get_now_user_id)]
url = msg.replace("/force_url_login ","").replace("/force_url_login","").replace(" ","")
print("明文訊息強制點名:")
print(url)
if (event.source.type == "group") :
if(event.source.group_id == groupId[0]):
headers= {
"Authorization": "Bearer " + grouptoken[0],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n" + recived })#翹課大魔王
msgbuffer = url_login(url,event,force = True)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
elif(event.source.group_id == groupId[1]):
headers= {
"Authorization": "Bearer " + grouptoken[1],
}
requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': "\n" + recived })#秘密基地
msgbuffer = url_login(url,event,force = True)
public_msgbuffer = done + msgbuffer
payload = {'message': distinguish(public_msgbuffer) }
group_not_send_msg_func(not_send_msg,headers,payload)
else:
print("有不知名的群組")
elif(event.source.type == "user") :
person_not_send_msg_func(not_send_msg,event.source.user_id,TextSendMessage(recived))
msgbuffer = url_login(url,event,force=True)
public_msgbuffer = (done + msgbuffer)
line_bot_api.push_message(event.source.user_id, TextSendMessage(distinguish(public_msgbuffer)))
else:
print("ERROR:invalid source type during force login")
elif("/未點到名" in msg):#以明語訊息強制把訊息force_login
get_now_user_id = event.source.user_id
get_now_name = namelist[useridlist.index(get_now_user_id)]
get_now_user = userlist[useridlist.index(get_now_user_id)]
get_now_password = pwlist[useridlist.index(get_now_user_id)]
line_bot_api.reply_message(event.reply_token, TextSendMessage(get_now_name + roll_call_fail(get_now_user,get_now_password)))
else:
if (event.source.type == "user") :
limited_command(msg,event)
else:
line_bot_api.push_message(event.source.group_id, TextSendMessage("無法在群組使用此指令,請以私訊機器人的形式進行,謝謝"))
print("指令不存在此區")
return
def quick_reply(id):
quick_reply = TextSendMessage(
text="⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
quick_reply=QuickReply(
items=[
QuickReplyButton(
action=MessageAction(label="今天要吃什麼",text="今天要吃什麼")
),
QuickReplyButton(
action=MessageAction(label="指令列表",text="/help")
),
QuickReplyButton(
action=MessageAction(label="我的帳號",text="/我的帳號")
),
QuickReplyButton(
action=MessageAction(label="我的uuid",text="/我的uuid")
),
QuickReplyButton(
action=MessageAction(label="今日課表",text="/今日課表")
),
QuickReplyButton(
action=MessageAction(label="請假紀錄",text="/請假紀錄")
),
QuickReplyButton(
action=MessageAction(label="全學年缺課紀錄",text="/未點名到")
),
QuickReplyButton(
action=MessageAction(label="你今天被實驗助教搞了嗎",text="/你今天被實驗助教搞了嗎")
)
]
)
)
line_bot_api.push_message(id, quick_reply)
return
def user_quick_reply(id):
quick_reply = TextSendMessage(
text="⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
quick_reply=QuickReply(
items=[
QuickReplyButton(
action=MessageAction(label="今天要吃什麼",text="今天要吃什麼")
),
QuickReplyButton(
action=MessageAction(label="指令列表",text="/help")
),
QuickReplyButton(
action=MessageAction(label="我的帳號",text="/我的帳號")
),
QuickReplyButton(
action=MessageAction(label="我的uuid",text="/我的uuid")
),
QuickReplyButton(
action=MessageAction(label="重新抓取資料庫",text="/重新抓取資料庫")
),
QuickReplyButton(
action=MessageAction(label="清除綁定",text="/清除綁定")
),
QuickReplyButton(
action=MessageAction(label="今日課表",text="/今日課表")
),
QuickReplyButton(
action=MessageAction(label="請假紀錄",text="/請假紀錄")
),
QuickReplyButton(
action=MessageAction(label="你今天被實驗助教搞了嗎",text="/你今天被實驗助教搞了嗎")
)#還有成績指令沒寫完
]
)
)
line_bot_api.push_message(id, quick_reply)
return
def limited_command(msg,event):
if '/變更密碼' in msg or '/更改密碼' in msg:
get_now_user_id = event.source.user_id
if get_now_user_id in useridlist:#帳號存在
change_password = msg.replace("/變更密碼","").replace(" ","").replace("/更改密碼","")
if change_password == "":
line_bot_api.reply_message(event.reply_token, TextSendMessage("警告 密碼不能為空"))
else:
with open("json/change_password.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id , "change_password" : change_password})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)
else:#帳號不存在
with open("json/account_not_exist.json",encoding="utf-8") as path:
FlexMessage = json.loads(path.read() % {"get_now_user_id" : get_now_user_id})
flex_message = FlexSendMessage(
alt_text = '(請點擊聊天室已取得更多消息)' ,
contents = FlexMessage)
print("傳出flexmsg")
line_bot_api.reply_message(event.reply_token, flex_message)