From 0e84a9c5cad2c5b8d4a2a9cff67c106ce4a47dfa Mon Sep 17 00:00:00 2001 From: Jokler Date: Mon, 19 Mar 2018 03:26:09 +0100 Subject: Use a prefix from the config instead of the nick --- configs/config.toml | 1 + src/lib.rs | 40 +++++++++++++------------------------ src/main.rs | 5 ++++- src/plugin.rs | 37 +++++++++++++---------------------- src/plugins/currency.rs | 52 +++++++++++++++++++++---------------------------- src/plugins/tell/mod.rs | 24 +++++++++-------------- 6 files changed, 62 insertions(+), 97 deletions(-) diff --git a/configs/config.toml b/configs/config.toml index 5a78444..03b8046 100644 --- a/configs/config.toml +++ b/configs/config.toml @@ -25,6 +25,7 @@ source = "https://github.com/Mavulp/frippy" #"#frippy" = "" [options] +#prefix = "." #disabled_plugins = "Url" # If no database url is set a HashMap is used #mysql_url = "mysql://user:password@address/db" diff --git a/src/lib.rs b/src/lib.rs index 4d9b113..8477fd2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,11 +73,12 @@ use plugin::*; /// The bot which contains the main logic. #[derive(Default)] -pub struct Bot { +pub struct Bot<'a> { + prefix: &'a str, plugins: ThreadedPlugins, } -impl Bot { +impl<'a> Bot<'a> { /// Creates a `Bot`. /// By itself the bot only responds to a few simple CTCP commands /// defined per config file. @@ -89,8 +90,9 @@ impl Bot { /// use frippy::Bot; /// let mut bot = Bot::new(); /// ``` - pub fn new() -> Bot { + pub fn new(cmd_prefix: &'a str) -> Bot<'a> { Bot { + prefix: cmd_prefix, plugins: ThreadedPlugins::new(), } } @@ -162,11 +164,12 @@ impl Bot { client.identify().context(ErrorKind::Connection)?; info!("Identified"); - // TODO Verify if we actually need to clone plugins twice + // TODO Verify if we actually need to clone twice let plugins = self.plugins.clone(); + let prefix = self.prefix.to_owned(); reactor.register_client_with_handler(client, move |client, message| { - process_msg(client, plugins.clone(), message) + process_msg(client, plugins.clone(), &prefix.clone(), message) }); Ok(()) @@ -176,6 +179,7 @@ impl Bot { fn process_msg( client: &IrcClient, mut plugins: ThreadedPlugins, + prefix: &str, message: Message, ) -> Result<(), IrcError> { // Log any channels we join @@ -186,7 +190,7 @@ fn process_msg( } // Check for possible command and save the result for later - let command = PluginCommand::from(&client.current_nickname().to_lowercase(), &message); + let command = PluginCommand::try_from(prefix, &message); plugins.execute_plugins(client, message); @@ -259,14 +263,7 @@ impl ThreadedPlugins { client: &IrcClient, mut command: PluginCommand, ) -> Result<(), FrippyError> { - if !command.tokens.iter().any(|s| !s.is_empty()) { - let help = format!("Use \"{} help\" to get help", client.current_nickname()); - client - .send_notice(&command.source, &help) - .context(ErrorKind::Connection)?; - } - - // Check if the command is for this plugin + // Check if there is a plugin for this command if let Some(plugin) = self.plugins.get(&command.tokens[0].to_lowercase()) { // The first token contains the name of the plugin let name = command.tokens.remove(0); @@ -281,20 +278,9 @@ impl ThreadedPlugins { log_error(e); }; }); - - Ok(()) - } else { - let help = format!( - "\"{} {}\" is not a command, \ - try \"{0} help\" instead.", - client.current_nickname(), - command.tokens[0] - ); - - Ok(client - .send_notice(&command.source, &help) - .context(ErrorKind::Connection)?) } + + Ok(()) } } diff --git a/src/main.rs b/src/main.rs index 1070e9e..e0b50eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -121,17 +121,20 @@ fn run() -> Result<(), Error> { // Open a connection and add work for each config for config in configs { + let mut prefix = None; let mut disabled_plugins = None; let mut mysql_url = None; if let Some(ref options) = config.options { if let Some(disabled) = options.get("disabled_plugins") { disabled_plugins = Some(disabled.split(',').map(|p| p.trim()).collect::>()); } + prefix = options.get("prefix"); mysql_url = options.get("mysql_url"); } + let prefix = prefix.map(|&ref s| s.clone()).unwrap_or(String::from(".")); - let mut bot = frippy::Bot::new(); + let mut bot = frippy::Bot::new(&prefix); bot.add_plugin(Help::new()); bot.add_plugin(Url::new(1024)); bot.add_plugin(Sed::new(60)); diff --git a/src/plugin.rs b/src/plugin.rs index bc428d5..6c81741 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -66,35 +66,24 @@ impl PluginCommand { /// Creates a `PluginCommand` from [`Message`](../../irc/proto/message/struct.Message.html) /// if it contains a [`PRIVMSG`](../../irc/proto/command/enum.Command.html#variant.PRIVMSG) /// that starts with the provided `nick`. - pub fn from(nick: &str, message: &Message) -> Option { + pub fn try_from(prefix: &str, message: &Message) -> Option { // Get the actual message out of PRIVMSG if let Command::PRIVMSG(_, ref content) = message.command { - // Split content by spaces and filter empty tokens + // Split content by spaces let mut tokens: Vec = content.split(' ').map(ToOwned::to_owned).collect(); - // Commands start with our name - if tokens[0].to_lowercase().starts_with(nick) { - // Remove the bot's name from the first token - tokens[0].drain(..nick.len()); - - // We assume that only ':' and ',' are used as suffixes on IRC - // If there are any other chars we assume that it is not ment for the bot - tokens[0] = tokens[0].chars().filter(|&c| !":,".contains(c)).collect(); - if !tokens[0].is_empty() { - return None; - } - - // The first token contained the name of the bot - tokens.remove(0); - - Some(PluginCommand { - source: message.source_nickname().unwrap().to_string(), - target: message.response_target().unwrap().to_string(), - tokens: tokens, - }) - } else { - None + // Commands start with a prefix + if !tokens[0].to_lowercase().starts_with(prefix) { + return None; } + // Remove the prefix from the first token + tokens[0].drain(..prefix.len()); + + Some(PluginCommand { + source: message.source_nickname().unwrap().to_string(), + target: message.response_target().unwrap().to_string(), + tokens: tokens, + }) } else { None } diff --git a/src/plugins/currency.rs b/src/plugins/currency.rs index 53a245c..99f46c8 100644 --- a/src/plugins/currency.rs +++ b/src/plugins/currency.rs @@ -70,15 +70,15 @@ impl Currency { }) } - fn convert(&self, client: &IrcClient, command: &mut PluginCommand) -> Result { + fn convert(&self, command: &mut PluginCommand) -> Result { if command.tokens.len() < 3 { - return Err(self.invalid_command(client)); + return Err(self.invalid_command()); } let request = match self.eval_command(&command.tokens) { Ok(request) => request, Err(_) => { - return Err(self.invalid_command(client)); + return Err(self.invalid_command()); } }; @@ -94,31 +94,23 @@ impl Currency { Ok(response) } - None => Err(String::from( - "An error occured during the conversion of the given currency", - )), + None => Err("An error occured during the conversion of the given currency"), } } - fn help(&self, client: &IrcClient) -> String { - format!( - "usage: {} currency value from_currency to_currency\r\n\ - example: {0} currency 1.5 eur usd\r\n\ - available currencies: AUD, BGN, BRL, CAD, \ - CHF, CNY, CZK, DKK, GBP, HKD, HRK, HUF, \ - IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, \ - NZD, PHP, PLN, RON, RUB, SEK, SGD, THB, \ - TRY, USD, ZAR", - client.current_nickname() - ) + fn help(&self) -> &str { + "usage: currency value from_currency to_currency\r\n\ + example: {0} currency 1.5 eur usd\r\n\ + available currencies: AUD, BGN, BRL, CAD, \ + CHF, CNY, CZK, DKK, GBP, HKD, HRK, HUF, \ + IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, \ + NZD, PHP, PLN, RON, RUB, SEK, SGD, THB, \ + TRY, USD, ZAR" } - fn invalid_command(&self, client: &IrcClient) -> String { - format!( - "Incorrect Command. \ - Send \"{} currency help\" for help.", - client.current_nickname() - ) + fn invalid_command(&self) -> &str { + "Incorrect Command. \ + Send \"currency help\" for help." } } @@ -134,15 +126,15 @@ impl Plugin for Currency { fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), FrippyError> { if command.tokens.is_empty() { return Ok(client - .send_notice(&command.source, &self.invalid_command(client)) + .send_notice(&command.source, &self.invalid_command()) .context(FrippyErrorKind::Connection)?); } match command.tokens[0].as_ref() { "help" => Ok(client - .send_notice(&command.source, &self.help(client)) + .send_notice(&command.source, self.help()) .context(FrippyErrorKind::Connection)?), - _ => match self.convert(client, &mut command) { + _ => match self.convert(&mut command) { Ok(msg) => Ok(client .send_privmsg(&command.target, &msg) .context(FrippyErrorKind::Connection)?), @@ -153,14 +145,14 @@ impl Plugin for Currency { } } - fn evaluate(&self, client: &IrcClient, mut command: PluginCommand) -> Result { + fn evaluate(&self, _: &IrcClient, mut command: PluginCommand) -> Result { if command.tokens.is_empty() { - return Err(self.invalid_command(client)); + return Err(self.invalid_command().to_owned()); } match command.tokens[0].as_ref() { - "help" => Ok(self.help(client)), - _ => self.convert(client, &mut command), + "help" => Ok(self.help().to_owned()), + _ => self.convert(&mut command).map_err(|e| e.to_owned()), } } } diff --git a/src/plugins/tell/mod.rs b/src/plugins/tell/mod.rs index e8a2bb6..b3c2195 100644 --- a/src/plugins/tell/mod.rs +++ b/src/plugins/tell/mod.rs @@ -45,7 +45,7 @@ impl Tell { command: PluginCommand, ) -> Result { if command.tokens.len() < 2 { - return Ok(self.invalid_command(client)); + return Ok(self.invalid_command().to_owned()); } let mut online = Vec::new(); @@ -168,20 +168,14 @@ impl Tell { Ok(()) } - fn invalid_command(&self, client: &IrcClient) -> String { - format!( - "Incorrect Command. \ - Send \"{} tell help\" for help.", - client.current_nickname() - ) + fn invalid_command(&self) -> &str { + "Incorrect Command. \ + Send \"tell help\" for help." } - fn help(&self, client: &IrcClient) -> String { - format!( - "usage: {} tell user message\r\n\ - example: {0} tell Foobar Hello!", - client.current_nickname() - ) + fn help(&self) -> &str { + "usage: {} tell user message\r\n\ + example: {0} tell Foobar Hello!" } } @@ -215,7 +209,7 @@ impl Plugin for Tell { fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { if command.tokens.is_empty() { return Ok(client - .send_notice(&command.source, &self.invalid_command(client)) + .send_notice(&command.source, &self.invalid_command()) .context(FrippyErrorKind::Connection)?); } @@ -223,7 +217,7 @@ impl Plugin for Tell { Ok(match command.tokens[0].as_ref() { "help" => client - .send_notice(&command.source, &self.help(client)) + .send_notice(&command.source, &self.help()) .context(FrippyErrorKind::Connection) .into(), _ => match self.tell_command(client, command) { -- cgit v1.2.3-70-g09d2