botserver/src/basic/keywords/wait.rs

45 lines
1.5 KiB
Rust
Raw Normal View History

2025-10-06 10:30:17 -03:00
use crate::shared::state::AppState;
2025-10-11 12:29:03 -03:00
use crate::shared::models::UserSession;
2025-10-06 10:30:17 -03:00
use log::info;
use rhai::{Dynamic, Engine};
use std::thread;
use std::time::Duration;
2025-10-11 12:29:03 -03:00
pub fn wait_keyword(_state: &AppState, _user: UserSession, engine: &mut Engine) {
2025-10-06 10:30:17 -03:00
engine
.register_custom_syntax(
&["WAIT", "$expr$"],
2025-10-11 12:29:03 -03:00
false,
2025-10-06 10:30:17 -03:00
move |context, inputs| {
let seconds = context.eval_expression_tree(&inputs[0])?;
let duration_secs = if seconds.is::<i64>() {
seconds.cast::<i64>() as f64
} else if seconds.is::<f64>() {
seconds.cast::<f64>()
} else {
return Err(format!("WAIT expects a number, got: {}", seconds).into());
};
if duration_secs < 0.0 {
return Err("WAIT duration cannot be negative".into());
}
let capped_duration = if duration_secs > 300.0 {
300.0
} else {
duration_secs
};
info!("WAIT {} seconds (thread sleep)", capped_duration);
let duration = Duration::from_secs_f64(capped_duration);
thread::sleep(duration);
info!("WAIT completed after {} seconds", capped_duration);
Ok(Dynamic::from(format!("Waited {} seconds", capped_duration)))
},
)
.unwrap();
}