Skip to content

Commit 5caaa4c

Browse files
committed
⚡️ 优化脚本执行逻辑 & 修复信号文件未删除
1 parent 32fe92c commit 5caaa4c

File tree

2 files changed

+93
-29
lines changed

2 files changed

+93
-29
lines changed

src/nonebot_plugin_sky/tools/restart.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,5 @@ async def trigger_signal(bot: Bot):
144144
await bot.send_private_msg(user_id=signal.user_id, message=signal.message)
145145
elif signal.action == Action.SEND_GROUP_MSG:
146146
await bot.send_group_msg(group_id=signal.group_id, message=signal.message)
147+
# 触发后删除
148+
SIGNAL_PATH.unlink()

src/sky_cli/cli.py

Lines changed: 91 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,44 +6,82 @@
66
import click
77

88
POWERSHELL_SCRIPT_CONTENT = r"""
9-
# =======================================================
10-
# == NoneBot Guardian & Restarter for Windows ==
11-
# == (Generated by nonebot-plugin-sky) ==
12-
# =======================================================
9+
# ===================================================================
10+
# == Robust NoneBot Guardian & Restarter for Windows (v2.0) ==
11+
# == - Auto-detects virtual environments. ==
12+
# == - Falls back to system-level commands. ==
13+
# ===================================================================
1314
1415
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
1516
Set-Location -Path $ScriptRoot
1617
17-
$VenvPythonPath = Join-Path $ScriptRoot ".venv\Scripts\python.exe"
18+
# 在当前目录下查找一个有效的 Python 虚拟环境
19+
# 如果找到,返回 python.exe 的完整路径,否则返回 $null。
20+
function Find-LocalPython {
21+
$subdirectories = Get-ChildItem -Path $ScriptRoot -Directory
22+
23+
foreach ($dir in $subdirectories) {
24+
$potentialPath = Join-Path -Path $dir.FullName -ChildPath "Scripts\python.exe"
25+
if (Test-Path -Path $potentialPath -PathType Leaf) {
26+
return $potentialPath
27+
}
28+
}
29+
30+
return $null
31+
}
32+
33+
$CommandToRun = $null
34+
$CommandArgs = $null
35+
36+
$localPythonPath = Find-LocalPython
37+
38+
if ($localPythonPath) {
39+
Write-Host "√ Automatically detected Python virtual environment at '$localPythonPath'" -ForegroundColor Green
40+
$CommandToRun = $localPythonPath
41+
$CommandArgs = "-m", "nb_cli", "run"
42+
}
1843
19-
if (-not (Test-Path $VenvPythonPath)) {
20-
Write-Host "Error: Python virtual environment not found at '$VenvPythonPath'" -ForegroundColor Red
44+
elseif (Get-Command "nb.exe" -ErrorAction SilentlyContinue) {
45+
Write-Host "No local virtual environment found. Falling back to system-level 'nb.exe' command." -ForegroundColor Cyan
46+
$CommandToRun = "nb.exe"
47+
$CommandArgs = "run"
48+
}
49+
else {
50+
Write-Host "× Error: Could not find a local virtual environment (e.g., '.\.venv\Scripts\python.exe') or a system-level 'nb.exe' command in your PATH." -ForegroundColor Red
51+
Write-Host "Please ensure NoneBot is installed correctly either in a local venv or globally." -ForegroundColor Red
2152
Read-Host "Press Enter to exit"
2253
exit 1
2354
}
2455
56+
# 进程守护循环
2557
while ($true) {
2658
Write-Host ""
27-
Write-Host "($(Get-Date -Format 'HH:mm:ss')) Starting NoneBot process..."
28-
29-
$process = Start-Process -FilePath $VenvPythonPath -ArgumentList "-m", "nb_cli", "run" -NoNewWindow -Wait -PassThru
30-
31-
$ExitCode = $process.ExitCode
59+
Write-Host "($(Get-Date -Format 'HH:mm:ss')) Starting NoneBot process..." -ForegroundColor White
60+
61+
try {
62+
$process = Start-Process -FilePath $CommandToRun -ArgumentList $CommandArgs -NoNewWindow -Wait -PassThru
63+
$ExitCode = $process.ExitCode
64+
} catch {
65+
Write-Host "Failed to start process with command: '$CommandToRun'" -ForegroundColor Red
66+
Write-Host $_.Exception.Message -ForegroundColor Red
67+
$ExitCode = -1
68+
}
3269
33-
# 当且仅当退出码为 0 时重启
34-
if ($ExitCode -eq 0) {
70+
if ($ExitCode -eq -1073741510) {
3571
Write-Host ""
36-
Write-Host "($(Get-Date -Format 'HH:mm:ss')) Process exited with code 0. Assuming restart request. Rebooting in 5 seconds..." -ForegroundColor Yellow
37-
Start-Sleep -Seconds 5
72+
Write-Host "($(Get-Date -Format 'HH:mm:ss')) Process was interrupted by user (Ctrl+C). Not restarting." -ForegroundColor Green
73+
break
3874
} else {
75+
# 退出码为 0 或其他错误码都进行重启
3976
Write-Host ""
40-
Write-Host "($(Get-Date -Format 'HH:mm:ss')) NoneBot process was interrupted (code $ExitCode). Not restarting." -ForegroundColor Green
41-
break
77+
Write-Host "($(Get-Date -Format 'HH:mm:ss')) Process exited with code ($ExitCode). Restarting in 5 seconds..." -ForegroundColor Yellow
78+
Start-Sleep -Seconds 5
4279
}
4380
}
4481
4582
Write-Host ""
46-
Read-Host "Script has finished. Press Enter to exit."
83+
Write-Host "Script has finished." -ForegroundColor Green
84+
Read-Host "Press Enter to exit."
4785
"""
4886

4987
BASH_SCRIPT_CONTENT = r"""
@@ -54,32 +92,56 @@
5492
# == (Generated by nonebot-plugin-sky) ==
5593
# =======================================================
5694
57-
cd "$(dirname "$0")"
95+
cd "$(dirname "$0")" || exit
96+
97+
# 在当前目录下查找一个有效的 Python 虚拟环境
98+
# 如果找到,打印出 python 可执行文件的路径并返回 0;否则返回 1。
99+
find_local_python() {
100+
for dir in */ .*/ ; do
101+
if [ -d "$dir" ] && [ "$dir" != "./" ] && [ "$dir" != "../" ]; then
102+
local potential_python="$dir/bin/python"
103+
if [ -f "$potential_python" ]; then
104+
echo "$potential_python"
105+
return 0
106+
fi
107+
fi
108+
done
109+
return 1
110+
}
111+
112+
RUN_CMD=""
58113
59-
VENV_PYTHON="./.venv/bin/python"
114+
VENV_PYTHON=$(find_local_python)
60115
61-
if [ ! -f "$VENV_PYTHON" ]; then
62-
echo "Error: Python virtual environment not found at '$VENV_PYTHON'" >&2
116+
if [ $? -eq 0 ]; then
117+
echo "✅ Automatically detected Python virtual environment at './${VENV_PYTHON#./}'"
118+
RUN_CMD=("$VENV_PYTHON" -m nb_cli run)
119+
# 如果虚拟环境不存在,则检测全局的 'nb' 命令
120+
elif command -v nb >/dev/null 2>&1; then
121+
echo "ℹ️ No local virtual environment found. Falling back to system-level 'nb' command."
122+
RUN_CMD=(nb run)
123+
else
124+
echo "❌ Error: Could not find a local virtual environment (e.g., ./.venv/bin/python) or a system-level 'nb' command in your PATH." >&2
125+
echo "Please ensure NoneBot is installed correctly either in a local venv or globally." >&2
63126
exit 1
64127
fi
65128
129+
# 进程守护循环
66130
while true; do
67131
echo ""
68-
echo "[$(date +'%H:%M:%S')] Starting NoneBot process..."
132+
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Starting NoneBot process..."
69133
70-
"$VENV_PYTHON" -m nb_cli run
134+
"${RUN_CMD[@]}"
71135
72136
EXIT_CODE=$?
73137
74-
# 退出码为 130 (SIGINT) 时不重启
75138
if [ $EXIT_CODE -eq 130 ]; then
76139
echo ""
77-
echo "[$(date +'%H:%M:%S')] Process was interrupted by user (SIGINT / Ctrl+C). Not restarting."
140+
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Process was interrupted by user (Ctrl+C). Not restarting."
78141
break
79142
else
80-
# 退出码为 0 或其他错误码,都进行重启
81143
echo ""
82-
echo "[$(date +'%H:%M:%S')] Process exited with code ($EXIT_CODE). Assuming restart request or crash. Rebooting in 5 seconds..."
144+
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Process exited with code ($EXIT_CODE). Restarting in 5 seconds..."
83145
sleep 5
84146
fi
85147
done

0 commit comments

Comments
 (0)