-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrun_config_web.py
1927 lines (1696 loc) · 66.6 KB
/
run_config_web.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
"""
配置管理Web界面启动文件
提供Web配置界面功能,包括:
- 初始化Python路径
- 禁用字节码缓存
- 清理缓存文件
- 启动Web服务器
- 动态修改配置
"""
import os
import sys
import re
import logging
from flask import Flask, render_template, jsonify, request, send_from_directory, redirect, url_for, session
import importlib
import json
from colorama import init, Fore, Style
from werkzeug.utils import secure_filename
from typing import Dict, Any, List
import psutil
import subprocess
import threading
from src.autoupdate.updater import Updater
import requests
import time
from queue import Queue
import datetime
from logging.config import dictConfig
import shutil
import signal
import atexit
import socket
import webbrowser
import hashlib
import secrets
from datetime import timedelta
from src.utils.console import print_status
from src.avatar_manager import avatar_manager # 导入角色设定管理器
# 在文件开头添加全局变量声明
bot_process = None
bot_start_time = None
bot_logs = Queue(maxsize=1000)
# 配置日志
dictConfig({
'version': 1,
'formatters': {
'default': {
'format': '[%(asctime)s] %(levelname)s: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
'level': 'DEBUG'
}
},
'root': {
'level': 'DEBUG',
'handlers': ['console']
},
'loggers': {
'werkzeug': {
'level': 'ERROR', # 将 Werkzeug 的日志级别设置为 ERROR
'handlers': ['console'],
'propagate': False
}
}
})
# 初始化日志记录器
logger = logging.getLogger(__name__)
# 初始化colorama
init()
# 添加项目根目录到Python路径
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(ROOT_DIR)
# 禁用Python的字节码缓存
sys.dont_write_bytecode = True
app = Flask(__name__,
template_folder=os.path.join(ROOT_DIR, 'src/webui/templates'),
static_folder=os.path.join(ROOT_DIR, 'src/webui/static'))
# 添加配置
app.config['UPLOAD_FOLDER'] = os.path.join(ROOT_DIR, 'src/webui/background_image')
# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# 生成密钥用于session加密
app.secret_key = secrets.token_hex(16)
# 在 app 初始化后添加
app.register_blueprint(avatar_manager)
def get_available_avatars() -> List[str]:
"""获取可用的人设目录列表"""
avatar_base_dir = os.path.join(ROOT_DIR, "data/avatars")
if not os.path.exists(avatar_base_dir):
return []
# 获取所有包含 avatar.md 和 emojis 目录的有效人设目录
avatars = []
for item in os.listdir(avatar_base_dir):
avatar_dir = os.path.join(avatar_base_dir, item)
if os.path.isdir(avatar_dir):
if os.path.exists(os.path.join(avatar_dir, "avatar.md")) and \
os.path.exists(os.path.join(avatar_dir, "emojis")):
avatars.append(f"data/avatars/{item}")
return avatars
def parse_config_groups() -> Dict[str, Dict[str, Any]]:
"""解析配置文件,将配置项按组分类"""
from src.config import config
config_groups = {
"基础配置": {},
"图像识别API配置": {},
"图像生成配置": {},
"时间配置": {},
"语音配置": {},
"Prompt配置": {},
}
# 基础配置
config_groups["基础配置"].update(
{
"LISTEN_LIST": {
"value": config.user.listen_list,
"description": "用户列表(请配置要和bot说话的账号的昵称或者群名,不要写备注!)",
},
"DEEPSEEK_BASE_URL": {
"value": config.llm.base_url,
"description": "API注册地址",
},
"DEEPSEEK_API_KEY": {
"value": config.llm.api_key,
"description": "API密钥",
},
"DIFY_BASE_URL": {
"value": config.llm.dify_base_url,
"description": "DIFY注册地址",
},
"DIFY_API_KEY": {
"value": config.llm.dify_api_key,
"description": "DIFY API密钥",
},
# "MODEL": {"value": config.llm.model, "description": "AI模型选择"},
# "MAX_TOKEN": {
# "value": config.llm.max_tokens,
# "description": "回复最大token数",
# "type": "number",
# },
# "TEMPERATURE": {
# "value": float(config.llm.temperature), # 确保是浮点数
# "type": "number",
# "description": "温度参数",
# "min": 0.0,
# "max": 1.7,
# },
}
)
# 图像识别API配置
config_groups["图像识别API配置"].update(
{
"MOONSHOT_API_KEY": {
"value": config.media.image_recognition.api_key,
"description": "Moonshot API密钥(用于图片和表情包识别)\n API申请https://platform.moonshot.cn/console/api-keys (免费15元额度)",
},
"MOONSHOT_BASE_URL": {
"value": config.media.image_recognition.base_url,
"description": "Moonshot API基础URL",
},
"MOONSHOT_TEMPERATURE": {
"value": config.media.image_recognition.temperature,
"description": "Moonshot温度参数",
},
}
)
# 图像生成配置
config_groups["图像生成配置"].update(
{
"IMAGE_MODEL": {
"value": config.media.image_generation.model,
"description": "图像生成模型",
},
"TEMP_IMAGE_DIR": {
"value": config.media.image_generation.temp_dir,
"description": "临时图片目录",
},
}
)
# 时间配置
config_groups["时间配置"].update(
{
"AUTO_MESSAGE": {
"value": config.behavior.auto_message.content,
"description": "自动消息内容",
},
"MIN_COUNTDOWN_HOURS": {
"value": config.behavior.auto_message.min_hours,
"description": "最小倒计时时间(小时)",
},
"MAX_COUNTDOWN_HOURS": {
"value": config.behavior.auto_message.max_hours,
"description": "最大倒计时时间(小时)",
},
"QUIET_TIME_START": {
"value": config.behavior.quiet_time.start,
"description": "安静时间开始",
},
"QUIET_TIME_END": {
"value": config.behavior.quiet_time.end,
"description": "安静时间结束",
},
}
)
# 语音配置
config_groups["语音配置"].update(
{
"TTS_API_URL": {
"value": config.media.text_to_speech.tts_api_url,
"description": "语音服务API地址",
},
"VOICE_DIR": {
"value": config.media.text_to_speech.voice_dir,
"description": "语音文件目录",
},
}
)
# Prompt配置
available_avatars = get_available_avatars()
config_groups["Prompt配置"].update(
{
"MAX_GROUPS": {
"value": config.behavior.context.max_groups,
"description": "最大的上下文轮数",
},
"AVATAR_DIR": {
"value": config.behavior.context.avatar_dir,
"description": "人设目录(自动包含 avatar.md 和 emojis 目录)",
"options": available_avatars,
"type": "select"
}
}
)
return config_groups
def save_config(new_config: Dict[str, Any]) -> bool:
"""保存新的配置到文件"""
try:
from src.config import (
UserSettings,
LLMSettings,
ImageRecognitionSettings,
ImageGenerationSettings,
TextToSpeechSettings,
MediaSettings,
AutoMessageSettings,
QuietTimeSettings,
ContextSettings,
BehaviorSettings,
config
)
# 添加调试日志,查看接收到的所有参数
logger.debug("接收到的所有配置参数:")
for key, value in new_config.items():
logger.debug(f"{key}: {value} (类型: {type(value)})")
# 特别处理温度参数
# temperature = float(new_config.get("TEMPERATURE", 1.1))
# logger.debug(f"处理后的温度参数: {temperature} (类型: {type(temperature)})")
# 构建所有新的配置对象
llm_settings = LLMSettings(
api_key=new_config.get("DEEPSEEK_API_KEY", ""),
base_url=new_config.get("DEEPSEEK_BASE_URL", ""),
dify_api_key=new_config.get("DIFY_API_KEY",""),
dify_base_url=new_config.get("DIFY_BASE_URL",""),
# model=new_config.get("MODEL", ""),
# max_tokens=int(new_config.get("MAX_TOKEN", 2000)),
# temperature=temperature # 使用处理后的温度值
)
media_settings = MediaSettings(
image_recognition=ImageRecognitionSettings(
api_key=new_config.get("MOONSHOT_API_KEY", ""),
base_url=new_config.get("MOONSHOT_BASE_URL", ""),
temperature=float(new_config.get("MOONSHOT_TEMPERATURE", 1.1)),
),
image_generation=ImageGenerationSettings(
model=new_config.get("IMAGE_MODEL", ""),
temp_dir=new_config.get("TEMP_IMAGE_DIR", ""),
),
text_to_speech=TextToSpeechSettings(
tts_api_url=new_config.get("TTS_API_URL", ""),
voice_dir=new_config.get("VOICE_DIR", ""),
)
)
behavior_settings = BehaviorSettings(
auto_message=AutoMessageSettings(
content=new_config.get("AUTO_MESSAGE", ""),
min_hours=float(new_config.get("MIN_COUNTDOWN_HOURS", 1)),
max_hours=float(new_config.get("MAX_COUNTDOWN_HOURS", 3)),
),
quiet_time=QuietTimeSettings(
start=new_config.get("QUIET_TIME_START", ""),
end=new_config.get("QUIET_TIME_END", ""),
),
context=ContextSettings(
max_groups=int(new_config.get("MAX_GROUPS", 15)),
avatar_dir=new_config.get("AVATAR_DIR", ""),
),
)
# 构建JSON结构
config_data = {
"categories": {
"user_settings": {
"title": "用户设置",
"settings": {
"listen_list": {
"value": UserSettings(listen_list=new_config.get("LISTEN_LIST", [])).listen_list,
"type": "array",
"description": "要监听的用户列表(请使用微信昵称,不要使用备注名)",
}
},
},
"llm_settings": {
"title": "大语言模型配置",
"settings": {
"api_key": {
"value": llm_settings.api_key,
"type": "string",
"description": "API密钥",
"is_secret": True,
},
"base_url": {
"value": llm_settings.base_url,
"type": "string",
"description": "DeepSeek API基础URL",
},
"dify_api_key": {
"value": llm_settings.dify_api_key,
"type": "string",
"description": "DIFY API密钥",
"is_secret": True,
},
"dify_base_url": {
"value": llm_settings.dify_base_url,
"type": "string",
"description": "DIFY API基础URL",
}
# "model": {
# "value": llm_settings.model,
# "type": "string",
# "description": "使用的AI模型名称",
# "options": [
# "deepseek-ai/DeepSeek-V3",
# "Pro/deepseek-ai/DeepSeek-V3",
# "Pro/deepseek-ai/DeepSeek-R1",
# ],
# },
# "max_tokens": {
# "value": llm_settings.max_tokens,
# "type": "number",
# "description": "回复最大token数量",
# },
# "temperature": {
# "value": temperature,
# "type": "number",
# "description": "AI回复的温度值",
# "min": 0.0,
# "max": 1.7
# },
},
},
"media_settings": {
"title": "媒体设置",
"settings": {
"image_recognition": {
"api_key": {
"value": media_settings.image_recognition.api_key,
"type": "string",
"description": "Moonshot AI API密钥(用于图片和表情包识别)",
"is_secret": True,
},
"base_url": {
"value": media_settings.image_recognition.base_url,
"type": "string",
"description": "Moonshot API基础URL",
},
"temperature": {
"value": media_settings.image_recognition.temperature,
"type": "number",
"description": "Moonshot AI的温度值",
"min": 0,
"max": 2,
},
},
"image_generation": {
"model": {
"value": media_settings.image_generation.model,
"type": "string",
"description": "图像生成模型",
},
"temp_dir": {
"value": media_settings.image_generation.temp_dir,
"type": "string",
"description": "临时图片存储目录",
},
},
"text_to_speech": {
"tts_api_url": {
"value": media_settings.text_to_speech.tts_api_url,
"type": "string",
"description": "TTS服务API地址",
},
"voice_dir": {
"value": media_settings.text_to_speech.voice_dir,
"type": "string",
"description": "语音文件存储目录",
},
}
},
},
"behavior_settings": {
"title": "行为设置",
"settings": {
"auto_message": {
"content": {
"value": behavior_settings.auto_message.content,
"type": "string",
"description": "自动消息内容",
},
"countdown": {
"min_hours": {
"value": behavior_settings.auto_message.min_hours,
"type": "number",
"description": "最小倒计时时间(小时)",
},
"max_hours": {
"value": behavior_settings.auto_message.max_hours,
"type": "number",
"description": "最大倒计时时间(小时)",
},
},
},
"quiet_time": {
"start": {
"value": behavior_settings.quiet_time.start,
"type": "string",
"description": "安静时间开始",
},
"end": {
"value": behavior_settings.quiet_time.end,
"type": "string",
"description": "安静时间结束",
},
},
"context": {
"max_groups": {
"value": behavior_settings.context.max_groups,
"type": "number",
"description": "最大上下文轮数",
},
"avatar_dir": {
"value": behavior_settings.context.avatar_dir,
"type": "string",
"description": "人设目录(自动包含 avatar.md 和 emojis 目录)",
},
},
},
},
}
}
# # 在保存前记录最终的温度配置
# final_temp = config_data["categories"]["llm_settings"]["settings"]["temperature"]["value"]
# logger.debug(f"最终保存到JSON的温度值: {final_temp} (类型: {type(final_temp)})")
# 使用 Config 类的方法保存配置
if not config.save_config(config_data):
logger.error("保存配置失败")
return False
# 重新加载配置模块
importlib.reload(sys.modules["src.config"])
logger.debug("配置已成功保存和重新加载")
return True
except Exception as e:
logger.error(f"保存配置失败: {str(e)}")
return False
@app.route('/')
def index():
"""重定向到控制台"""
return redirect(url_for('dashboard'))
@app.route('/save', methods=['POST'])
def save():
"""保存配置"""
try:
new_config = request.json
logger.debug(f"接收到的配置数据: {new_config}")
if save_config(new_config):
return jsonify({
"status": "success",
"message": "✨ 配置已成功保存并生效",
"title": "保存成功" # 添加标题字段
})
return jsonify({
"status": "error",
"message": "保存失败,请重试",
"title": "保存失败"
})
except Exception as e:
logger.error(f"保存失败: {str(e)}")
return jsonify({
"status": "error",
"message": f"保存失败: {str(e)}",
"title": "错误"
})
# 添加上传处理路由
@app.route('/upload_background', methods=['POST'])
def upload_background():
if 'background' not in request.files:
return jsonify({"status": "error", "message": "没有选择文件"})
file = request.files['background']
if file.filename == '':
return jsonify({"status": "error", "message": "没有选择文件"})
if file:
filename = secure_filename(file.filename)
# 清理旧的背景图片
for old_file in os.listdir(app.config['UPLOAD_FOLDER']):
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], old_file))
# 保存新图片
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify({
"status": "success",
"message": "背景图片已更新",
"path": f"/background_image/{filename}"
})
# 添加背景图片目录的路由
@app.route('/background_image/<filename>')
def background_image(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
# 添加获取背景图片路由
@app.route('/get_background')
def get_background():
"""获取当前背景图片"""
try:
# 获取背景图片目录中的第一个文件
files = os.listdir(app.config['UPLOAD_FOLDER'])
if files:
# 返回找到的第一个图片
return jsonify({
"status": "success",
"path": f"/background_image/{files[0]}"
})
return jsonify({
"status": "success",
"path": None
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
})
# 添加新的路由
@app.route('/dashboard')
def dashboard():
"""仪表盘页面"""
if not session.get('logged_in'):
return redirect(url_for('login'))
return render_template(
'dashboard.html',
is_local=is_local_network(),
active_page='dashboard'
)
@app.route('/system_info')
def system_info():
"""获取系统信息"""
try:
# 创建静态变量存储上次的值
if not hasattr(system_info, 'last_bytes'):
system_info.last_bytes = {
'sent': 0,
'recv': 0,
'time': time.time()
}
cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
net = psutil.net_io_counters()
# 计算网络速度
current_time = time.time()
time_delta = current_time - system_info.last_bytes['time']
# 计算每秒的字节数
upload_speed = (net.bytes_sent - system_info.last_bytes['sent']) / time_delta
download_speed = (net.bytes_recv - system_info.last_bytes['recv']) / time_delta
# 更新上次的值
system_info.last_bytes = {
'sent': net.bytes_sent,
'recv': net.bytes_recv,
'time': current_time
}
# 转换为 KB/s
upload_speed = upload_speed / 1024
download_speed = download_speed / 1024
return jsonify({
'cpu': cpu_percent,
'memory': {
'total': round(memory.total / (1024**3), 2),
'used': round(memory.used / (1024**3), 2),
'percent': memory.percent
},
'disk': {
'total': round(disk.total / (1024**3), 2),
'used': round(disk.used / (1024**3), 2),
'percent': disk.percent
},
'network': {
'upload': round(upload_speed, 2),
'download': round(download_speed, 2)
}
})
except Exception as e:
logger.error(f"获取系统信息失败: {str(e)}")
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/check_update')
def check_update():
"""检查更新"""
try:
updater = Updater()
result = updater.check_for_updates()
return jsonify({
'status': 'success',
'has_update': result.get('has_update', False),
'console_output': result['output'],
'update_info': result if result.get('has_update') else None,
'wait_input': result.get('has_update', False)
})
except Exception as e:
return jsonify({
'status': 'error',
'has_update': False,
'console_output': f'检查更新失败: {str(e)}'
})
@app.route('/confirm_update', methods=['POST'])
def confirm_update():
"""确认是否更新"""
try:
choice = request.json.get('choice', '').lower()
if choice in ('y', 'yes'):
updater = Updater()
result = updater.update()
return jsonify({
'status': 'success' if result['success'] else 'error',
'console_output': result['output']
})
else:
return jsonify({
'status': 'success',
'console_output': '用户取消更新'
})
except Exception as e:
return jsonify({
'status': 'error',
'console_output': f'更新失败: {str(e)}'
})
@app.route('/start_bot')
def start_bot():
"""启动机器人"""
global bot_process, bot_start_time
try:
if bot_process and bot_process.poll() is None:
return jsonify({
'status': 'error',
'message': '机器人已在运行中'
})
# 清空之前的日志
while not bot_logs.empty():
bot_logs.get()
# 设置环境变量
env = os.environ.copy()
env['PYTHONIOENCODING'] = 'utf-8'
# 创建新的进程组
if sys.platform.startswith('win'):
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
creationflags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
else:
creationflags = 0
# 启动进程
bot_process = subprocess.Popen(
[sys.executable, 'run.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1,
env=env,
encoding='utf-8',
errors='replace',
creationflags=creationflags if sys.platform.startswith('win') else 0,
preexec_fn=os.setsid if not sys.platform.startswith('win') else None
)
# 记录启动时间
bot_start_time = datetime.datetime.now()
# 启动日志读取线程
def read_output():
try:
while bot_process and bot_process.poll() is None:
line = bot_process.stdout.readline()
if line:
try:
# 尝试解码并清理日志内容
line = line.strip()
if isinstance(line, bytes):
line = line.decode('utf-8', errors='replace')
timestamp = datetime.datetime.now().strftime('%H:%M:%S')
bot_logs.put(f"[{timestamp}] {line}")
except Exception as e:
logger.error(f"日志处理错误: {str(e)}")
continue
except Exception as e:
logger.error(f"读取日志失败: {str(e)}")
bot_logs.put(f"[ERROR] 读取日志失败: {str(e)}")
thread = threading.Thread(target=read_output, daemon=True)
thread.start()
return jsonify({
'status': 'success',
'message': '机器人启动成功'
})
except Exception as e:
logger.error(f"启动机器人失败: {str(e)}")
return jsonify({
'status': 'error',
'message': str(e)
})
@app.route('/get_bot_logs')
def get_bot_logs():
"""获取机器人日志"""
logs = []
while not bot_logs.empty():
logs.append(bot_logs.get())
# 获取运行时间
uptime = '0分钟'
if bot_start_time and bot_process and bot_process.poll() is None:
delta = datetime.datetime.now() - bot_start_time
total_seconds = int(delta.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
if hours > 0:
uptime = f"{hours}小时{minutes}分钟{seconds}秒"
elif minutes > 0:
uptime = f"{minutes}分钟{seconds}秒"
else:
uptime = f"{seconds}秒"
return jsonify({
'status': 'success',
'logs': logs,
'uptime': uptime,
'is_running': bot_process is not None and bot_process.poll() is None
})
@app.route('/stop_bot')
def stop_bot():
"""停止机器人"""
global bot_process
try:
if bot_process:
# 首先尝试正常终止进程
bot_process.terminate()
# 等待进程结束
try:
bot_process.wait(timeout=5) # 等待最多5秒
except subprocess.TimeoutExpired:
# 如果超时,强制结束进程
bot_process.kill()
bot_process.wait()
# 确保所有子进程都被终止
if sys.platform.startswith('win'):
subprocess.run(['taskkill', '/F', '/T', '/PID', str(bot_process.pid)],
capture_output=True)
else:
import signal
os.killpg(os.getpgid(bot_process.pid), signal.SIGTERM)
# 清理进程对象
bot_process = None
# 添加日志记录
timestamp = datetime.datetime.now().strftime('%H:%M:%S')
bot_logs.put(f"[{timestamp}] 正在关闭监听线程...")
bot_logs.put(f"[{timestamp}] 正在关闭系统...")
bot_logs.put(f"[{timestamp}] 系统已退出")
return jsonify({
'status': 'success',
'message': '机器人已停止'
})
return jsonify({
'status': 'error',
'message': '机器人未在运行'
})
except Exception as e:
logger.error(f"停止机器人失败: {str(e)}")
return jsonify({
'status': 'error',
'message': str(e)
})
@app.route('/config')
def config():
"""配置页面"""
if not session.get('logged_in'):
return redirect(url_for('login'))
config_groups = parse_config_groups() # 获取配置组
return render_template(
'config.html',
config_groups=config_groups, # 传递配置组
is_local=is_local_network(), # 传递本地网络状态
active_page='config' # 传递当前页面标识
)
# 添加获取用户信息的路由
@app.route('/user_info')
def get_user_info():
"""获取用户账户信息"""
try:
from src.config import config
api_key = config.llm.api_key
base_url = config.llm.base_url.rstrip('/')
# 确保使用正确的API端点
if 'siliconflow.cn' in base_url:
api_url = f"{base_url}/user/info"
else:
return jsonify({
'status': 'error',
'message': '当前API不支持查询用户信息'
})
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
response = requests.get(api_url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
if data.get('status') is True and data.get('data'): # 修改判断条件
user_data = data['data']
return jsonify({
'status': 'success',
'data': {
'balance': user_data.get('balance', '0'),
'total_balance': user_data.get('totalBalance', '0'),
'charge_balance': user_data.get('chargeBalance', '0'),
'name': user_data.get('name', 'Unknown'),
'email': user_data.get('email', 'Unknown'),
'status': user_data.get('status', 'Unknown')
}
})
return jsonify({
'status': 'error',
'message': f"API返回错误: {response.text}"
})
except Exception as e:
return jsonify({
'status': 'error',
'message': f"获取用户信息失败: {str(e)}"
})
# 在 app 初始化后添加
@app.route('/static/<path:filename>')
def serve_static(filename):
"""提供静态文件服务"""
return send_from_directory(app.static_folder, filename)
@app.route('/execute_command', methods=['POST'])
def execute_command():
"""执行控制台命令"""
try:
command = request.json.get('command', '').strip()
global bot_process, bot_start_time
# 处理内置命令
if command.lower() == 'help':
return jsonify({
'status': 'success',
'output': '''可用命令:
help - 显示帮助信息
clear - 清空日志
status - 显示系统状态
version - 显示版本信息
memory - 显示内存使用情况
start - 启动机器人
stop - 停止机器人
restart - 重启机器人
支持所有CMD命令,例如:
dir - 显示目录内容
cd - 切换目录
echo - 显示消息
type - 显示文件内容
等...'''
})
elif command.lower() == 'clear':
# 清空日志队列
while not bot_logs.empty():
bot_logs.get()
return jsonify({
'status': 'success',
'output': '', # 返回空输出,让前端清空日志
'clear': True # 添加标记,告诉前端需要清空日志
})
elif command.lower() == 'status':
if bot_process and bot_process.poll() is None:
uptime = '0分钟'
if bot_start_time:
delta = datetime.datetime.now() - bot_start_time
total_seconds = int(delta.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
if hours > 0:
uptime = f"{hours}小时{minutes}分钟{seconds}秒"
elif minutes > 0:
uptime = f"{minutes}分钟{seconds}秒"
else:
uptime = f"{seconds}秒"
return jsonify({
'status': 'success',
'output': f'机器人状态: 运行中\n运行时间: {uptime}'
})