nbr 0.4.3

CLI for NoneBot2 - A Rust implementation
Documentation
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
use super::env;
use crate::cli::generate::generate_bot_content;
use crate::log::StyledText;
use crate::utils::process_utils;
use anyhow::{Context, Result};
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::signal;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};

pub struct BotRunner {
    /// Bot entry file path
    bot_file: PathBuf,
    /// Python executable path
    python_executable: String,
    /// Enable auto-reload
    auto_reload: bool,
    /// Working directory
    work_dir: PathBuf,
    /// Current running process
    current_process: Arc<Mutex<Option<Child>>>,
    /// File watcher for auto-reload
    #[allow(unused)]
    watcher: Option<RecommendedWatcher>,
    /// Watch event receiver
    watch_rx: Option<Receiver<Event>>,
}

impl BotRunner {
    /// Create a new bot runner
    pub fn new(
        bot_file: PathBuf,
        python_executable: String,
        auto_reload: bool,
        work_dir: PathBuf,
    ) -> Result<Self> {
        let current_process = Arc::new(Mutex::new(None));

        let (watcher, watch_rx) = if auto_reload {
            let (tx, rx) = mpsc::channel();

            let mut watcher = RecommendedWatcher::new(
                move |res: notify::Result<Event>| {
                    if let Ok(event) = res
                        && let Err(e) = tx.send(event)
                    {
                        error!("Failed to send file watch event: {}", e);
                    }
                },
                Config::default(),
            )
            .context("Failed to create file watcher")?;

            watcher
                .watch(&work_dir, RecursiveMode::Recursive)
                .context("Failed to watch directory")?;

            (Some(watcher), Some(rx))
        } else {
            (None, None)
        };

        let runner = Self {
            bot_file,
            python_executable,
            auto_reload,
            work_dir,
            current_process,
            watcher,
            watch_rx,
        };

        Ok(runner)
    }

    /// Start the bot process
    pub async fn run(&mut self) -> Result<()> {
        // Setup signal handling for graceful shutdown
        let process_handle = Arc::clone(&self.current_process);
        tokio::spawn(async move {
            let _ = signal::ctrl_c().await;

            warn!("Received interrupt signal, shutting down...");
            if let Ok(mut process) = process_handle.lock()
                && let Some(mut child) = process.take()
            {
                let _ = child.kill();
                let _ = child.wait();
            }
            // sleep 2 second
            sleep(Duration::from_secs(2)).await;
            std::process::exit(0);
        });

        if self.auto_reload {
            self.run_with_reload().await
        } else {
            self.run_once().await
        }
    }

    /// Run bot once without reload
    async fn run_once(&mut self) -> Result<()> {
        let mut process = self.start_bot_process()?;

        let exit_status = process.wait().context("Failed to wait for process")?;

        if exit_status.success() {
            info!("Bot process exited successfully");
        } else {
            let exit_code = exit_status.code().unwrap_or(-1);
            error!("Bot process failed with exit code: {}", exit_code);
        }
        Ok(())
    }

    /// Run bot with auto-reload
    async fn run_with_reload(&mut self) -> Result<()> {
        let mut last_restart = std::time::Instant::now();
        const MAX_RAPID_RESTARTS: u32 = 5;
        const RAPID_RESTART_THRESHOLD: Duration = Duration::from_secs(10);

        let mut reload_needed = false;
        loop {
            // Start the bot process
            match self.start_bot_process() {
                Ok(process) => {
                    {
                        let mut current = self.current_process.lock().unwrap();
                        *current = Some(process);
                    }

                    info!("Bot started successfully with auto-reload enabled");
                    let mut restart_count = 0;

                    // Wait for file changes or process exit
                    reload_needed = self.wait_for_reload_trigger().await?;

                    // Kill current process
                    self.kill_current_process();

                    if !reload_needed {
                        break;
                    }

                    // Check for rapid restarts
                    let now = std::time::Instant::now();
                    if now.duration_since(last_restart) < RAPID_RESTART_THRESHOLD {
                        restart_count += 1;
                        if restart_count >= MAX_RAPID_RESTARTS {
                            warn!("Too many rapid restarts, adding delay 5s...");
                            sleep(Duration::from_secs(5)).await;
                        }
                    }
                    last_restart = now;

                    debug!("Starting bot process...");
                }
                Err(e) => {
                    error!("Failed to start bot process: {}", e);
                    if !reload_needed {
                        break;
                    }
                    sleep(Duration::from_secs(2)).await;
                }
            }
        }

        Ok(())
    }

    /// Wait for reload trigger (file change or process exit)
    async fn wait_for_reload_trigger(&self) -> Result<bool> {
        let Some(watch_rx) = self.watch_rx.as_ref() else {
            return Ok(false);
        };

        loop {
            // Check if process is still running
            {
                let mut process_guard = self.current_process.lock().unwrap();
                if let Some(process) = process_guard.as_mut() {
                    match process.try_wait() {
                        Ok(Some(status)) => {
                            info!("Bot process exited with status: {}", status);
                            return Ok(false); // Process exited, don't reload
                        }
                        Ok(None) => {} // Process still running
                        Err(e) => {
                            error!("Checking bot process status: {}", e);
                            return Ok(false);
                        }
                    }
                }
            }
            // Check for file changes
            match watch_rx.try_recv() {
                Ok(event) => {
                    if self.should_reload_for_event(&event) {
                        info!("File change detected, reloading bot...");
                        // 清空未处理的事件
                        while watch_rx.try_recv().is_ok() {}
                        return Ok(true);
                    }
                }
                Err(mpsc::TryRecvError::Empty) => {
                    // No events, continue waiting
                    sleep(Duration::from_millis(1000)).await;
                }
                Err(mpsc::TryRecvError::Disconnected) => {
                    error!("File watcher disconnected");
                    return Ok(false);
                }
            }
        }
    }

    /// Check if an event should trigger a reload
    fn should_reload_for_event(&self, event: &Event) -> bool {
        match event.kind {
            EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_) => {}
            _ => return false,
        }

        // 需要重载的文件名
        let file_names = ["pyproject.toml", ".env", ".env.dev", ".env.prod"];

        for path in &event.paths {
            if let Some(name) = path.file_name().and_then(|n| n.to_str())
                && file_names.contains(&name)
            {
                return true;
            }

            // Only reload for Python files
            if path.extension().and_then(|ext| ext.to_str()) == Some("py") {
                return true;
            }
        }
        false
    }

    #[allow(unused)]
    fn start_bot_process_with_uv(&self) -> Result<Child> {
        let mut cmd = Command::new("uv");
        cmd.arg("run").arg("--no-sync");
        if self.bot_file.exists() {
            cmd.arg(&self.bot_file);
        } else {
            cmd.arg("python")
                .arg("-c")
                .arg(generate_bot_content(&self.work_dir)?);
        }
        cmd.current_dir(&self.work_dir)
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());

        let process = cmd.spawn().context("Failed to start bot process")?;

        debug!("Bot process started with PID: {}", process.id());
        Ok(process)
    }

    fn start_bot_process(&self) -> Result<Child> {
        let mut cmd = Command::new(self.python_executable.clone());
        if self.bot_file.exists() {
            cmd.arg(&self.bot_file);
        } else {
            let bot_content = generate_bot_content(&self.work_dir)?;
            cmd.arg("-c").arg(bot_content);
        }
        cmd.current_dir(&self.work_dir)
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());

        let process = cmd.spawn().context("Failed to start bot process")?;

        debug!("Bot process started with PID: {}", process.id());
        Ok(process)
    }

    /// Kill current process
    fn kill_current_process(&self) {
        let mut process_guard = self.current_process.lock().unwrap();
        if let Some(mut process) = process_guard.take() {
            debug!("Stopping bot process...");

            // Try graceful shutdown first
            if let Err(e) = process.kill() {
                warn!("Failed to kill process gracefully: {}", e);
            }

            // Wait for process to exit
            match process.wait() {
                Ok(status) => {
                    debug!("Process exited with status: {}", status);
                }
                Err(e) => {
                    warn!("Error waiting for process to exit: {}", e);
                }
            }
        }
    }
}

impl Drop for BotRunner {
    fn drop(&mut self) {
        self.kill_current_process();
    }
}

/// Handle the run command
pub async fn handle(file: Option<String>, reload: bool) -> Result<()> {
    let bot_file = file.unwrap_or("bot.py".to_string());
    // Load configuration
    let work_dir = std::env::current_dir()?;
    // Find bot file
    let bot_file_path = work_dir.join(bot_file);
    // Find Python executable
    let python_executable = env::find_python_executable(&work_dir)?;
    // Create and run bot
    let mut runner = BotRunner::new(bot_file_path, python_executable, reload, work_dir)?;
    StyledText::new(" ")
        .green("Using Python:")
        .cyan_underline(&runner.python_executable)
        .println_bold();

    runner.run().await?;
    Ok(())
}

/// Verify Python environment
#[allow(unused)]
async fn verify_python_environment(python_executable: &str) -> Result<()> {
    debug!("Verifying Python environment...");
    // Check Python version
    let version = process_utils::get_python_version(python_executable).await?;
    debug!("Python version: {}", version);

    // Verify it's Python 3.10+
    if !version.contains("Python 3.1") {
        anyhow::bail!("Python 3.10+ required, found: {}", version);
    }

    // Check if NoneBot is installed
    match process_utils::execute_command_with_output(
        python_executable,
        &["-c", "import nonebot"],
        None,
        60,
    )
    .await
    {
        Ok(_) => {
            debug!("NoneBot is installed");
        }
        Err(_) => {
            warn!("NoneBot doesn't seem to be installed. The bot may fail to start.");
        }
    }

    Ok(())
}

/// Load environment variables from .env files
pub fn load_environment_variables(work_dir: &Path) -> Result<HashMap<String, String>> {
    let mut env_vars = HashMap::new();

    let env_files = [".env", ".env.dev", ".env.prod"];

    for env_file in &env_files {
        let env_path = work_dir.join(env_file);
        if env_path.exists() {
            debug!("Loading environment variables from {}", env_path.display());

            let content = fs::read_to_string(&env_path)
                .with_context(|| format!("Failed to read {}", env_file))?;

            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }

                if let Some(eq_pos) = line.find('=') {
                    let key = line[..eq_pos].trim().to_string();
                    let value = line[eq_pos + 1..].trim();

                    // Remove quotes if present
                    let value = if (value.starts_with('"') && value.ends_with('"'))
                        || (value.starts_with('\'') && value.ends_with('\''))
                    {
                        &value[1..value.len() - 1]
                    } else {
                        value
                    };

                    env_vars.insert(key, value.to_string());
                }
            }
        }
    }

    debug!("Loaded {} environment variables", env_vars.len());
    Ok(env_vars)
}