diff --git a/src/main.rs b/src/main.rs index da980b8..d53f327 100644 --- a/src/main.rs +++ b/src/main.rs @@ -117,15 +117,18 @@ async fn handler(cfg: &Config, s: &mut State) -> Result<(), reqwest::Error> { match args.next()? { "ru" => { let comic_id = args.next()?.parse::().ok()?; - Some((msg, format!("https://xkcd.ru/{}/?json=true", comic_id))) + let url = format!("https://xkcd.ru/{}/?json=true", comic_id); + Some(SenderCtx { msg, url, comic_id }) } "en" => { let comic_id = args.next()?.parse::().ok()?; - Some((msg, format!("https://xkcd.com/{}/info.0.json", comic_id))) + let url = format!("https://xkcd.com/{}/info.0.json", comic_id); + Some(SenderCtx { msg, url, comic_id }) } comic_id => { let comic_id = comic_id.parse::().ok()?; - Some((msg, format!("https://xkcd.com/{}/info.0.json", comic_id))) + let url = format!("https://xkcd.com/{}/info.0.json", comic_id); + Some(SenderCtx { msg, url, comic_id }) } } } else { @@ -134,8 +137,8 @@ async fn handler(cfg: &Config, s: &mut State) -> Result<(), reqwest::Error> { }) }) }) - .for_each(|(msg, url)| { - tokio::spawn(send_comic(cfg.clone(), msg, url)); + .for_each(|ctx| { + tokio::spawn(send_comic(cfg.clone(), ctx)); }); if let Some(u) = updates.last() { @@ -145,16 +148,24 @@ async fn handler(cfg: &Config, s: &mut State) -> Result<(), reqwest::Error> { Ok(()) } -async fn send_comic(cfg: Config, msg: TgMessage, url: String) -> Result<(), reqwest::Error> { - let info = cfg.client.get(url).send().await?.json::().await?; +async fn send_comic(cfg: Config, ctx: SenderCtx) -> Result<(), reqwest::Error> { + let info = cfg + .client + .get(ctx.url) + .send() + .await? + .error_for_status()? + .json::() + .await?; cfg.client .post((*cfg.send_url).clone()) .form(&[ - ("chat_id", msg.chat.id.to_string()), + ("chat_id", ctx.msg.chat.id.to_string()), ( "message_thread_id", - msg.thread + ctx.msg + .thread .map(|t| t.to_string()) .unwrap_or("null".to_owned()), ), diff --git a/src/types.rs b/src/types.rs index b5e7dfa..d0d533b 100644 --- a/src/types.rs +++ b/src/types.rs @@ -17,6 +17,14 @@ pub struct Config { pub send_url: Arc, } +/// Object holding a context for fn send_comic +#[derive(Debug)] +pub struct SenderCtx { + pub msg: TgMessage, + pub url: String, + pub comic_id: u16, +} + /// Telegram Bot API response: /// these idiots use `{ok:true,response:...}` schema /// for some reason