rust - 如何将额外的参数传递给 Rust 中的“Fn”参数?
问题描述
要使用名为 Teloxide 的 TG bot crate 处理命令,我必须提供一个handle_command
具有特殊签名的函数:
pub async fn commands_repl<R, Cmd, H, Fut, HandlerE, N>(requester: R, bot_name: N, handler: H)
where
Cmd: BotCommand + Send + 'static,
H: Fn(UpdateWithCx<R, Message>, Cmd) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), HandlerE>> + Send + 'static,
Result<(), HandlerE>: OnError<HandlerE>,
HandlerE: Debug + Send,
N: Into<String> + Send + 'static,
R: Requester + Send + Clone + 'static,
<R as Requester>::GetUpdatesFaultTolerant: Send,
然而,在我的handler
函数体中,我想访问 Tokio Sender 通道来发送从我的电报消息中接收到的数据。
所以在代码中,这就是我想做的:
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let (tx, rx) = mpsc::channel(1);
let bot = Bot::new(&cfg.telegram.api_key).auto_send();
let bot_name: String = String::from("Tracker Bot");
teloxide::commands_repl(bot, bot_name, handle_command).await;
Ok(())
}
async fn handle_command(
cx: UpdateWithCx<AutoSend<Bot>, Message>,
command: telegram::Command,
) -> 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(())
}
解决此问题的最佳方法是什么?我考虑过制作Sender
一个全局变量,但这似乎会产生很多其他问题。那么还有其他方法可以访问handle_command
函数内的该变量吗?
解决方案
推荐阅读
- python - Keras 在单个 epoch 中打印出每批的结果,这是为什么呢?
- python - 非相邻对之间的 pct_change
- sql - 复合键中的一个字段可以依赖于另一个字段吗?
- java - Fetching data using hibernate with Netbeans
- sqlite - 从基于 JOIN 但使用不在 JOIN 或 SELECT 中的列的两个单独的 SQL 表中提取数据
- unit-testing - Spring-Webflux:处理函数单元测试抛出 UnsupportedMediaTypeStatusException
- sql-server - 使用日期表在期末进行中的事件的 dax
- javascript - Firebase signInWithEmailAndPassword not working as well
- javascript - React Native app doesn't show database items
- node.js - 设置快速服务器的反应