-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·1136 lines (1000 loc) · 44.1 KB
/
app.py
File metadata and controls
executable file
·1136 lines (1000 loc) · 44.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""LINE Bot 題目練習應用程式,提供多題庫練習、即時回饋和答題統計功能。"""
import asyncio
import base64
import hashlib
import hmac
import json
import logging
import os
import random
from datetime import datetime
from dotenv import find_dotenv, load_dotenv
from flask import Flask, request
from linebot.v3 import WebhookHandler
from linebot.v3.exceptions import InvalidSignatureError
from linebot.v3.messaging import (
ApiClient,
AsyncApiClient,
AsyncMessagingApi,
Configuration,
FlexContainer,
FlexMessage,
MessagingApi,
ReplyMessageRequest,
ShowLoadingAnimationRequest,
TextMessage,
)
from linebot.v3.webhooks import MessageEvent, TextMessageContent
from database import Database
from flask_logs import LogSetup
load_dotenv(find_dotenv())
access_token = os.getenv("ACCESS_TOKEN")
secret = os.getenv("SECRET")
configuration = Configuration(access_token=access_token)
handler = WebhookHandler(secret)
app = Flask(__name__)
app.config["LOG_TYPE"] = os.environ.get("LOG_TYPE", "watched")
app.config["LOG_LEVEL"] = os.environ.get("LOG_LEVEL", "INFO")
app.config["LOG_DIR"] = os.environ.get("LOG_DIR", "./logs")
app.config["APP_LOG_NAME"] = os.environ.get("APP_LOG_NAME", "app.log")
app.config["WWW_LOG_NAME"] = os.environ.get("WWW_LOG_NAME", "access.log")
app.config["LOG_MAX_BYTES"] = os.environ.get(
"LOG_MAX_BYTES", 100_000_000
) # 100MB in bytes
app.config["LOG_COPIES"] = os.environ.get("LOG_COPIES", 5)
logs = LogSetup()
logs.init_app(app)
# 定義全局變量
current_question = None
current_question_data = None # 用於存儲完整的題目數據
current_database = None # 用於追踪當前題庫
user_selections = {} # 添加全局變量來儲存用戶選擇
user_question_options = {} # 添加全局變量來儲存每個用戶的題目選項順序
user_current_question = {} # user_id: 正確答案
user_current_question_data = {} # user_id: 題目完整資料
@app.after_request
def after_request(response):
"""Logging after every request."""
logger = logging.getLogger("app.access")
logger.info(
"%s [%s] %s %s %s %s %s %s %s",
request.remote_addr,
datetime.now().strftime("%d/%b/%Y:%H:%M:%S.%f")[:-3],
request.method,
request.path,
request.scheme,
response.status,
response.content_length,
request.referrer,
request.user_agent,
)
return response
# 初始化數據庫
db = Database()
def create_database_flex_message(page=1):
"""創建題庫選擇的 Flex Message
Args:
page (int): 當前頁碼,從1開始
"""
try:
# 讀取基本模板
with open("templates/database_flex_message.json", "r", encoding="utf-8") as f:
flex_message = json.load(f)
# 獲取 database 資料夾中的所有 json 文件
database_files = [f for f in os.listdir("database") if f.endswith(".json")]
# 計算分頁資訊
items_per_page = 10 # 每頁顯示10個題庫
total_pages = (len(database_files) + items_per_page - 1) // items_per_page
# 確保頁碼有效
page = max(1, min(page, total_pages))
# 計算當前頁的題庫
start_idx = (page - 1) * items_per_page
end_idx = start_idx + items_per_page
current_page_files = database_files[start_idx:end_idx]
# 創建題庫氣泡列表
bubbles = []
for db_file in current_page_files:
# 移除 .json 副檔名,作為題庫名稱
db_name = db_file[:-5]
# 將 _multi 替換為 _多選
display_name = db_name.replace("_multi", "_多選")
# 如果題庫名稱太長,截斷它
if len(display_name) > 20: # 為了在氣泡中顯示得更好
display_name = display_name[:17] + "..."
bubble = {
"type": "bubble",
"size": "micro",
"body": {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": display_name,
"weight": "bold",
"size": "md",
"wrap": True,
"align": "center",
},
{
"type": "button",
"style": "primary",
"color": "#5A8DEE",
"action": {
"type": "message",
"label": "開始練習",
"text": f"切換到 {db_name}",
},
},
],
},
}
bubbles.append(bubble)
# 添加分頁控制氣泡
if total_pages > 1:
navigation_contents = [
{
"type": "text",
"text": f"第 {page}/{total_pages} 頁",
"weight": "bold",
"size": "sm",
"align": "center",
}
]
# 上一頁按鈕
if page > 1:
navigation_contents.append(
{
"type": "button",
"style": "secondary",
"action": {
"type": "message",
"label": "上一頁",
"text": f"題庫列表 {page - 1}",
},
}
)
# 下一頁按鈕
if page < total_pages:
navigation_contents.append(
{
"type": "button",
"style": "secondary",
"action": {
"type": "message",
"label": "下一頁",
"text": f"題庫列表 {page + 1}",
},
}
)
navigation_bubble = {
"type": "bubble",
"size": "micro",
"body": {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": navigation_contents,
},
}
bubbles.append(navigation_bubble)
# 更新 carousel 內容
flex_message["contents"] = bubbles
return flex_message
except Exception as e:
print(f"Error creating database flex message: {e}")
return None
def get_question(database_name=None):
"""從指定題庫或預設題庫中讀取隨機題目"""
try:
file_path = (
f"database/{database_name}.json" if database_name else "questions.json"
)
with open(file_path, "r", encoding="utf-8") as f:
questions_data = json.load(f)
questions = questions_data["questions"]
return random.choice(questions)
except Exception as e:
print(f"Error reading questions: {e}")
return None
def is_multi_choice_db(database_name):
"""判斷是否為多選題庫"""
return database_name.endswith("multi")
def create_flex_message(
question_data, selected_options=None, user_id=None, is_multi=False
):
"""創建 Flex Message,保持ABCD順序不變,但選項內容隨機排序
Args:
question_data: 題目數據
selected_options: 已選擇的選項集合
user_id: 用戶ID,用於追踪選項順序
is_multi: 是否為多選題
"""
global current_question, current_question_data, user_question_options
# 根據題目類型選擇不同的模板文件
template_file = (
"templates/multi_flex_message.json"
if is_multi
else "templates/topic_flex_message.json"
)
with open(template_file, "r", encoding="utf-8") as f:
flex_message = json.load(f)
# 保存當前題目數據
current_question = question_data["answer"] # 這裡可能是單個字母或多個字母的字符串
current_question_data = question_data
# 設置題目文字(如果太長則截斷)
question_text = question_data["question_text"]
if len(question_text) > 100: # 限制題目長度
question_text = question_text[:97] + "..."
flex_message["body"]["contents"][1]["text"] = f"🧠 題目:{question_text}"
# 檢查是否已有固定的選項順序
if (
is_multi
and user_id
and user_id in user_question_options
and question_data["id"] == user_question_options[user_id]["id"]
):
# 使用已存在的選項順序
new_options = user_question_options[user_id]["options"]
current_question = user_question_options[user_id]["answer"]
else:
# 首次顯示題目,隨機排序選項
options = list(question_data["options"].values()) # 獲取選項內容列表
random.shuffle(options) # 隨機打亂選項內容
# 創建新的選項映射
new_options = {}
original_answers = list(question_data["answer"]) # 將答案字符串轉換為列表
# 建立新的選項對應關係
new_answers = [] # 用於存儲新的答案字母
for i, option in enumerate(options):
char = "ABCD"[i]
new_options[char] = option
# 檢查這個選項是否是原來的正確答案之一
for original_answer in original_answers:
if option == question_data["options"][original_answer]:
new_answers.append(char)
# 更新正確答案為新的字母組合
current_question = "".join(sorted(new_answers))
# 保存選項順序(僅多選題需要)
if is_multi and user_id:
user_question_options[user_id] = {
"id": question_data["id"],
"options": new_options,
"answer": current_question,
}
# 更新題目數據中的選項
current_question_data = question_data.copy()
current_question_data["options"] = new_options
current_question_data["answer"] = current_question
# 創建選項容器
options_container = {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": [],
}
# 如果沒有已選擇的選項,初始化為空集合
if selected_options is None:
selected_options = set()
# 設置選項按鈕(按 A,B,C,D 順序)
for i, char in enumerate("ABCD"):
if is_multi:
# 多選題使用盒子樣式,有背景色變化
background_color = "#5A8DEE" if char in selected_options else "#AAAAAA"
option_box = {
"type": "box",
"layout": "vertical",
"cornerRadius": "xxl",
"backgroundColor": background_color,
"action": {"type": "message", "text": f"選擇 {char}"},
"contents": [
{
"type": "box",
"layout": "horizontal",
"paddingAll": "lg",
"contents": [
{
"type": "text",
"text": f"{char}. {new_options[char]}",
"color": "#ffffff",
"wrap": True,
"size": "sm",
"flex": 1,
}
],
}
],
}
else:
# 單選題使用盒子樣式
option_box = {
"type": "box",
"layout": "vertical",
"cornerRadius": "xxl",
"backgroundColor": "#5A8DEE",
"action": {"type": "message", "text": f"選擇 {char}"},
"contents": [
{
"type": "box",
"layout": "horizontal",
"paddingAll": "lg",
"contents": [
{
"type": "text",
"text": f"{char}. {new_options[char]}",
"color": "#ffffff",
"wrap": True,
"size": "sm",
"flex": 1,
}
],
}
],
}
options_container["contents"].append(option_box)
# 更新 flex message 中的選項容器
flex_message["body"]["contents"][3] = options_container
# 獲取題目的作答統計
attempt_stats = db.get_question_attempt_stats(question_data["id"], current_database)
print(f"Got attempt stats: {attempt_stats}")
# 更新 footer 中的統計信息
if "footer" in flex_message:
stats_box = flex_message["footer"]["contents"][0]
if isinstance(stats_box, dict) and "contents" in stats_box:
print(f"Updating stats in footer: {stats_box}")
# 直接設置實際的數值,而不是使用佔位符
stats_box["contents"][0]["text"] = (
f"作答次數:{attempt_stats['total_attempts']}"
)
stats_box["contents"][1]["text"] = (
f"答對次數:{attempt_stats['correct_attempts']}"
)
print(f"Updated footer stats: {stats_box}")
else:
print(f"Unexpected footer structure: {stats_box}")
if user_id:
user_current_question[user_id] = current_question
user_current_question_data[user_id] = current_question_data
return flex_message
def create_statistics_flex_message(user_id, database_name):
"""創建統計信息的 Flex Message"""
try:
# 讀取基本模板
with open("templates/statistics_flex_message.json", "r", encoding="utf-8") as f:
flex_message = json.load(f)
# 獲取統計數據
stats = db.get_user_statistics(user_id, database_name)
# 更新模板中的變量
flex_message["body"]["contents"][1]["text"] = f"📚 當前題庫:{database_name}"
# 更新統計數據
stats_box = flex_message["body"]["contents"][2]["contents"]
for box in stats_box:
if box.get("type") == "box" and box.get("layout") == "baseline":
value_text = box["contents"][1]
if "總題目數" in box["contents"][0]["text"]:
value_text["text"] = str(stats["total_questions"])
elif "已答題數" in box["contents"][0]["text"]:
value_text["text"] = str(stats["total_answers"])
elif "答對題數" in box["contents"][0]["text"]:
value_text["text"] = str(stats["correct_answers"])
elif "完成率" in box["contents"][0]["text"]:
value_text["text"] = f"{stats['completion_rate']:.1f}%"
elif "正確率" in box["contents"][0]["text"]:
value_text["text"] = f"{stats['accuracy_rate']:.1f}%"
elif "錯題數" in box["contents"][0]["text"]:
value_text["text"] = str(stats["total_wrong_questions"])
# 如果有錯題練習記錄,添加相關統計
if stats["practice_count"] > 0:
practice_stats = {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"margin": "xl",
"contents": [
{
"type": "text",
"text": "📝 錯題練習統計",
"weight": "bold",
"size": "md",
"color": "#1a1a1a",
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "練習次數",
"size": "sm",
"color": "#888888",
"flex": 1,
},
{
"type": "text",
"text": str(stats["practice_count"]),
"size": "sm",
"color": "#5A8DEE",
"align": "end",
},
],
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "答對次數",
"size": "sm",
"color": "#888888",
"flex": 1,
},
{
"type": "text",
"text": str(stats["practice_correct"]),
"size": "sm",
"color": "#00C851",
"align": "end",
},
],
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "練習正確率",
"size": "sm",
"color": "#888888",
"flex": 1,
},
{
"type": "text",
"text": f"{stats['practice_accuracy_rate']:.1f}%",
"size": "sm",
"color": "#00C851",
"align": "end",
},
],
},
],
}
flex_message["body"]["contents"].append(practice_stats)
return flex_message
except Exception as e:
print(f"Error creating statistics flex message: {e}")
return None
def send_question(reply_token, database_name=None, user_id=None, wrong_question=None):
"""發送新題目"""
global current_database
try:
# 如果沒有指定題庫名稱,使用當前題庫或第一個可用的題庫
if database_name is None:
if current_database:
database_name = current_database
else:
database_files = [
f[:-5] for f in os.listdir("database") if f.endswith(".json")
]
if not database_files:
raise FileNotFoundError("找不到任何題庫文件")
database_name = database_files[0]
current_database = database_name
is_multi = is_multi_choice_db(database_name)
# 更新用戶當前題庫
if user_id:
db.update_user_state(user_id, database_name)
# 獲取題目
if wrong_question:
question_data = wrong_question["question_data"]
else:
question_data = get_question(database_name)
if not question_data:
raise ValueError("無法從題庫中獲取題目")
# 清除用戶之前的選項順序
if user_id in user_question_options:
del user_question_options[user_id]
# 創建 Flex Message
flex_content = create_flex_message(question_data, set(), user_id, is_multi)
if not flex_content:
raise ValueError("無法創建 Flex Message")
flex_content["body"]["contents"][0]["text"] = f"📚 題庫:{database_name}"
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=reply_token,
messages=[
FlexMessage(
alt_text=f"iPAS {database_name}題目",
contents=FlexContainer.from_dict(flex_content),
)
],
)
)
except Exception as e:
print(f"Error in send_question: {e}")
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=reply_token,
messages=[
TextMessage(
text="抱歉,讀取題目時發生錯誤。請稍後再試或切換其他題庫。"
)
],
)
)
def create_answer_flex_message(question_data, selected_answer, is_correct):
"""創建答案回覆的 Flex Message"""
try:
with open("templates/answer_flex_message.json", "r", encoding="utf-8") as f:
flex_message = json.load(f)
# 設置答對/答錯的文字和顏色
flex_message["body"]["contents"][0]["text"] = (
"✅ 答對了!" if is_correct else "❌ 答錯了!"
)
flex_message["body"]["contents"][0]["color"] = (
"#00C851" if is_correct else "#ff4444"
)
# 設置題目文字(如果太長則截斷)
question_text = question_data["question_text"]
if len(question_text) > 100: # 限制題目長度
question_text = question_text[:97] + "..."
flex_message["body"]["contents"][2]["text"] = question_text
# 設置正確答案(如果太長則截斷)
# 對於多選題,顯示所有正確答案
correct_answers = []
for ans in question_data["answer"]:
correct_answers.append(f"{ans}. {question_data['options'][ans]}")
correct_answer_text = "\n".join(correct_answers)
if len(correct_answer_text) > 200: # 限制答案長度
correct_answer_text = correct_answer_text[:197] + "..."
flex_message["body"]["contents"][3]["contents"][1]["text"] = correct_answer_text
return flex_message
except Exception as e:
print(f"Error creating answer flex message: {e}")
return None
@app.route("/", methods=["POST"])
def callback():
# 获取基本请求信息
ip = request.remote_addr
method = request.method
path = request.path
# 获取 X-Line-Signature 请求头
signature = request.headers.get("X-Line-Signature", "")
if not signature:
extra = {"ip": ip, "method": method, "path": path, "status": 400, "size": 0}
logging.warning("Missing X-Line-Signature header", extra=extra)
return "Bad Request", 400
# 获取请求体
body = request.get_data(as_text=True)
# 验证签名
try:
# 使用环境变量中的 channel secret
channel_secret = os.getenv("SECRET")
if not channel_secret:
extra = {"ip": ip, "method": method, "path": path, "status": 500, "size": 0}
logging.error("Missing channel secret", extra=extra)
return "Server Error", 500
# 计算签名
hash_obj = hmac.new(
channel_secret.encode("utf-8"), body.encode("utf-8"), hashlib.sha256
)
calculated_signature = base64.b64encode(hash_obj.digest()).decode("utf-8")
# 比较签名
if not hmac.compare_digest(signature, calculated_signature):
extra = {"ip": ip, "method": method, "path": path, "status": 400, "size": 0}
logging.warning("Invalid signature", extra=extra)
return "Bad Request", 400
# 处理 webhook 请求
handler.handle(body, signature)
# 记录成功请求
extra = {
"ip": ip,
"method": method,
"path": path,
"status": 200,
"size": len(body),
}
logging.info("Request processed successfully", extra=extra)
return "OK"
except InvalidSignatureError:
extra = {"ip": ip, "method": method, "path": path, "status": 400, "size": 0}
logging.warning("Invalid signature", extra=extra)
return "Bad Request", 400
except Exception as e:
extra = {"ip": ip, "method": method, "path": path, "status": 500, "size": 0}
logging.error("Error processing webhook: %s", str(e), extra=extra)
return "Server Error", 500
@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
"""處理收到的消息"""
global is_wrong_question_practice
try:
message_text = event.message.text
user_id = event.source.user_id
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
# 檢查當前是否為多選題庫
is_multi = current_database and is_multi_choice_db(current_database)
# 如果是選項選擇
if message_text.startswith("選擇 "):
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
# 從消息中提取選項(例如:"選擇 A. 選項內容" -> "A")
selected_answer = message_text.split(" ")[1].split(".")[0]
if not is_multi:
# 單選題直接檢查答案
if (
user_id in user_current_question
and user_id in user_current_question_data
):
correct_answer = user_current_question[user_id]
question_data = user_current_question_data[user_id]
is_correct = selected_answer == correct_answer
# 記錄答題
db.record_answer(
user_id=user_id,
question_data=question_data,
user_answer=selected_answer,
is_correct=is_correct,
database_name=current_database,
is_wrong_question_practice=getattr(
globals(), "is_wrong_question_practice", False
),
)
# 清除
del user_current_question[user_id]
del user_current_question_data[user_id]
# 顯示結果
result_flex = create_answer_flex_message(
question_data, selected_answer, is_correct
)
if result_flex:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(
alt_text="題目回顧",
contents=FlexContainer.from_dict(
result_flex
),
)
],
)
)
return
else:
# 多選題只更新選擇,不做答題判斷
if user_id not in user_selections:
user_selections[user_id] = set()
if selected_answer in user_selections[user_id]:
user_selections[user_id].remove(selected_answer)
else:
user_selections[user_id].add(selected_answer)
# 更新畫面
if user_id in user_current_question_data:
flex_content = create_flex_message(
user_current_question_data[user_id],
user_selections[user_id],
user_id,
True,
)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(
alt_text="選擇題選項",
contents=FlexContainer.from_dict(flex_content),
)
],
)
)
return
# 如果是清除選擇(僅多選題可用)
elif message_text == "清除選擇" and is_multi:
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
if user_id in user_selections:
user_selections[user_id].clear()
if user_id in user_current_question_data:
flex_content = create_flex_message(
user_current_question_data[user_id], set(), user_id, True
)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(
alt_text="選擇題選項",
contents=FlexContainer.from_dict(flex_content),
)
],
)
)
return
# 如果是送出答案(僅多選題可用)
elif message_text == "送出答案" and is_multi:
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
if user_id not in user_selections or not user_selections[user_id]:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text="請先選擇答案")],
)
)
return
if (
user_id in user_current_question
and user_id in user_current_question_data
):
correct_answer = user_current_question[user_id]
question_data = user_current_question_data[user_id]
selected_answers = sorted(user_selections[user_id])
is_correct = len(selected_answers) == len(correct_answer) and all(
ans in correct_answer for ans in selected_answers
)
# 記錄答題
db.record_answer(
user_id=user_id,
question_data=question_data,
user_answer=",".join(selected_answers),
is_correct=is_correct,
database_name=current_database,
is_wrong_question_practice=getattr(
globals(), "is_wrong_question_practice", False
),
)
# 重置錯題練習標記
if "is_wrong_question_practice" in globals():
del is_wrong_question_practice
result_flex = create_answer_flex_message(
question_data, ",".join(selected_answers), is_correct
)
user_selections[user_id].clear()
if user_id in user_question_options:
del user_question_options[user_id]
if result_flex:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(
alt_text="題目回顧",
contents=FlexContainer.from_dict(result_flex),
)
],
)
)
return
# 如果是查看統計
elif message_text == "查看統計":
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
current_db = db.get_user_state(user_id)
if current_db:
stats_flex = create_statistics_flex_message(user_id, current_db)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(
alt_text="答題統計",
contents=FlexContainer.from_dict(stats_flex),
)
],
)
)
else:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text="請先選擇題庫開始練習")],
)
)
return
# 如果是練習錯題
elif message_text == "練習錯題":
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
current_db = db.get_user_state(user_id)
if current_db:
wrong_questions = db.get_wrong_questions(user_id, current_db)
if wrong_questions:
# 隨機選擇一道錯題
wrong_question = random.choice(wrong_questions)
# 發送題目時標記為錯題練習
is_wrong_question_practice = True
send_question(
event.reply_token, current_db, user_id, wrong_question
)
else:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text="目前沒有錯題記錄")],
)
)
else:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text="請先選擇題庫開始練習")],
)
)
return
# 如果是切換題庫請求
elif message_text == "切換題庫":
# 顯示 loading animation
async def show_loading():
async_api_client = AsyncApiClient(configuration)
async_line_bot_api = AsyncMessagingApi(async_api_client)
await async_line_bot_api.show_loading_animation(
ShowLoadingAnimationRequest(chatId=user_id, loadingSeconds=5)
)
asyncio.run(show_loading())
flex_content = create_database_flex_message(page=1)
if flex_content:
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
FlexMessage(