From 4669d37a7186a7b744acaf1e30b7ae4cad9f2055 Mon Sep 17 00:00:00 2001 From: Sakuhl <2012collector@gmail.com> Date: Wed, 7 Mar 2018 14:53:31 +0100 Subject: [PATCH] Fix cleverbot error handling --- src/main.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6006ad8..f67d66e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -156,6 +156,18 @@ struct CBResponse { output: String } +fn cleverbot(msg: &Message) -> Result { + let _ = msg.channel_id.broadcast_typing(); + let resp = reqwest::get(&format!("http://www.cleverbot.com/getreply?key=CC7wgO9gQl7yPjB54eDLHmM5Jmg&input={}&cb_settings_tweak1=0&cb_settings_tweak2=100&cb_settings_tweak3=100{}", + msg.content.replace("<@392763365409292298>", ""), (*CS).lock().clone().map(|x| format!("&cs={}", x)).unwrap_or_else(String::new)))? + .error_for_status()? + .text()?; + thread::sleep_ms(500); + let resp: CBResponse = serde_json::from_str(&resp)?; + msg.channel_id.say(format!("{} {}", msg.author.mention(), resp.output))?; + Ok(resp.cs) +} + impl Handler { fn process_message(&self, msg: &Message, prefix: &str) -> Result<(), Error> { if msg.content == "<@392763365409292298> has big gay" { @@ -171,16 +183,14 @@ impl Handler { return Ok(()); } if msg.content.contains("<@392763365409292298>") { - let _ = msg.channel_id.broadcast_typing(); - let resp = reqwest::get(&format!("http://www.cleverbot.com/getreply?key=CC7wgO9gQl7yPjB54eDLHmM5Jmg&input={}&cb_settings_tweak1=0&cb_settings_tweak2=100&cb_settings_tweak3=100{}", - msg.content.replace("<@392763365409292298>", ""), (*CS).lock().clone().map(|x| format!("&cs={}", x)).unwrap_or_else(String::new)))? - .error_for_status()? - .text()?; - thread::sleep_ms(500); - let resp: CBResponse = serde_json::from_str(&resp)?; - *(*CS).lock() = Some(resp.cs); - msg.channel_id.say(format!("{} {}", msg.author.mention(), resp.output))?; - return Ok(()); + if let Ok(cs) = cleverbot(msg) { + *(*CS).lock() = Some(cs); + return Ok(()); + } else { + *(*CS).lock() = None; + self.process_message(msg, prefix)?; + return Ok(()); + } } if !msg.content.starts_with(&prefix) { return Ok(());