diff options
Diffstat (limited to '')
| -rw-r--r-- | src/hooks/wa.rs | 28 |
1 files changed, 18 insertions, 10 deletions
diff --git a/src/hooks/wa.rs b/src/hooks/wa.rs index e51aa47..b518bf4 100644 --- a/src/hooks/wa.rs +++ b/src/hooks/wa.rs @@ -1,11 +1,11 @@ use crate::util::web::shorten_url; -use anyhow::{Context, Error, Result}; +use anyhow::{bail, Context, Error, Result}; use futures::try_join; use irc::client::prelude::*; +use macros::privmsg; use reqwest::{get, Url}; use serde::{Deserialize, Serialize}; use serde_json::Result as SerdeJsonResult; -use macros::privmsg; #[derive(Serialize, Deserialize, Debug)] struct WaResponse { @@ -57,14 +57,13 @@ fn to_single_string(wa_res: WaResponse) -> String { .join(" - ") } -fn get_url(query_str: &str, base_url: Option<&str>) -> String { - let app_id = "XXX"; // TODO: Get from env +fn get_url(query_str: &str, api_key: Option<&str>, base_url: Option<&str>) -> String { let wa_url = "http://api.wolframalpha.com"; let api_url = format!( "{}/v2/query?input={}&appid={}&output=json", base_url.unwrap_or(wa_url), query_str, - app_id + api_key.unwrap_or("XXX"), // Allow tests to run without a key ); api_url } @@ -87,11 +86,15 @@ async fn handle_wa_req(url: &str) -> Result<WaResponse, Error> { /// Sends a request to the Wolfram Alpha API, returns a plain text response. #[tracing::instrument] -async fn wa_query(query_str: &str, base_url: Option<&str>) -> Result<String, Error> { +async fn wa_query( + query_str: &str, + api_key: Option<&str>, + base_url: Option<&str>, +) -> Result<String, Error> { let user_url = format!("http://www.wolframalpha.com/input/?i={}", query_str); let user_url_shortened_fut = shorten_url(&user_url); - let url = get_url(query_str, base_url); + let url = get_url(query_str, api_key, base_url); let wa_res_fut = handle_wa_req(&url); // Can't just (foo.await, bar.await), smh @@ -112,9 +115,14 @@ pub async fn wa(bot: &crate::Bot, msg: Message) -> Result<()> { chars.next_back(); let content = chars.as_str(); + if content.is_empty() { + bail!("Empty input for WA query"); + } + bot.send_privmsg( - msg.response_target().context("failed to get response target")?, - &wa_query(content, None).await? + msg.response_target() + .context("failed to get response target")?, + &wa_query(content, Some(&bot.config.settings.wa_api_key), None).await?, )?; }) } @@ -135,7 +143,7 @@ mod tests { .create(); mockito::start(); - let res = wa_query("5/10", Some(&mockito::server_url())).await?; + let res = wa_query("5/10", None, Some(&mockito::server_url())).await?; let res_without_link = res.splitn(2, "-").collect::<Vec<&str>>()[1].trim(); assert_eq!(res_without_link, "Exact result: 1/2 - Decimal form: 0.5"); Ok(()) |
