I am writing a program on rust to create a telegram bot, which should also asynchronously send a request to another service.
I can’t compilation program, get problem
Full text program:
use telebot::Bot;
use futures::stream::Stream;
use dotenv::dotenv;
use std::env;
use serde::Deserialize;
use reqwest::Error;
// import all available functions
use telebot::functions::*;
#[derive(Deserialize, Debug)]
struct ApiResponse {
translatedText: String,
}
async fn translate(_text: &String, _api_translate_url: &str, _api_translate_key: &str) -> Result<(), Error> {
let url = _api_translate_url;
let response = reqwest::get(url).await?.json::<ApiResponse>().await?;
println!("{:#?}", response);
Ok(())
}
#[tokio::main]
async fn main() {
dotenv().ok();
env_logger::init();
let token_bot = env::var("TELEGRAM_BOT_KEY").expect("TELEGRAM_BOT_KEY not found");
let api_translate_url = env::var("API_TRANSLATE_URL").expect("API_TRANSLATE_URL not found");
let api_translate_key = env::var("API_TRANSLATE_KEY").expect("API_TRANSLATE_KEY not found");
// Create the bot
let mut bot = Bot::new(&token_bot).update_interval(200);
// Register a reply command which answers a message
let handle = bot.new_cmd("/reply")
.and_then(move |(bot, msg)| {
let mut text = msg.text.unwrap().clone();
if text.is_empty() {
text = "<empty>".into();
}
bot.message(msg.chat.id, text).send();
let api_translate_url = api_translate_url.clone();
let api_translate_key = api_translate_key.clone();
async move {
translate(&text, &api_translate_url, &api_translate_key).await?;
Ok(())
}
})
.for_each(|result| async {
if let Err(err) = result {
eprintln!("Error: {:?}", err);
}
});
bot.run_with(handle);
}
The problem is related to for_each
41 | let handle = bot.new_cmd("/reply")
| __________________-
42 | | .and_then(move |(bot, msg)| {
43 | | let mut text = msg.text.unwrap().clone();
44 | | if text.is_empty() {
... |
57 | | })
58 | | .for_each(|result| async {
| | -^^^^^^^^ method cannot be called due to unsatisfied trait bounds
| |_________|
|
I can’t solve the problem
Make sure and_then handles asynchronous blocks correctly via async move.
New contributor
Digkill is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.