Skip to content

Commit fdc098d

Browse files
BBleaeClaude
and
Claude
committed
优化代码格式和异常处理
- 修复异常处理链,使用from语法保留原始异常 - 格式化代码以符合项目规范 - 优化导入模块的顺序 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent a829dfd commit fdc098d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+3157
-2779
lines changed

bot.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ def dev():
101101
RuntimeError(f"ENVIRONMENT 配置错误,请检查 .env 文件中的 ENVIRONMENT 变量及对应 .env.{env} 是否存在")
102102

103103

104-
105104
def scan_provider(env_config: dict):
106105
provider = {}
107106

@@ -164,12 +163,13 @@ async def uvicorn_main():
164163
uvicorn_server = server
165164
await server.serve()
166165

166+
167167
def check_eula():
168168
eula_confirm_file = Path("eula.confirmed")
169169
privacy_confirm_file = Path("privacy.confirmed")
170170
eula_file = Path("EULA.md")
171171
privacy_file = Path("PRIVACY.md")
172-
172+
173173
eula_updated = True
174174
eula_new_hash = None
175175
privacy_updated = True
@@ -218,35 +218,36 @@ def check_eula():
218218
print('输入"同意"或"confirmed"继续运行')
219219
while True:
220220
user_input = input().strip().lower()
221-
if user_input in ['同意', 'confirmed']:
221+
if user_input in ["同意", "confirmed"]:
222222
# print("确认成功,继续运行")
223223
# print(f"确认成功,继续运行{eula_updated} {privacy_updated}")
224224
if eula_updated:
225225
print(f"更新EULA确认文件{eula_new_hash}")
226-
eula_confirm_file.write_text(eula_new_hash,encoding="utf-8")
226+
eula_confirm_file.write_text(eula_new_hash, encoding="utf-8")
227227
if privacy_updated:
228228
print(f"更新隐私条款确认文件{privacy_new_hash}")
229-
privacy_confirm_file.write_text(privacy_new_hash,encoding="utf-8")
229+
privacy_confirm_file.write_text(privacy_new_hash, encoding="utf-8")
230230
break
231231
else:
232232
print('请输入"同意"或"confirmed"以继续运行')
233233
return
234234
elif eula_confirmed and privacy_confirmed:
235235
return
236236

237+
237238
def raw_main():
238239
# 利用 TZ 环境变量设定程序工作的时区
239240
# 仅保证行为一致,不依赖 localtime(),实际对生产环境几乎没有作用
240241
if platform.system().lower() != "windows":
241242
time.tzset()
242-
243+
243244
check_eula()
244245
print("检查EULA和隐私条款完成")
245246
easter_egg()
246247
init_config()
247248
init_env()
248249
load_env()
249-
250+
250251
# load_logger()
251252

252253
env_config = {key: os.getenv(key) for key in os.environ}
@@ -278,15 +279,15 @@ def raw_main():
278279
app = nonebot.get_asgi()
279280
loop = asyncio.new_event_loop()
280281
asyncio.set_event_loop(loop)
281-
282+
282283
try:
283284
loop.run_until_complete(uvicorn_main())
284285
except KeyboardInterrupt:
285286
logger.warning("收到中断信号,正在优雅关闭...")
286287
loop.run_until_complete(graceful_shutdown())
287288
finally:
288289
loop.close()
289-
290+
290291
except Exception as e:
291292
logger.error(f"主程序异常: {str(e)}")
292293
if loop and not loop.is_closed():

config/auto_update.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,35 @@
33
import tomlkit
44
from pathlib import Path
55

6+
67
def update_config():
78
# 获取根目录路径
89
root_dir = Path(__file__).parent.parent
910
template_dir = root_dir / "template"
1011
config_dir = root_dir / "config"
11-
12+
1213
# 定义文件路径
1314
template_path = template_dir / "bot_config_template.toml"
1415
old_config_path = config_dir / "bot_config.toml"
1516
new_config_path = config_dir / "bot_config.toml"
16-
17+
1718
# 读取旧配置文件
1819
old_config = {}
1920
if old_config_path.exists():
2021
with open(old_config_path, "r", encoding="utf-8") as f:
2122
old_config = tomlkit.load(f)
22-
23+
2324
# 删除旧的配置文件
2425
if old_config_path.exists():
2526
os.remove(old_config_path)
26-
27+
2728
# 复制模板文件到配置目录
2829
shutil.copy2(template_path, new_config_path)
29-
30+
3031
# 读取新配置文件
3132
with open(new_config_path, "r", encoding="utf-8") as f:
3233
new_config = tomlkit.load(f)
33-
34+
3435
# 递归更新配置
3536
def update_dict(target, source):
3637
for key, value in source.items():
@@ -55,13 +56,14 @@ def update_dict(target, source):
5556
except (TypeError, ValueError):
5657
# 如果转换失败,直接赋值
5758
target[key] = value
58-
59+
5960
# 将旧配置的值更新到新配置中
6061
update_dict(new_config, old_config)
61-
62+
6263
# 保存更新后的配置(保留注释和格式)
6364
with open(new_config_path, "w", encoding="utf-8") as f:
6465
f.write(tomlkit.dumps(new_config))
6566

67+
6668
if __name__ == "__main__":
6769
update_config()

run.py

+15-22
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,7 @@ def run_maimbot():
5454
run_cmd(r"napcat\NapCatWinBootMain.exe 10001", False)
5555
if not os.path.exists(r"mongodb\db"):
5656
os.makedirs(r"mongodb\db")
57-
run_cmd(
58-
r"mongodb\bin\mongod.exe --dbpath=" + os.getcwd() + r"\mongodb\db --port 27017"
59-
)
57+
run_cmd(r"mongodb\bin\mongod.exe --dbpath=" + os.getcwd() + r"\mongodb\db --port 27017")
6058
run_cmd("nb run")
6159

6260

@@ -70,30 +68,29 @@ def install_mongodb():
7068
stream=True,
7169
)
7270
total = int(resp.headers.get("content-length", 0)) # 计算文件大小
73-
with open("mongodb.zip", "w+b") as file, tqdm( # 展示下载进度条,并解压文件
74-
desc="mongodb.zip",
75-
total=total,
76-
unit="iB",
77-
unit_scale=True,
78-
unit_divisor=1024,
79-
) as bar:
71+
with (
72+
open("mongodb.zip", "w+b") as file,
73+
tqdm( # 展示下载进度条,并解压文件
74+
desc="mongodb.zip",
75+
total=total,
76+
unit="iB",
77+
unit_scale=True,
78+
unit_divisor=1024,
79+
) as bar,
80+
):
8081
for data in resp.iter_content(chunk_size=1024):
8182
size = file.write(data)
8283
bar.update(size)
8384
extract_files("mongodb.zip", "mongodb")
8485
print("MongoDB 下载完成")
8586
os.remove("mongodb.zip")
86-
choice = input(
87-
"是否安装 MongoDB Compass?此软件可以以可视化的方式修改数据库,建议安装(Y/n)"
88-
).upper()
87+
choice = input("是否安装 MongoDB Compass?此软件可以以可视化的方式修改数据库,建议安装(Y/n)").upper()
8988
if choice == "Y" or choice == "":
9089
install_mongodb_compass()
9190

9291

9392
def install_mongodb_compass():
94-
run_cmd(
95-
r"powershell Start-Process powershell -Verb runAs 'Set-ExecutionPolicy RemoteSigned'"
96-
)
93+
run_cmd(r"powershell Start-Process powershell -Verb runAs 'Set-ExecutionPolicy RemoteSigned'")
9794
input("请在弹出的用户账户控制中点击“是”后按任意键继续安装")
9895
run_cmd(r"powershell mongodb\bin\Install-Compass.ps1")
9996
input("按任意键启动麦麦")
@@ -107,7 +104,7 @@ def install_napcat():
107104
napcat_filename = input(
108105
"下载完成后请把文件复制到此文件夹,并将**不包含后缀的文件名**输入至此窗口,如 NapCat.32793.Shell:"
109106
)
110-
if(napcat_filename[-4:] == ".zip"):
107+
if napcat_filename[-4:] == ".zip":
111108
napcat_filename = napcat_filename[:-4]
112109
extract_files(napcat_filename + ".zip", "napcat")
113110
print("NapCat 安装完成")
@@ -121,11 +118,7 @@ def install_napcat():
121118
print("按任意键退出")
122119
input()
123120
exit(1)
124-
choice = input(
125-
"请输入要进行的操作:\n"
126-
"1.首次安装\n"
127-
"2.运行麦麦\n"
128-
)
121+
choice = input("请输入要进行的操作:\n1.首次安装\n2.运行麦麦\n")
129122
os.system("cls")
130123
if choice == "1":
131124
confirm = input("首次安装将下载并配置所需组件\n1.确认\n2.取消\n")

setup.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
version="0.1",
66
packages=find_packages(),
77
install_requires=[
8-
'python-dotenv',
9-
'pymongo',
8+
"python-dotenv",
9+
"pymongo",
1010
],
11-
)
11+
)

src/common/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# 这个文件可以为空,但必须存在
1+
# 这个文件可以为空,但必须存在

src/common/database.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import os
2-
from typing import cast
32
from pymongo import MongoClient
43
from pymongo.database import Database
54

@@ -11,7 +10,7 @@ def __create_database_instance():
1110
uri = os.getenv("MONGODB_URI")
1211
host = os.getenv("MONGODB_HOST", "127.0.0.1")
1312
port = int(os.getenv("MONGODB_PORT", "27017"))
14-
db_name = os.getenv("DATABASE_NAME", "MegBot")
13+
# db_name 变量在创建连接时不需要,在获取数据库实例时才使用
1514
username = os.getenv("MONGODB_USERNAME")
1615
password = os.getenv("MONGODB_PASSWORD")
1716
auth_source = os.getenv("MONGODB_AUTH_SOURCE")

0 commit comments

Comments
 (0)