You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何向Teloxide的commands_repl的handler函数传递额外参数?

最优实现方案

通过闭包捕获克隆后的Tokio mpsc Sender实例实现需求,无需引入全局变量,完全符合Teloxide的接口约束。

修改后的代码示例

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 可根据业务需要调整通道缓冲区大小
    let (tx, mut rx) = mpsc::channel(10);
    let bot = Bot::new(&cfg.telegram.api_key).auto_send();
    let bot_name: String = String::from("Tracker Bot");

    // 单独 spawn 异步任务消费通道数据
    tokio::spawn(async move {
        while let Some(addr) = rx.recv().await {
            // 此处编写接收到地址后的处理逻辑
            println!("收到新增Token地址: {addr}");
        }
    });

    // 克隆Sender,通过move闭包传入处理逻辑
    let tx_clone = tx.clone();
    teloxide::commands_repl(bot, bot_name, move |cx, command| async move {
        handle_command(cx, command, tx_clone.clone()).await
    }).await;

    Ok(())
}

async fn handle_command(
    cx: UpdateWithCx<AutoSend<Bot>, Message>,
    command: telegram::Command,
    tx: mpsc::Sender<H160>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match command {
        telegram::Command::Help => cx.answer(telegram::Command::descriptions()).await?,
        telegram::Command::AddToken(token) => {
            let addr: H160 = token.parse()?;
            tx.send(addr).await?;
            cx.answer(format!("Token added: {}", token)).await?
        }
    };

    Ok(())
}

方案说明

  • Tokio mpsc通道原生支持多发送端设计,clone()生成新发送端的开销极低,符合多场景共享发送能力的需求
  • 传入commands_repl的闭包完全满足接口约束:move关键字将克隆后的Sender所有权转移到闭包内,无外部生命周期依赖,满足'static要求,同时闭包本身符合Send + Sync约束
  • 所有变量作用域和生命周期可控,完全规避全局变量带来的初始化、同步、生命周期管理等额外问题

内容的提问来源于stack exchange,提问作者boston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:39:03