-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathgui.py
More file actions
2451 lines (2048 loc) · 102 KB
/
Copy pathgui.py
File metadata and controls
2451 lines (2048 loc) · 102 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
"""闲鱼智能客服 - 可视化界面(新版侧边栏布局)"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import threading
import asyncio
import sys
import os
import json
import ctypes
from pathlib import Path
from PIL import Image, ImageDraw, ImageTk, ImageFont
# 确保能找到其他模块
sys.path.insert(0, str(Path(__file__).parent))
from dotenv import load_dotenv, set_key
from loguru import logger
from logger_setup import set_gui_conversation_callback, rebind_console_output
from config import DEFAULT_STATUS_MAPPING, DEFAULT_COZE_VARS, Config
def _extract_status_mapping_values(value):
"""从状态映射值中提取 mapped 和 system_msg 字段"""
if isinstance(value, dict):
return value.get('mapped', ''), value.get('system_msg', '')
return value, ''
class XianyuGUI:
def __init__(self):
self.root = tk.Tk()
self.root.title("闲鱼智能客服 RPA")
self.root.geometry("1200x750")
self.root.minsize(1000, 650)
self.root.resizable(True, True)
# 状态变量
self.is_running = False
self.is_paused = False
self.handler = None
self.loop = None
self.thread = None
self.show_debug_logs = False
self.log_handler_id = None
self.float_ball = None # 悬浮球窗口
# 控制台窗口状态
self.console_visible = False
self._init_console_control()
# Coze变量配置
self.coze_vars_config = {}
self.status_mapping = {}
self.prompt_content = ''
self.title_grab_length = 15 # 默认抓取标题字符数
self.vars_config_path = Path(__file__).parent / "coze_vars_config.json"
# 加载当前配置
self.env_path = Path(__file__).parent / ".env"
load_dotenv(self.env_path)
self._load_coze_vars_config()
# 当前页面
self.current_page = None
self.pages = {}
self.nav_buttons = {}
# 创建主界面
self._create_main_layout()
self._load_config()
# 重定向日志到界面
self._setup_logging()
# 注册对话记录回调
self._register_conversation_callback()
# 默认显示概览页
self._show_page("overview")
def _create_main_layout(self):
"""创建主布局:左侧导航 + 右侧内容"""
# 主容器
main_container = ttk.Frame(self.root)
main_container.pack(fill="both", expand=True)
# ===== 左侧导航栏 =====
self.nav_frame = tk.Frame(main_container, bg="#1a5fb4", width=140)
self.nav_frame.pack(side="left", fill="y")
self.nav_frame.pack_propagate(False)
# Logo/标题区域
logo_frame = tk.Frame(self.nav_frame, bg="#1a5fb4", height=60)
logo_frame.pack(fill="x")
logo_frame.pack_propagate(False)
tk.Label(
logo_frame,
text="闲鱼RPA",
font=("Microsoft YaHei", 14, "bold"),
fg="white",
bg="#1a5fb4"
).pack(expand=True)
# 导航按钮
nav_items = [
("overview", "概览"),
("reply_settings", "回复设置"),
("memory", "跨窗口记忆"),
("merge", "多消息合并"),
("coze_sessions", "会话管理"),
("sync_products", "同步商品"),
("system_settings", "系统设置"),
]
for page_id, text in nav_items:
btn = tk.Button(
self.nav_frame,
text=text,
font=("Microsoft YaHei", 10),
fg="white",
bg="#1a5fb4",
activebackground="#3584e4",
activeforeground="white",
bd=0,
pady=12,
cursor="hand2",
command=lambda p=page_id: self._show_page(p)
)
btn.pack(fill="x")
self.nav_buttons[page_id] = btn
# 鼠标悬停效果
btn.bind("<Enter>", lambda e, b=btn: b.config(bg="#3584e4") if b != self.nav_buttons.get(self.current_page) else None)
btn.bind("<Leave>", lambda e, b=btn, p=page_id: b.config(bg="#1a5fb4") if p != self.current_page else None)
# ===== 右侧内容区域 =====
self.content_frame = ttk.Frame(main_container)
self.content_frame.pack(side="right", fill="both", expand=True)
# 创建各个页面
self._create_overview_page()
self._create_reply_settings_page()
self._create_memory_page()
self._create_merge_page()
self._create_coze_sessions_page()
self._create_sync_products_page()
self._create_system_settings_page()
def _show_page(self, page_id):
"""切换显示页面"""
# 隐藏所有页面
for page in self.pages.values():
page.pack_forget()
# 更新导航按钮样式
for pid, btn in self.nav_buttons.items():
if pid == page_id:
btn.config(bg="#3584e4")
else:
btn.config(bg="#1a5fb4")
# 显示目标页面
self.current_page = page_id
if page_id in self.pages:
self.pages[page_id].pack(fill="both", expand=True)
# 如果是Coze会话页,自动刷新列表
if page_id == "coze_sessions" and hasattr(self, '_refresh_coze_sessions'):
self._refresh_coze_sessions()
# 如果是同步商品页,自动刷新列表
if page_id == "sync_products" and hasattr(self, '_refresh_products_list'):
self._refresh_products_list()
# ==================== 概览页 ====================
def _create_overview_page(self):
"""创建概览页"""
page = ttk.Frame(self.content_frame)
self.pages["overview"] = page
# 顶部控制栏
control_frame = ttk.Frame(page)
control_frame.pack(fill="x", padx=20, pady=15)
# 启动/停止按钮
self.start_btn = ttk.Button(
control_frame,
text="启动",
command=self._toggle_running,
width=12
)
self.start_btn.pack(side="left", padx=5)
# 状态标签
self.status_var = tk.StringVar(value="已停止")
self.status_label = tk.Label(
control_frame,
textvariable=self.status_var,
font=("Microsoft YaHei", 10),
fg="gray"
)
self.status_label.pack(side="left", padx=20)
# 清空所有会话按钮
ttk.Button(
control_frame,
text="清空所有会话",
command=self._clear_all_sessions,
width=12
).pack(side="right", padx=5)
# 控制台显示/隐藏按钮
self.console_btn = ttk.Button(
control_frame,
text="显示控制台",
command=self._toggle_console,
width=10
)
self.console_btn.pack(side="right", padx=5)
# 悬浮球显示复选框
self.float_ball_visible_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
control_frame,
text="悬浮球",
variable=self.float_ball_visible_var,
command=self._toggle_float_ball_visibility
).pack(side="right", padx=5)
# 运行日志区域
log_frame = ttk.LabelFrame(page, text="运行日志", padding=10)
log_frame.pack(fill="both", expand=True, padx=20, pady=10)
# 创建 Notebook(对话记录/系统日志)
self.log_notebook = ttk.Notebook(log_frame)
self.log_notebook.pack(fill="both", expand=True)
# Tab 1: 对话记录表格
conv_tab = ttk.Frame(self.log_notebook)
self.log_notebook.add(conv_tab, text="对话记录")
# 对话记录表格
conv_columns = ('time', 'level', 'type', 'username', 'content', 'conv_id', 'order_status')
self.conv_tree = ttk.Treeview(conv_tab, columns=conv_columns, show='headings', height=15)
self.conv_tree.heading('time', text='时间')
self.conv_tree.heading('level', text='级别')
self.conv_tree.heading('type', text='类型')
self.conv_tree.heading('username', text='用户名')
self.conv_tree.heading('content', text='内容')
self.conv_tree.heading('conv_id', text='会话ID')
self.conv_tree.heading('order_status', text='订单状态')
self.conv_tree.column('time', width=70, minwidth=60, anchor='center')
self.conv_tree.column('level', width=50, minwidth=40, anchor='center')
self.conv_tree.column('type', width=50, minwidth=40, anchor='center')
self.conv_tree.column('username', width=100, minwidth=80, anchor='center')
self.conv_tree.column('content', width=400, minwidth=250, anchor='w')
self.conv_tree.column('conv_id', width=160, minwidth=120, anchor='center')
self.conv_tree.column('order_status', width=80, minwidth=60, anchor='center')
conv_scrollbar = ttk.Scrollbar(conv_tab, orient="vertical", command=self.conv_tree.yview)
self.conv_tree.configure(yscrollcommand=conv_scrollbar.set)
self.conv_tree.pack(side="left", fill="both", expand=True)
conv_scrollbar.pack(side="right", fill="y")
# 设置行颜色
self.conv_tree.tag_configure('user', background='#e3f2fd')
self.conv_tree.tag_configure('ai', background='#f3e5f5')
self.conv_tree.tag_configure('info', background='#ffffff')
self.conv_tree.tag_configure('warning', background='#fff8e1')
self.conv_tree.tag_configure('error', background='#ffebee')
# Tab 2: 系统日志
sys_tab = ttk.Frame(self.log_notebook)
self.log_notebook.add(sys_tab, text="系统日志")
self.log_text = scrolledtext.ScrolledText(
sys_tab,
height=15,
font=("Consolas", 9),
bg="#1e1e1e",
fg="#d4d4d4",
insertbackground="white",
state="disabled"
)
self.log_text.pack(fill="both", expand=True)
# 配置日志颜色标签
self.log_text.tag_configure("INFO", foreground="#4ec9b0")
self.log_text.tag_configure("DEBUG", foreground="#808080")
self.log_text.tag_configure("WARNING", foreground="#dcdcaa")
self.log_text.tag_configure("ERROR", foreground="#f14c4c")
self.log_text.tag_configure("SUCCESS", foreground="#6a9955")
self.log_text.tag_configure("TIME", foreground="#569cd6")
# 日志控制区域
log_control_frame = ttk.Frame(log_frame)
log_control_frame.pack(fill="x", pady=5)
self.debug_log_var = tk.BooleanVar(value=False)
ttk.Checkbutton(
log_control_frame,
text="显示详细日志",
variable=self.debug_log_var,
command=self._toggle_debug_logs
).pack(side="left")
ttk.Button(log_control_frame, text="清空日志", command=self._clear_log).pack(side="right")
# ==================== 回复设置页 ====================
def _create_reply_settings_page(self):
"""创建回复设置页"""
page = ttk.Frame(self.content_frame)
self.pages["reply_settings"] = page
# 设置区域
settings_frame = ttk.LabelFrame(page, text="回复设置", padding=15)
settings_frame.pack(fill="x", padx=20, pady=15)
# 检查间隔
row1 = ttk.Frame(settings_frame)
row1.pack(fill="x", pady=8)
ttk.Label(row1, text="检查间隔 (秒):", width=15).pack(side="left")
self.interval_var = tk.StringVar(value="2")
interval_spinbox = ttk.Spinbox(row1, from_=1, to=60, textvariable=self.interval_var, width=8)
interval_spinbox.pack(side="left", padx=5)
interval_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
# 重复消息过滤
row2 = ttk.Frame(settings_frame)
row2.pack(fill="x", pady=8)
ttk.Label(row2, text="重复消息过滤:", width=15).pack(side="left")
self.skip_duplicate_var = tk.BooleanVar(value=True)
ttk.Checkbutton(row2, text="启用", variable=self.skip_duplicate_var,
command=self._on_duplicate_toggle).pack(side="left")
ttk.Label(row2, text="过期时间:").pack(side="left", padx=(20, 5))
self.msg_expire_var = tk.StringVar(value="60")
self.msg_expire_spinbox = ttk.Spinbox(row2, from_=0, to=300, textvariable=self.msg_expire_var, width=6)
self.msg_expire_spinbox.pack(side="left")
self.msg_expire_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row2, text="秒").pack(side="left", padx=3)
# 主动发消息
row3 = ttk.Frame(settings_frame)
row3.pack(fill="x", pady=8)
ttk.Label(row3, text="主动发消息:", width=15).pack(side="left")
self.inactive_enabled_var = tk.BooleanVar(value=True)
ttk.Checkbutton(row3, text="启用", variable=self.inactive_enabled_var,
command=self._on_inactive_toggle).pack(side="left")
ttk.Label(row3, text="超时:").pack(side="left", padx=(20, 5))
self.inactive_timeout_var = tk.StringVar(value="3")
self.inactive_timeout_spinbox = ttk.Spinbox(row3, from_=1, to=30, textvariable=self.inactive_timeout_var, width=5)
self.inactive_timeout_spinbox.pack(side="left")
self.inactive_timeout_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row3, text="分钟").pack(side="left", padx=3)
# 会话切入延迟
row4 = ttk.Frame(settings_frame)
row4.pack(fill="x", pady=8)
ttk.Label(row4, text="会话切入延迟:", width=15).pack(side="left")
self.enter_delay_var = tk.StringVar(value="1.5")
enter_delay_spinbox = ttk.Spinbox(row4, from_=0.5, to=5.0, increment=0.5,
textvariable=self.enter_delay_var, width=6)
enter_delay_spinbox.pack(side="left")
enter_delay_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row4, text="秒 (进入会话后等待页面加载)").pack(side="left", padx=5)
# 系统提示词
prompt_frame = ttk.LabelFrame(page, text="系统提示词 (prompt)", padding=15)
prompt_frame.pack(fill="both", expand=True, padx=20, pady=10)
ttk.Label(prompt_frame, text="在 Coze 智能体的人设中使用 {{prompt}} 引用此变量:").pack(anchor="w")
self.prompt_text = tk.Text(prompt_frame, height=8, font=("Microsoft YaHei", 9))
self.prompt_text.pack(fill="both", expand=True, pady=5)
self.prompt_text.bind("<FocusOut>", lambda e: self._auto_save_config())
# ==================== 跨窗口记忆页 ====================
def _create_memory_page(self):
"""创建跨窗口记忆页"""
page = ttk.Frame(self.content_frame)
self.pages["memory"] = page
# 标题
ttk.Label(
page,
text="跨窗口记忆 - 跨商品上下文传递",
font=("Microsoft YaHei", 12, "bold")
).pack(pady=15)
# 说明文字
desc_frame = ttk.LabelFrame(page, text="功能说明", padding=10)
desc_frame.pack(fill="x", padx=20, pady=5)
desc_text = """当同一个用户从不同商品页面发起聊天时,系统会自动获取该用户之前与其他商品的对话历史,
并将这些历史记录作为上下文传递给新会话的第一条消息,帮助AI更好地了解用户的需求和偏好。
适用场景:
• 用户咨询过商品A后,又来咨询商品B
• 用户是回头客,之前有过购买/咨询记录
• 需要跨商品保持对话连贯性的场景"""
ttk.Label(desc_frame, text=desc_text, justify="left", wraplength=800).pack(anchor="w")
# 设置区域
settings_frame = ttk.LabelFrame(page, text="设置", padding=15)
settings_frame.pack(fill="x", padx=20, pady=10)
# 启用开关
row1 = ttk.Frame(settings_frame)
row1.pack(fill="x", pady=8)
self.memory_enabled_var = tk.BooleanVar(value=True)
ttk.Checkbutton(row1, text="启用跨窗口记忆功能", variable=self.memory_enabled_var,
command=self._auto_save_config).pack(side="left")
# 上下文轮数
row2 = ttk.Frame(settings_frame)
row2.pack(fill="x", pady=8)
ttk.Label(row2, text="获取历史对话轮数:").pack(side="left")
self.memory_rounds_var = tk.StringVar(value="5")
memory_spinbox = ttk.Spinbox(row2, from_=1, to=20, textvariable=self.memory_rounds_var, width=5)
memory_spinbox.pack(side="left", padx=5)
memory_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row2, text="轮 (每轮包含用户问+AI答)").pack(side="left")
# 示例展示
example_frame = ttk.LabelFrame(page, text="传递给新会话的 input 内容示例", padding=10)
example_frame.pack(fill="both", expand=True, padx=20, pady=10)
example_text = scrolledtext.ScrolledText(example_frame, height=12, font=("Consolas", 9), bg="#f5f5f5")
example_text.pack(fill="both", expand=True)
example_content = """[历史会话记录]
会话ID: 7593074481959125027
商品ID: 7890123456
商品标题:小米10 PRO 内存12+512
对话内容:
user:你好,这个手机是什么颜色的?
AI:这款是黑色的哦,成色很新。
user:电池健康度怎么样?
AI:电池健康度92%,续航很好的。
user:价格能便宜点吗?
AI:已经是最低价了呢,质量绝对有保障。
当前消息:你好,这个耳机还在吗?"""
example_text.insert("1.0", example_content)
example_text.config(state="disabled")
# ==================== 多消息合并页 ====================
def _create_merge_page(self):
"""创建多消息合并页"""
page = ttk.Frame(self.content_frame)
self.pages["merge"] = page
# 标题
ttk.Label(
page,
text="多消息合并 - 防止用户分段发送导致AI回复混乱",
font=("Microsoft YaHei", 12, "bold")
).pack(pady=15)
# 说明文字
desc_frame = ttk.LabelFrame(page, text="功能说明", padding=10)
desc_frame.pack(fill="x", padx=20, pady=5)
desc_text = """当用户快速连续发送多条短消息时(如"pro"、"还有"、"吗"),系统会等待一段时间,
将这些消息合并成一条完整的消息("pro还有吗")再发送给AI处理,避免AI对不完整的消息产生错误回复。
工作原理:
• 当收到长度小于阈值的短消息时,消息会进入等待队列
• 在等待时间内收到的新消息会不断追加到队列中
• 等待时间结束后,所有排队消息会合并成一条发送给AI
• 如果收到一条长消息,会立即将之前排队的消息一起合并处理"""
ttk.Label(desc_frame, text=desc_text, justify="left", wraplength=800).pack(anchor="w")
# 设置区域
settings_frame = ttk.LabelFrame(page, text="设置", padding=15)
settings_frame.pack(fill="x", padx=20, pady=10)
# 启用开关
row1 = ttk.Frame(settings_frame)
row1.pack(fill="x", pady=8)
self.merge_enabled_var = tk.BooleanVar(value=True)
ttk.Checkbutton(row1, text="启用多消息合并功能", variable=self.merge_enabled_var,
command=self._auto_save_config).pack(side="left")
# 等待时间
row2 = ttk.Frame(settings_frame)
row2.pack(fill="x", pady=8)
ttk.Label(row2, text="等待合并时间:").pack(side="left")
self.merge_wait_var = tk.StringVar(value="3")
merge_wait_spinbox = ttk.Spinbox(row2, from_=1, to=10, textvariable=self.merge_wait_var, width=5)
merge_wait_spinbox.pack(side="left", padx=5)
merge_wait_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row2, text="秒 (收到短消息后等待多久再处理)").pack(side="left")
# 短消息阈值
row3 = ttk.Frame(settings_frame)
row3.pack(fill="x", pady=8)
ttk.Label(row3, text="短消息阈值:").pack(side="left")
self.merge_min_length_var = tk.StringVar(value="5")
merge_length_spinbox = ttk.Spinbox(row3, from_=1, to=20, textvariable=self.merge_min_length_var, width=5)
merge_length_spinbox.pack(side="left", padx=5)
merge_length_spinbox.bind("<FocusOut>", lambda e: self._auto_save_config())
ttk.Label(row3, text="字 (低于此长度的消息会触发合并等待)").pack(side="left")
# 保存按钮
row4 = ttk.Frame(settings_frame)
row4.pack(fill="x", pady=(15, 5))
ttk.Button(row4, text="保存设置", command=self._save_merge_config).pack(side="left")
self.merge_save_status = tk.StringVar(value="")
ttk.Label(row4, textvariable=self.merge_save_status, foreground="green").pack(side="left", padx=10)
# 示例展示
example_frame = ttk.LabelFrame(page, text="效果示例", padding=10)
example_frame.pack(fill="both", expand=True, padx=20, pady=10)
example_text = scrolledtext.ScrolledText(example_frame, height=12, font=("Consolas", 9), bg="#f5f5f5")
example_text.pack(fill="both", expand=True)
example_content = """场景:用户想问 "pro还有吗",但分成3条发送
未开启消息合并时:
[10:00:01] 用户发送: "pro"
[10:00:01] AI回复: "您好,请问您是想了解Pro版本吗?" ❌ 错误回复
[10:00:02] 用户发送: "还有"
[10:00:02] AI回复: "还有什么呢?请问有什么需要帮助的?" ❌ 错误回复
[10:00:03] 用户发送: "吗"
[10:00:03] AI回复: "?" ❌ 错误回复
开启消息合并后(等待3秒):
[10:00:01] 用户发送: "pro" → 加入合并队列,等待3秒
[10:00:02] 用户发送: "还有" → 追加到队列,重置等待
[10:00:03] 用户发送: "吗" → 追加到队列,重置等待
[10:00:06] 3秒内无新消息,合并处理: "pro还有吗"
[10:00:06] AI回复: "Pro版还有货的,需要给您发链接吗?" ✓ 正确回复"""
example_text.insert("1.0", example_content)
example_text.config(state="disabled")
# ==================== 会话管理页 ====================
def _create_coze_sessions_page(self):
"""创建会话管理页"""
page = ttk.Frame(self.content_frame)
self.pages["coze_sessions"] = page
# 标题说明
ttk.Label(
page,
text="会话管理 - 查看和管理Coze服务器上的会话",
font=("Microsoft YaHei", 12, "bold")
).pack(pady=15)
# 列表区域
list_frame = ttk.Frame(page)
list_frame.pack(fill="both", expand=True, padx=20, pady=10)
# 创建表格
columns = ('conversation_id', 'user_id', 'buyer_name', 'item_id', 'created_at')
self.coze_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=18)
self.coze_tree.heading('conversation_id', text='会话ID')
self.coze_tree.heading('user_id', text='用户ID')
self.coze_tree.heading('buyer_name', text='用户名')
self.coze_tree.heading('item_id', text='商品ID')
self.coze_tree.heading('created_at', text='创建时间')
self.coze_tree.column('conversation_id', width=180, minwidth=150)
self.coze_tree.column('user_id', width=180, minwidth=150)
self.coze_tree.column('buyer_name', width=100, minwidth=80)
self.coze_tree.column('item_id', width=180, minwidth=150)
self.coze_tree.column('created_at', width=150, minwidth=120)
scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.coze_tree.yview)
self.coze_tree.configure(yscrollcommand=scrollbar.set)
self.coze_tree.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# 状态标签
self.coze_status_label = ttk.Label(page, text="")
self.coze_status_label.pack(pady=5)
# 按钮区域
btn_frame = ttk.Frame(page)
btn_frame.pack(pady=15)
ttk.Button(btn_frame, text="刷新列表", command=self._refresh_coze_sessions, width=12).pack(side="left", padx=5)
ttk.Button(btn_frame, text="清空Coze会话", command=self._clear_coze_sessions, width=14).pack(side="left", padx=5)
ttk.Button(btn_frame, text="清除本地记录", command=self._clear_local_sessions, width=14).pack(side="left", padx=5)
# 存储会话数据
self.coze_conversations_data = []
# ==================== 同步商品页 ====================
def _create_sync_products_page(self):
"""创建同步商品页"""
page = ttk.Frame(self.content_frame)
self.pages["sync_products"] = page
# 标题
ttk.Label(
page,
text="同步商品 - 抓取闲鱼商品信息",
font=("Microsoft YaHei", 12, "bold")
).pack(pady=15)
# 输入区域
input_frame = ttk.LabelFrame(page, text="添加商品", padding=10)
input_frame.pack(fill="x", padx=20, pady=5)
# 链接输入行
link_row = ttk.Frame(input_frame)
link_row.pack(fill="x", pady=5)
ttk.Label(link_row, text="商品链接:").pack(side="left")
self.product_link_var = tk.StringVar()
link_entry = ttk.Entry(link_row, textvariable=self.product_link_var, width=60)
link_entry.pack(side="left", padx=10, fill="x", expand=True)
ttk.Button(link_row, text="同步商品", command=self._sync_product, width=12).pack(side="left", padx=5)
# 同步状态
self.sync_status_var = tk.StringVar(value="")
ttk.Label(input_frame, textvariable=self.sync_status_var, foreground="gray").pack(anchor="w", pady=5)
# 商品列表区域
list_frame = ttk.LabelFrame(page, text="已同步商品", padding=10)
list_frame.pack(fill="both", expand=True, padx=20, pady=10)
# 抓取标题字符数设置
settings_row = ttk.Frame(list_frame)
settings_row.pack(fill="x", pady=(0, 8))
ttk.Label(settings_row, text="抓取标题字符数:").pack(side="left")
self.title_grab_length_var = tk.StringVar(value=str(self.title_grab_length))
title_length_entry = ttk.Entry(settings_row, textvariable=self.title_grab_length_var, width=5)
title_length_entry.pack(side="left", padx=5)
ttk.Label(settings_row, text="字符(0=不限制)").pack(side="left")
ttk.Button(settings_row, text="保存", command=self._confirm_title_length, width=6).pack(side="left", padx=10)
self.title_length_status = tk.StringVar(value="")
ttk.Label(settings_row, textvariable=self.title_length_status, foreground="green").pack(side="left")
# 商品表格
columns = ('item_id', 'title', 'price', 'updated_at', 'operation')
self.products_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=12)
self.products_tree.heading('item_id', text='商品ID')
self.products_tree.heading('title', text='商品标题')
self.products_tree.heading('price', text='价格')
self.products_tree.heading('updated_at', text='更新时间')
self.products_tree.heading('operation', text='操作')
self.products_tree.column('item_id', width=140, minwidth=120, anchor='center')
self.products_tree.column('title', width=240, minwidth=160, anchor='center')
self.products_tree.column('price', width=70, minwidth=50, anchor='center')
self.products_tree.column('updated_at', width=140, minwidth=110, anchor='center')
self.products_tree.column('operation', width=100, minwidth=80, anchor='center')
# 绑定点击事件处理操作列
self.products_tree.bind('<ButtonRelease-1>', self._on_products_tree_click)
scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.products_tree.yview)
self.products_tree.configure(yscrollcommand=scrollbar.set)
self.products_tree.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# 按钮区域
btn_frame = ttk.Frame(page)
btn_frame.pack(pady=10)
ttk.Button(btn_frame, text="刷新列表", command=self._refresh_products_list, width=12).pack(side="left", padx=5)
ttk.Button(btn_frame, text="清空列表", command=self._clear_products_list, width=12).pack(side="left", padx=5)
def _clear_products_list(self):
"""清空所有商品"""
from db_manager import db_manager
# 获取当前商品数量
products = db_manager.get_all_products()
if not products:
messagebox.showinfo("提示", "列表已为空")
return
if not messagebox.askyesno("确认", f"确定要删除所有 {len(products)} 个商品吗?"):
return
try:
db_manager._ensure_connection()
with db_manager.connection.cursor() as cursor:
cursor.execute("DELETE FROM products")
db_manager.connection.commit()
self._refresh_products_list()
messagebox.showinfo("成功", "已清空所有商品")
except Exception as e:
messagebox.showerror("错误", f"清空失败: {e}")
def _confirm_title_length(self):
"""确认抓取标题字符数设置并保存到配置文件"""
try:
val = int(self.title_grab_length_var.get())
if val < 0:
self.title_grab_length_var.set("15")
self.title_length_status.set("无效值,已重置为15")
val = 15
else:
self.title_length_status.set(f"已保存: {val} 字符" if val > 0 else "已保存: 不限制")
# 保存到配置文件
self.title_grab_length = val
self._save_title_grab_length()
except ValueError:
self.title_grab_length_var.set("15")
self.title_length_status.set("无效值,已重置为15")
def _save_title_grab_length(self):
"""保存抓取标题字符数到配置文件"""
try:
# 读取现有配置
data = {}
if self.vars_config_path.exists():
with open(self.vars_config_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 更新抓取标题字符数
data['title_grab_length'] = self.title_grab_length
# 保存配置
with open(self.vars_config_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"保存抓取标题字符数失败: {e}")
def _extract_item_id_from_url(self, url: str) -> str:
"""从URL中提取商品ID"""
import re
match = re.search(r'[?&]id=(\d+)', url)
if match:
return match.group(1)
return None
def _sync_product(self):
"""同步商品信息"""
url = self.product_link_var.get().strip()
if not url:
messagebox.showwarning("提示", "请输入商品链接")
return
# 提取商品ID
item_id = self._extract_item_id_from_url(url)
if not item_id:
messagebox.showerror("错误", "无法从链接中提取商品ID,请检查链接格式")
return
# 在主线程中获取抓取字数设置
try:
title_max_len = int(self.title_grab_length_var.get())
except (ValueError, AttributeError):
title_max_len = 15 # 默认15字
self.sync_status_var.set(f"正在同步商品 {item_id}...")
def do_sync(max_len):
try:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
context = p.chromium.launch_persistent_context(
user_data_dir=Config.USER_DATA_DIR,
headless=False,
)
page = context.pages[0] if context.pages else context.new_page()
page.goto(url, timeout=30000)
page.wait_for_load_state('networkidle', timeout=15000)
# 使用 JavaScript 提取商品信息
result = page.evaluate("""
() => {
let description = '';
let price = '';
// 直接定位闲鱼商品描述元素(可能有多个)
const descEls = document.querySelectorAll('[class*="ItemDesc--"], [class*="itemDesc"], [class*="goods-desc"]');
if (descEls.length > 0) {
const allTexts = [];
for (let i = 0; i < descEls.length; i++) {
const txt = (descEls[i].innerText || descEls[i].textContent || '').trim();
if (txt.length > 0) allTexts.push(txt);
}
// 合并所有文本,按换行分割再用空格连接
const combined = allTexts.join(String.fromCharCode(10));
const lines = combined.split(String.fromCharCode(10));
const cleaned = [];
for (let j = 0; j < lines.length; j++) {
const line = lines[j].replace(/^[ ]+|[ ]+$/g, '');
if (line.length > 0) cleaned.push(line);
}
description = cleaned.join(' ');
}
// 备选:从页面标题获取
if (!description) {
const title = document.title || '';
if (title.includes('_闲鱼')) {
description = title.replace(/_闲鱼.*$/, '').trim();
}
}
// 查找价格:闲鱼的 ¥ 和数字是分开的兄弟元素
const allElements = document.querySelectorAll('*');
for (const el of allElements) {
// 找到只包含 ¥ 的叶子节点
if (el.children.length === 0 && el.textContent.trim() === '¥') {
// 获取下一个兄弟元素的文本(应该是价格数字)
let next = el.nextElementSibling;
if (next && /^[\\d.]+$/.test(next.textContent.trim())) {
price = next.textContent.trim();
// 检查是否有小数部分在再下一个兄弟
let nextNext = next.nextElementSibling;
if (nextNext && /^\\.[\\d]+$/.test(nextNext.textContent.trim())) {
price += nextNext.textContent.trim();
}
break;
}
}
}
// 备选:用正则从整页文本匹配
if (!price) {
const bodyText = document.body.innerText;
const match = bodyText.match(/¥\\s*([\\d.]+)/);
if (match) price = match[1];
}
return { description, price };
}
""")
context.close()
title = result.get('description', '')
price = result.get('price', '')
# 根据设置截断标题(按字符数)
if max_len > 0 and len(title) > max_len:
title = title[:max_len]
if title:
self.root.after(0, lambda t=title, p=price: self._save_product(item_id, t, p))
else:
self.root.after(0, lambda: self._on_sync_error("无法抓取商品标题,请手动输入"))
except Exception as e:
err_msg = str(e)
self.root.after(0, lambda msg=err_msg: self._on_sync_error(msg))
threading.Thread(target=do_sync, args=(title_max_len,), daemon=True).start()
def _save_product(self, item_id: str, title: str, price: str = None):
"""保存商品到数据库"""
from db_manager import db_manager
if not db_manager.connection:
db_manager.connect()
# 确保表结构是最新的(会自动添加缺失的列)
db_manager.init_tables()
if db_manager.add_or_update_product(item_id, title, price):
price_str = f" ¥{price}" if price else ""
self.sync_status_var.set(f"同步成功: {title}{price_str}")
self.product_link_var.set("")
self._refresh_products_list()
self._log(f"商品同步成功: {item_id} - {title} - ¥{price}")
else:
self.sync_status_var.set("保存失败")
def _on_sync_error(self, error_msg: str):
"""同步失败处理"""
self.sync_status_var.set(f"同步失败: {error_msg}")
# 提供手动输入选项
item_id = self._extract_item_id_from_url(self.product_link_var.get())
if item_id:
if messagebox.askyesno("同步失败", f"自动抓取失败: {error_msg}\n\n是否手动输入商品标题?"):
self._show_manual_input_dialog(item_id)
def _show_manual_input_dialog(self, item_id: str):
"""显示手动输入对话框"""
dialog = tk.Toplevel(self.root)
dialog.title("手动输入商品信息")
dialog.geometry("400x180")
dialog.transient(self.root)
dialog.grab_set()
ttk.Label(dialog, text=f"商品ID: {item_id}").pack(pady=10)
row1 = ttk.Frame(dialog)
row1.pack(fill="x", padx=20, pady=5)
ttk.Label(row1, text="商品标题:", width=10).pack(side="left")
title_var = tk.StringVar()
title_entry = ttk.Entry(row1, textvariable=title_var, width=30)
title_entry.pack(side="left", padx=10)
title_entry.focus()
row2 = ttk.Frame(dialog)
row2.pack(fill="x", padx=20, pady=5)
ttk.Label(row2, text="商品价格:", width=10).pack(side="left")
price_var = tk.StringVar()
price_entry = ttk.Entry(row2, textvariable=price_var, width=15)
price_entry.pack(side="left", padx=10)
ttk.Label(row2, text="元").pack(side="left")
def save():
title = title_var.get().strip()
price = price_var.get().strip()
if title:
self._save_product(item_id, title, price if price else None)
dialog.destroy()
else:
messagebox.showwarning("提示", "请输入商品标题")
btn_frame = ttk.Frame(dialog)
btn_frame.pack(pady=15)
ttk.Button(btn_frame, text="保存", command=save).pack(side="left", padx=10)
ttk.Button(btn_frame, text="取消", command=dialog.destroy).pack(side="left", padx=10)
def _refresh_products_list(self):
"""刷新商品列表"""
from db_manager import db_manager
if not db_manager.connection:
db_manager.connect()
# 清空现有数据
for item in self.products_tree.get_children():
self.products_tree.delete(item)
# 加载商品
products = db_manager.get_all_products()
for p in products:
updated_at = str(p.get('updated_at', ''))[:19] if p.get('updated_at') else ''
price = p.get('price', '')
price_display = f"¥{price}" if price else ''
self.products_tree.insert('', 'end', values=(
p.get('item_id', ''),
p.get('title', ''),
price_display,
updated_at,
'编辑 | 删除'
))
def _on_products_tree_click(self, event):
"""处理商品列表点击事件"""
region = self.products_tree.identify_region(event.x, event.y)
if region != 'cell':
return
column = self.products_tree.identify_column(event.x)
# #5 是操作列(第5列)
if column != '#5':
return
item_id = self.products_tree.identify_row(event.y)
if not item_id:
return
item = self.products_tree.item(item_id)
product_item_id = item['values'][0]
product_title = item['values'][1]
# 获取点击位置,判断是编辑还是删除
bbox = self.products_tree.bbox(item_id, column)
if bbox:
cell_x = event.x - bbox[0]
cell_width = bbox[2]
# 左半边是编辑,右半边是删除
if cell_x < cell_width / 2:
self._edit_product(product_item_id)
else:
self._delete_product_by_id(product_item_id, product_title)
def _edit_product(self, item_id: str):
"""编辑商品对话框"""
from db_manager import db_manager
if not db_manager.connection:
db_manager.connect()
# 确保表结构是最新的
db_manager.init_tables()
# 获取商品现有信息
product = db_manager.get_product(item_id)
if not product:
messagebox.showerror("错误", "商品不存在")
return
dialog = tk.Toplevel(self.root)
dialog.title("编辑商品信息")
dialog.geometry("550x400")
dialog.transient(self.root)
dialog.grab_set()