diff options
| author | acdenisSK <[email protected]> | 2017-07-27 06:42:48 +0200 |
|---|---|---|
| committer | acdenisSK <[email protected]> | 2017-07-27 07:30:23 +0200 |
| commit | 550030264952f0e0043b63f4582bb817ef8bbf37 (patch) | |
| tree | b921e2f78fd603a5ca671623083a32806fd16090 /src/framework/mod.rs | |
| parent | Use a consistent indentation style (diff) | |
| download | serenity-550030264952f0e0043b63f4582bb817ef8bbf37.tar.xz serenity-550030264952f0e0043b63f4582bb817ef8bbf37.zip | |
rustfmt
Diffstat (limited to 'src/framework/mod.rs')
| -rw-r--r-- | src/framework/mod.rs | 276 |
1 files changed, 163 insertions, 113 deletions
diff --git a/src/framework/mod.rs b/src/framework/mod.rs index d132b5b..9fddc76 100644 --- a/src/framework/mod.rs +++ b/src/framework/mod.rs @@ -63,7 +63,7 @@ mod create_group; mod buckets; pub(crate) use self::buckets::{Bucket, Ratelimit}; -pub use self::command::{Command, CommandType, CommandGroup}; +pub use self::command::{Command, CommandGroup, CommandType}; pub use self::command::CommandOrAlias; pub use self::configuration::Configuration; pub use self::create_command::CreateCommand; @@ -73,16 +73,16 @@ use self::command::{AfterHook, BeforeHook}; use std::collections::HashMap; use std::default::Default; use std::sync::Arc; -use ::client::Context; -use ::model::{Message, UserId, GuildId, ChannelId}; -use ::model::permissions::Permissions; -use ::utils; +use client::Context; +use model::{ChannelId, GuildId, Message, UserId}; +use model::permissions::Permissions; +use utils; use tokio_core::reactor::Handle; -#[cfg(feature="cache")] -use ::client::CACHE; -#[cfg(feature="cache")] -use ::model::Channel; +#[cfg(feature = "cache")] +use client::CACHE; +#[cfg(feature = "cache")] +use model::Channel; /// A macro to generate "named parameters". This is useful to avoid manually /// using the "arguments" parameter and manually parsing types. @@ -236,16 +236,15 @@ pub struct BuiltinFramework { /// framework check if a [`Event::MessageCreate`] should be processed by /// itself. /// - /// [`EventHandler::on_message`]: ../client/event_handler/trait.EventHandler.html#method.on_message + /// [`EventHandler::on_message`]: + /// ../client/event_handler/trait.EventHandler.html#method.on_message /// [`Event::MessageCreate`]: ../model/event/enum.Event.html#variant.MessageCreate pub initialized: bool, user_info: (u64, bool), } impl BuiltinFramework { - pub fn new() -> Self { - BuiltinFramework::default() - } + pub fn new() -> Self { BuiltinFramework::default() } /// Configures the framework, setting non-default values. All fields are /// optional. Refer to [`Configuration::default`] for more information on @@ -278,7 +277,8 @@ impl BuiltinFramework { /// [`prefix`]: struct.Configuration.html#method.prefix /// [allowing whitespace]: struct.Configuration.html#method.allow_whitespace pub fn configure<F>(mut self, f: F) -> Self - where F: FnOnce(Configuration) -> Configuration { + where + F: FnOnce(Configuration) -> Configuration, { self.configuration = f(self.configuration); self @@ -308,15 +308,17 @@ impl BuiltinFramework { /// .exec_str("pong!"))); /// ``` pub fn bucket<S>(mut self, s: S, delay: i64, time_span: i64, limit: i32) -> Self - where S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay: delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: None, - }); + where + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay: delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: None, + }); self } @@ -336,10 +338,12 @@ impl BuiltinFramework { /// /// client.with_framework(BuiltinFramework::new() /// .complex_bucket("basic", 2, 10, 3, |_, guild_id, channel_id, user_id| { - /// // check if the guild is `123` and the channel where the command(s) was called: `456` + /// // check if the guild is `123` and the channel where the command(s) was called: + /// `456` /// // and if the user who called the command(s) is `789` /// // otherwise don't apply the bucket at all. - /// guild_id.is_some() && guild_id.unwrap() == 123 && channel_id == 456 && user_id == 789 + /// guild_id.is_some() && guild_id.unwrap() == 123 && channel_id == 456 && user_id + /// == 789 /// }) /// .command("ping", |c| c /// .bucket("basic") @@ -347,19 +351,27 @@ impl BuiltinFramework { /// ``` /// /// [`bucket`]: #method.bucket - #[cfg(feature="cache")] - pub fn complex_bucket<S, Check>(mut self, s: S, delay: i64, time_span: i64, limit: i32, check: Check) -> Self - where Check: Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static, - S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: Some(Box::new(check)), - }); - + #[cfg(feature = "cache")] + pub fn complex_bucket<S, Check>(mut self, + s: S, + delay: i64, + time_span: i64, + limit: i32, + check: Check) + -> Self + where + Check: Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static, + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: Some(Box::new(check)), + }); + self } @@ -389,19 +401,27 @@ impl BuiltinFramework { /// ``` /// /// [`bucket`]: #method.bucket - #[cfg(not(feature="cache"))] - pub fn complex_bucket<S, Check>(mut self, s: S, delay: i64, time_span: i64, limit: i32, check: Check) -> Self - where Check: Fn(&mut Context, ChannelId, UserId) -> bool + 'static, - S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: Some(Box::new(check)), - }); - + #[cfg(not(feature = "cache"))] + pub fn complex_bucket<S, Check>(mut self, + s: S, + delay: i64, + time_span: i64, + limit: i32, + check: Check) + -> Self + where + Check: Fn(&mut Context, ChannelId, UserId) -> bool + 'static, + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: Some(Box::new(check)), + }); + self } @@ -427,20 +447,22 @@ impl BuiltinFramework { /// .exec_str("pong!"))); /// ``` pub fn simple_bucket<S>(mut self, s: S, delay: i64) -> Self - where S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay: delay, - limit: None, - }, - users: HashMap::new(), - check: None, - }); + where + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay: delay, + limit: None, + }, + users: HashMap::new(), + check: None, + }); self } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn is_blocked_guild(&self, message: &Message) -> bool { if let Some(Channel::Guild(channel)) = CACHE.read().unwrap().channel(message.channel_id) { let guild_id = channel.read().unwrap().guild_id; @@ -449,18 +471,23 @@ impl BuiltinFramework { } if let Some(guild) = guild_id.find() { - return self.configuration.blocked_users.contains(&guild.read().unwrap().owner_id); + return self.configuration + .blocked_users + .contains(&guild.read().unwrap().owner_id); } } false } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn has_correct_permissions(&self, command: &Arc<Command>, message: &Message) -> bool { if !command.required_permissions.is_empty() { if let Some(guild) = message.guild() { - let perms = guild.read().unwrap().permissions_for(message.channel_id, message.author.id); + let perms = guild + .read() + .unwrap() + .permissions_for(message.channel_id, message.author.id); return perms.contains(command.required_permissions); } @@ -476,7 +503,8 @@ impl BuiltinFramework { command: &Arc<Command>, args: usize, to_check: &str, - built: &str) -> Option<DispatchError> { + built: &str) + -> Option<DispatchError> { if self.configuration.ignore_bots && message.author.bot { Some(DispatchError::IgnoredBot) } else if self.configuration.ignore_webhooks && message.webhook_id.is_some() { @@ -512,22 +540,22 @@ impl BuiltinFramework { if let Some(x) = command.min_args { if args < x as usize { return Some(DispatchError::NotEnoughArguments { - min: x, - given: args - }); + min: x, + given: args, + }); } } if let Some(x) = command.max_args { if args > x as usize { return Some(DispatchError::TooManyArguments { - max: x, - given: args - }); + max: x, + given: args, + }); } } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { if self.is_blocked_guild(message) { return Some(DispatchError::BlockedGuild); @@ -538,7 +566,7 @@ impl BuiltinFramework { } if (!self.configuration.allow_dm && message.is_private()) || - (command.guild_only && message.is_private()) { + (command.guild_only && message.is_private()) { return Some(DispatchError::OnlyForGuilds); } @@ -549,9 +577,14 @@ impl BuiltinFramework { if command.owners_only { Some(DispatchError::OnlyForOwners) - } else if !command.checks.iter().all(|check| (check)(&mut context, message, command)) { + } else if !command + .checks + .iter() + .all(|check| (check)(&mut context, message, command)) { Some(DispatchError::CheckFailed) - } else if self.configuration.blocked_users.contains(&message.author.id) { + } else if self.configuration + .blocked_users + .contains(&message.author.id) { Some(DispatchError::BlockedUser) } else if self.configuration.disabled_commands.contains(to_check) { Some(DispatchError::CommandDisabled(to_check.to_owned())) @@ -603,16 +636,20 @@ impl BuiltinFramework { /// # } /// ``` pub fn on<F, S>(mut self, command_name: S, f: F) -> Self - where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, - S: Into<String> { + where + F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, + S: Into<String>, { { - let ungrouped = self.groups.entry("Ungrouped".to_owned()) + let ungrouped = self.groups + .entry("Ungrouped".to_owned()) .or_insert_with(|| Arc::new(CommandGroup::default())); if let Some(ref mut group) = Arc::get_mut(ungrouped) { let name = command_name.into(); - group.commands.insert(name, CommandOrAlias::Command(Arc::new(Command::new(f)))); + group + .commands + .insert(name, CommandOrAlias::Command(Arc::new(Command::new(f)))); } } @@ -633,10 +670,12 @@ impl BuiltinFramework { /// })); /// ``` pub fn command<F, S>(mut self, command_name: S, f: F) -> Self - where F: FnOnce(CreateCommand) -> CreateCommand, - S: Into<String> { + where + F: FnOnce(CreateCommand) -> CreateCommand, + S: Into<String>, { { - let ungrouped = self.groups.entry("Ungrouped".to_owned()) + let ungrouped = self.groups + .entry("Ungrouped".to_owned()) .or_insert_with(|| Arc::new(CommandGroup::default())); if let Some(ref mut group) = Arc::get_mut(ungrouped) { @@ -645,15 +684,22 @@ impl BuiltinFramework { if let Some(ref prefix) = group.prefix { for v in &cmd.aliases { - group.commands.insert(format!("{} {}", prefix, v.to_owned()), CommandOrAlias::Alias(format!("{} {}", prefix, name))); + group + .commands + .insert(format!("{} {}", prefix, v.to_owned()), + CommandOrAlias::Alias(format!("{} {}", prefix, name))); } } else { for v in &cmd.aliases { - group.commands.insert(v.to_owned(), CommandOrAlias::Alias(name.clone())); + group + .commands + .insert(v.to_owned(), CommandOrAlias::Alias(name.clone())); } } - group.commands.insert(name, CommandOrAlias::Command(Arc::new(cmd))); + group + .commands + .insert(name, CommandOrAlias::Command(Arc::new(cmd))); } } @@ -684,8 +730,9 @@ impl BuiltinFramework { /// .command("pong", |c| c.exec_str("ping!")))); /// ``` pub fn group<F, S>(mut self, group_name: S, f: F) -> Self - where F: FnOnce(CreateGroup) -> CreateGroup, - S: Into<String> { + where + F: FnOnce(CreateGroup) -> CreateGroup, + S: Into<String>, { let group = f(CreateGroup(CommandGroup::default())).0; self.groups.insert(group_name.into(), Arc::new(group)); @@ -694,7 +741,8 @@ impl BuiltinFramework { self } - /// Specify the function that's called in case a command wasn't executed for one reason or another. + /// Specify the function that's called in case a command wasn't executed for one reason or + /// another. /// /// DispatchError represents all possible fail conditions. /// @@ -729,7 +777,8 @@ impl BuiltinFramework { /// })); /// ``` pub fn on_dispatch_error<F>(mut self, f: F) -> Self - where F: Fn(Context, Message, DispatchError) + 'static { + where + F: Fn(Context, Message, DispatchError) + 'static, { self.dispatch_error_handler = Some(Arc::new(f)); self @@ -785,7 +834,8 @@ impl BuiltinFramework { /// ``` /// pub fn before<F>(mut self, f: F) -> Self - where F: Fn(&mut Context, &Message, &String) -> bool + 'static { + where + F: Fn(&mut Context, &Message, &String) -> bool + 'static, { self.before = Some(Arc::new(f)); self @@ -816,7 +866,8 @@ impl BuiltinFramework { /// })); /// ``` pub fn after<F>(mut self, f: F) -> Self - where F: Fn(&mut Context, &Message, &String, Result<(), String>) + 'static { + where + F: Fn(&mut Context, &Message, &String, Result<(), String>) + 'static, { self.after = Some(Arc::new(f)); self @@ -846,12 +897,8 @@ impl ::Framework for BuiltinFramework { 'outer: for position in positions { let mut built = String::new(); - let round = message.content.chars() - .skip(position) - .collect::<String>(); - let round = round.trim() - .split_whitespace() - .collect::<Vec<&str>>(); + let round = message.content.chars().skip(position).collect::<String>(); + let round = round.trim().split_whitespace().collect::<Vec<&str>>(); for i in 0..self.configuration.depth { if i != 0 { @@ -859,16 +906,17 @@ impl ::Framework for BuiltinFramework { } built.push_str(match round.get(i) { - Some(piece) => piece, - None => continue 'outer, - }); + Some(piece) => piece, + None => continue 'outer, + }); let groups = self.groups.clone(); for group in groups.values() { let command_length = built.len(); - if let Some(&CommandOrAlias::Alias(ref points_to)) = group.commands.get(&built) { + if let Some(&CommandOrAlias::Alias(ref points_to)) = + group.commands.get(&built) { built = points_to.to_owned(); } @@ -882,7 +930,8 @@ impl ::Framework for BuiltinFramework { built.clone() }; - if let Some(&CommandOrAlias::Command(ref command)) = group.commands.get(&to_check) { + if let Some(&CommandOrAlias::Command(ref command)) = + group.commands.get(&to_check) { let before = self.before.clone(); let command = command.clone(); let after = self.after.clone(); @@ -901,7 +950,12 @@ impl ::Framework for BuiltinFramework { } }; - if let Some(error) = self.should_fail(&mut context, &message, &command, args.len(), &to_check, &built) { + if let Some(error) = self.should_fail(&mut context, + &message, + &command, + args.len(), + &to_check, + &built) { if let Some(ref handler) = self.dispatch_error_handler { handler(context, message, error); } @@ -921,12 +975,10 @@ impl ::Framework for BuiltinFramework { Ok(()) }, - CommandType::Basic(ref x) => { - (x)(&mut context, &message, args) - }, + CommandType::Basic(ref x) => (x)(&mut context, &message, args), CommandType::WithCommands(ref x) => { (x)(&mut context, &message, groups, &args) - } + }, }; if let Some(after) = after { @@ -943,13 +995,11 @@ impl ::Framework for BuiltinFramework { } } - #[cfg(feature="builtin_framework")] + #[cfg(feature = "builtin_framework")] fn update_current_user(&mut self, user_id: UserId, is_bot: bool) { self.user_info = (user_id.0, is_bot); } - #[cfg(feature="builtin_framework")] - fn initialized(&self) -> bool { - self.initialized - } -}
\ No newline at end of file + #[cfg(feature = "builtin_framework")] + fn initialized(&self) -> bool { self.initialized } +} |