Skip to main content

word_guess/
word_guess.rs

1//! 群内猜词游戏:群里任何人都能作答;答错让本轮继续(一个 waiter、多个事件),"取消"/超时
2//! 结束。演示中断引擎 —— `session.waiter().scope(Scope::peer(g))` + 一个 `recv::<GroupMessage>`
3//! 循环 —— 外加一个 `#[event(Message, top)]` top 观察者(发言计数器):因为 top 层在 waiter 之前
4//! 运行,所以即便会话进行中它也持续看到每条消息。
5use nagisa::prelude::*;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::Duration;
8
9nagisa::plugin! { name = "猜词", category = Fun, key = "word_guess" }
10
11static SPEECH_COUNT: AtomicU64 = AtomicU64::new(0);
12
13#[event(Message, top, id = "speech_count")]
14async fn speech_count(_m: MessageEvent) -> HandlerResult {
15    SPEECH_COUNT.fetch_add(1, Ordering::Relaxed);
16    Ok(())
17}
18
19#[command("猜词", id = "start")]
20async fn start(reply: Reply, ep: EventPeer, session: Session) -> HandlerResult {
21    let group = ep.0;
22    let answer = "答案";
23    let waiter = session.waiter().scope(Scope::peer(group)).build();
24    reply.text("开始猜词,在群里直接发答案吧(发\"取消\"结束)").await?;
25    loop {
26        match waiter.recv::<GroupMessage>(Duration::from_secs(60)).await {
27            Some(m) => {
28                let text = m.0.content.first().and_then(|s| s.as_text()).unwrap_or("");
29                if text == "取消" {
30                    reply.text("已结束").await?;
31                    break;
32                } else if text == answer {
33                    // 链式构建器对标 `Msg`:先 @ 赢家,再道贺。
34                    reply.msg().at(m.0.sender).text(" 答对了!").send().await?;
35                    break;
36                } else {
37                    reply.text("再猜猜").await?;
38                }
39            }
40            None => {
41                reply.text(format!("超时,答案是 {answer}")).await?;
42                break;
43            }
44        }
45    }
46    Ok(())
47}
48
49#[cfg(feature = "onebot")]
50#[tokio::main]
51async fn main() -> Result<()> {
52    let shutdown = nagisa::ctrl_c_shutdown();
53    App::new().run_onebot(OneBotConfig::new("ws://127.0.0.1:8080/onebot/v11/ws"), shutdown).await
54}
55
56#[cfg(not(feature = "onebot"))]
57fn main() {
58    eprintln!("enable the `onebot` feature to run this example");
59}