aboutsummaryrefslogtreecommitdiff
path: root/src/framework
diff options
context:
space:
mode:
authoracdenisSK <[email protected]>2017-07-27 06:42:48 +0200
committeracdenisSK <[email protected]>2017-07-27 07:30:23 +0200
commit550030264952f0e0043b63f4582bb817ef8bbf37 (patch)
treeb921e2f78fd603a5ca671623083a32806fd16090 /src/framework
parentUse a consistent indentation style (diff)
downloadserenity-550030264952f0e0043b63f4582bb817ef8bbf37.tar.xz
serenity-550030264952f0e0043b63f4582bb817ef8bbf37.zip
rustfmt
Diffstat (limited to 'src/framework')
-rw-r--r--src/framework/buckets.rs12
-rw-r--r--src/framework/command.rs11
-rw-r--r--src/framework/configuration.rs13
-rw-r--r--src/framework/create_command.rs22
-rw-r--r--src/framework/create_group.rs29
-rw-r--r--src/framework/help_commands.rs72
-rw-r--r--src/framework/mod.rs276
7 files changed, 254 insertions, 181 deletions
diff --git a/src/framework/buckets.rs b/src/framework/buckets.rs
index 76a8c0b..95b832b 100644
--- a/src/framework/buckets.rs
+++ b/src/framework/buckets.rs
@@ -2,7 +2,7 @@ use chrono::Utc;
use std::collections::HashMap;
use std::default::Default;
use client::Context;
-use model::{GuildId, ChannelId, UserId};
+use model::{ChannelId, GuildId, UserId};
pub(crate) struct Ratelimit {
pub delay: i64,
@@ -19,16 +19,18 @@ pub(crate) struct MemberRatelimit {
pub(crate) struct Bucket {
pub ratelimit: Ratelimit,
pub users: HashMap<u64, MemberRatelimit>,
- #[cfg(feature="cache")]
- pub check: Option<Box<Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static>>,
- #[cfg(not(feature="cache"))]
+ #[cfg(feature = "cache")]
+ pub check:
+ Option<Box<Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static>>,
+ #[cfg(not(feature = "cache"))]
pub checK: Option<Box<Fn(&mut Context, ChannelId, UserId) -> bool + 'static>>,
}
impl Bucket {
pub fn take(&mut self, user_id: u64) -> i64 {
let time = Utc::now().timestamp();
- let user = self.users.entry(user_id)
+ let user = self.users
+ .entry(user_id)
.or_insert_with(MemberRatelimit::default);
if let Some((timespan, limit)) = self.ratelimit.limit {
diff --git a/src/framework/command.rs b/src/framework/command.rs
index e75ee5e..1484891 100644
--- a/src/framework/command.rs
+++ b/src/framework/command.rs
@@ -1,12 +1,14 @@
use std::sync::Arc;
use super::Configuration;
-use ::client::Context;
-use ::model::{Message, Permissions};
+use client::Context;
+use model::{Message, Permissions};
use std::collections::HashMap;
pub type Check = Fn(&mut Context, &Message, &Arc<Command>) -> bool + 'static;
pub type Exec = Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static;
-pub type Help = Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) -> Result<(), String> + 'static;
+pub type Help = Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String])
+ -> Result<(), String>
+ + 'static;
pub type BeforeHook = Fn(&mut Context, &Message, &String) -> bool + 'static;
pub type AfterHook = Fn(&mut Context, &Message, &String, Result<(), String>) + 'static;
pub(crate) type InternalCommand = Arc<Command>;
@@ -67,7 +69,8 @@ pub struct Command {
impl Command {
pub fn new<F>(f: F) -> Self
- where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static {
+ where
+ F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, {
Command {
aliases: Vec::new(),
checks: Vec::default(),
diff --git a/src/framework/configuration.rs b/src/framework/configuration.rs
index c74739e..06e7e6a 100644
--- a/src/framework/configuration.rs
+++ b/src/framework/configuration.rs
@@ -1,9 +1,9 @@
use std::collections::HashSet;
use std::default::Default;
use super::command::PrefixCheck;
-use ::client::Context;
-use ::http;
-use ::model::{GuildId, Message, UserId};
+use client::Context;
+use http;
+use model::{GuildId, Message, UserId};
/// The configuration to use for a [`Framework`] associated with a [`Client`]
/// instance.
@@ -18,7 +18,7 @@ use ::model::{GuildId, Message, UserId};
/// ```rust,no_run
/// # use serenity::prelude::EventHandler;
/// struct Handler;
-///
+///
/// impl EventHandler for Handler {}
/// use serenity::Client;
/// use std::env;
@@ -215,7 +215,8 @@ impl Configuration {
/// })));
/// ```
pub fn dynamic_prefix<F>(mut self, dynamic_prefix: F) -> Self
- where F: Fn(&mut Context, &Message) -> Option<String> + Send + Sync + 'static {
+ where
+ F: Fn(&mut Context, &Message) -> Option<String> + Send + Sync + 'static, {
self.dynamic_prefix = Some(Box::new(dynamic_prefix));
self
@@ -267,7 +268,7 @@ impl Configuration {
if let Ok(current_user) = http::get_current_user() {
self.on_mention = Some(vec![
- format!("<@{}>", current_user.id), // Regular mention
+ format!("<@{}>", current_user.id), // Regular mention
format!("<@!{}>", current_user.id), // Nickname mention
]);
}
diff --git a/src/framework/create_command.rs b/src/framework/create_command.rs
index 4f3ab27..d97f6fa 100644
--- a/src/framework/create_command.rs
+++ b/src/framework/create_command.rs
@@ -1,10 +1,10 @@
-pub use super::{Command, CommandType, CommandGroup};
+pub use super::{Command, CommandGroup, CommandType};
use std::collections::HashMap;
use std::default::Default;
use std::sync::Arc;
-use ::client::Context;
-use ::model::{Message, Permissions};
+use client::Context;
+use model::{Message, Permissions};
pub struct CreateCommand(pub Command);
@@ -52,7 +52,8 @@ impl CreateCommand {
/// .desc("Replies to a ping with a pong")
/// .exec(ping)));
///
- /// fn ping(_context: &mut Context, message: &Message, _args: Vec<String>) -> Result<(), String> {
+ /// fn ping(_context: &mut Context, message: &Message, _args: Vec<String>) -> Result<(),
+ /// String> {
/// let _ = message.channel_id.say("Pong!");
///
/// Ok(())
@@ -64,7 +65,8 @@ impl CreateCommand {
/// }
/// ```
pub fn check<F>(mut self, check: F) -> Self
- where F: Fn(&mut Context, &Message, &Arc<Command>) -> bool + Send + Sync + 'static {
+ where
+ F: Fn(&mut Context, &Message, &Arc<Command>) -> bool + Send + Sync + 'static, {
self.0.checks.push(Box::new(check));
self
@@ -98,7 +100,8 @@ impl CreateCommand {
///
/// [`exec_str`]: #method.exec_str
pub fn exec<F>(mut self, func: F) -> Self
- where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
+ where
+ F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static, {
self.0.exec = CommandType::Basic(Box::new(func));
self
@@ -110,7 +113,12 @@ impl CreateCommand {
///
/// You can return `Err(string)` if there's an error.
pub fn exec_help<F>(mut self, f: F) -> Self
- where F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) -> Result<(), String> + Send + Sync + 'static {
+ where
+ F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String])
+ -> Result<(), String>
+ + Send
+ + Sync
+ + 'static, {
self.0.exec = CommandType::WithCommands(Box::new(f));
self
diff --git a/src/framework/create_group.rs b/src/framework/create_group.rs
index 88aa6ba..d5b68c3 100644
--- a/src/framework/create_group.rs
+++ b/src/framework/create_group.rs
@@ -1,11 +1,11 @@
-pub use ext::framework::command::{Command, CommandType, CommandGroup};
+pub use ext::framework::command::{Command, CommandGroup, CommandType};
pub(crate) use ext::framework::command::CommandOrAlias;
pub use ext::framework::create_command::CreateCommand;
use std::default::Default;
use std::sync::Arc;
-use ::client::Context;
-use ::model::Message;
+use client::Context;
+use model::Message;
/// Used to create command groups
///
@@ -27,18 +27,26 @@ pub struct CreateGroup(pub CommandGroup);
impl CreateGroup {
/// Adds a command to group.
pub fn command<F>(mut self, command_name: &str, f: F) -> Self
- where F: FnOnce(CreateCommand) -> CreateCommand {
+ where
+ F: FnOnce(CreateCommand) -> CreateCommand, {
let cmd = f(CreateCommand(Command::default())).0;
for n in &cmd.aliases {
if let Some(ref prefix) = self.0.prefix {
- self.0.commands.insert(format!("{} {}", prefix, n.to_owned()), CommandOrAlias::Alias(format!("{} {}", prefix, command_name.to_string())));
+ self.0
+ .commands
+ .insert(format!("{} {}", prefix, n.to_owned()),
+ CommandOrAlias::Alias(format!("{} {}",
+ prefix,
+ command_name.to_string())));
} else {
- self.0.commands.insert(n.to_owned(), CommandOrAlias::Alias(command_name.to_string()));
+ self.0.commands.insert(n.to_owned(),
+ CommandOrAlias::Alias(command_name.to_string()));
}
}
- self.0.commands.insert(command_name.to_owned(), CommandOrAlias::Command(Arc::new(cmd)));
+ self.0.commands.insert(command_name.to_owned(),
+ CommandOrAlias::Command(Arc::new(cmd)));
self
}
@@ -46,10 +54,13 @@ impl CreateGroup {
/// Adds a command to group with simplified API.
/// You can return Err(string) if there's an error.
pub fn on<F>(mut self, command_name: &str, f: F) -> Self
- where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
+ where
+ F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static, {
let cmd = Arc::new(Command::new(f));
- self.0.commands.insert(command_name.to_owned(), CommandOrAlias::Command(cmd));
+ self.0
+ .commands
+ .insert(command_name.to_owned(), CommandOrAlias::Command(cmd));
self
}
diff --git a/src/framework/help_commands.rs b/src/framework/help_commands.rs
index d589ded..7f863b4 100644
--- a/src/framework/help_commands.rs
+++ b/src/framework/help_commands.rs
@@ -28,16 +28,13 @@ use std::sync::Arc;
use std::fmt::Write;
use super::command::InternalCommand;
use super::{Command, CommandGroup, CommandOrAlias};
-use ::client::Context;
-use ::model::{ChannelId, Message};
-use ::utils::Colour;
+use client::Context;
+use model::{ChannelId, Message};
+use utils::Colour;
fn error_embed(channel_id: &ChannelId, input: &str) {
- let _ = channel_id
- .send_message(|m| m
- .embed(|e| e
- .colour(Colour::dark_red())
- .description(input)));
+ let _ =
+ channel_id.send_message(|m| m.embed(|e| e.colour(Colour::dark_red()).description(input)));
}
fn remove_aliases(cmds: &HashMap<String, CommandOrAlias>) -> HashMap<&String, &InternalCommand> {
@@ -74,7 +71,8 @@ fn remove_aliases(cmds: &HashMap<String, CommandOrAlias>) -> HashMap<&String, &I
pub fn with_embeds(_: &mut Context,
msg: &Message,
groups: HashMap<String, Arc<CommandGroup>>,
- args: &[String]) -> Result<(), String> {
+ args: &[String])
+ -> Result<(), String> {
if !args.is_empty() {
let name = args.join(" ");
@@ -97,7 +95,7 @@ pub fn with_embeds(_: &mut Context,
error_embed(&msg.channel_id, &format!("Did you mean \"{}\"?", name));
return Ok(());
- }
+ },
}
}
}
@@ -111,28 +109,27 @@ pub fn with_embeds(_: &mut Context,
let _ = msg.channel_id.send_message(|m| {
m.embed(|e| {
- let mut embed = e.colour(Colour::rosewater())
- .title(command_name);
+ let mut embed = e.colour(Colour::rosewater()).title(command_name);
if let Some(ref desc) = command.desc {
embed = embed.description(desc);
}
if let Some(ref usage) = command.usage {
- embed = embed.field(|f| f
- .name("Usage")
- .value(&format!("`{} {}`", command_name, usage)));
+ embed = embed.field(|f| {
+ f.name("Usage")
+ .value(&format!("`{} {}`", command_name, usage))
+ });
}
if let Some(ref example) = command.example {
- embed = embed.field(|f| f
- .name("Sample usage")
- .value(&format!("`{} {}`", command_name, example)));
+ embed = embed.field(|f| {
+ f.name("Sample usage")
+ .value(&format!("`{} {}`", command_name, example))
+ });
}
if group_name != "Ungrouped" {
- embed = embed.field(|f| f
- .name("Group")
- .value(&group_name));
+ embed = embed.field(|f| f.name("Group").value(&group_name));
}
let available = if command.dm_only {
@@ -143,9 +140,7 @@ pub fn with_embeds(_: &mut Context,
"In DM and guilds"
};
- embed = embed.field(|f| f
- .name("Available")
- .value(available));
+ embed = embed.field(|f| f.name("Available").value(available));
embed
})
@@ -161,8 +156,8 @@ pub fn with_embeds(_: &mut Context,
return Ok(());
}
- let _ = msg.channel_id.send_message(|m| m
- .embed(|mut e| {
+ let _ = msg.channel_id.send_message(|m| {
+ m.embed(|mut e| {
e = e.colour(Colour::rosewater())
.description("To get help with an individual command, pass its \
name as an argument to this command.");
@@ -200,7 +195,8 @@ pub fn with_embeds(_: &mut Context,
}
e
- }));
+ })
+ });
Ok(())
}
@@ -227,7 +223,8 @@ pub fn with_embeds(_: &mut Context,
pub fn plain(_: &mut Context,
msg: &Message,
groups: HashMap<String, Arc<CommandGroup>>,
- args: &[String]) -> Result<(), String> {
+ args: &[String])
+ -> Result<(), String> {
if !args.is_empty() {
let name = args.join(" ");
@@ -241,7 +238,7 @@ pub fn plain(_: &mut Context,
command_name.to_owned()
};
- if name == with_prefix || name == *command_name {
+ if name == with_prefix || name == *command_name {
match *command {
CommandOrAlias::Command(ref cmd) => {
found = Some((command_name, cmd));
@@ -249,7 +246,7 @@ pub fn plain(_: &mut Context,
CommandOrAlias::Alias(ref name) => {
let _ = msg.channel_id.say(&format!("Did you mean {:?}?", name));
return Ok(());
- }
+ },
}
}
}
@@ -280,12 +277,12 @@ pub fn plain(_: &mut Context,
result.push_str("**Available:** ");
result.push_str(if command.dm_only {
- "Only in DM"
- } else if command.guild_only {
- "Only in guilds"
- } else {
- "In DM and guilds"
- });
+ "Only in DM"
+ } else if command.guild_only {
+ "Only in guilds"
+ } else {
+ "In DM and guilds"
+ });
result.push_str("\n");
let _ = msg.channel_id.say(&result);
@@ -294,7 +291,8 @@ pub fn plain(_: &mut Context,
}
}
- let _ = msg.channel_id.say(&format!("**Error**: Command `{}` not found.", name));
+ let _ = msg.channel_id
+ .say(&format!("**Error**: Command `{}` not found.", name));
return Ok(());
}
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 }
+}