aboutsummaryrefslogtreecommitdiff
path: root/src/client
diff options
context:
space:
mode:
authoracdenisSK <[email protected]>2017-07-22 16:59:10 +0200
committeracdenisSK <[email protected]>2017-07-22 16:59:10 +0200
commit2b053ea007d6ca9cc820cb910597e8b5dad89d70 (patch)
treec0664957758043b80fc7e40d9acc7923da53d3c1 /src/client
parentRemove the uneccessary function and `Send + Sync` bounds (diff)
downloadserenity-2b053ea007d6ca9cc820cb910597e8b5dad89d70.tar.xz
serenity-2b053ea007d6ca9cc820cb910597e8b5dad89d70.zip
Fix #130
Removed action support from the builtin one as well, due to it adding some uneccassery complexity and it being only asked upon by one user
Diffstat (limited to 'src/client')
-rw-r--r--src/client/dispatch.rs113
-rw-r--r--src/client/mod.rs80
2 files changed, 102 insertions, 91 deletions
diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs
index 68190d1..6c732d7 100644
--- a/src/client/dispatch.rs
+++ b/src/client/dispatch.rs
@@ -7,12 +7,12 @@ use super::Context;
use typemap::ShareMap;
use ::gateway::Shard;
use ::model::event::Event;
-use ::model::{Message, Reaction, GuildId, Channel};
+use ::model::{Message, GuildId, Channel};
use chrono::{Utc, Timelike};
use tokio_core::reactor::Handle;
#[cfg(feature="framework")]
-use ::ext::framework::{Framework, ReactionAction};
+use ::ext::framework::Framework;
#[cfg(feature="cache")]
use super::CACHE;
@@ -61,66 +61,37 @@ fn context(conn: &Arc<Mutex<Shard>>,
Context::new(conn.clone(), data.clone())
}
-// Heck you macro hygiene.
-macro_rules! impl_reaction_events {
- (($event:ident, $conn:ident, $data:ident, $event_handler:ident, $framework:ident, $handle:ident), $type_of_action:ident, $dispatch_name:ident) => {
- let context = context($conn, $data);
- let framework = $framework.lock().unwrap();
-
- if framework.initialized {
- $dispatch_name(context.clone(),
- $event.reaction.clone(),
- $event_handler,
- $handle);
-
- let res = framework.reaction_actions
- .iter()
- .find(|&(ra, _)| {
- if let ReactionAction::$type_of_action(ref kind) = *ra {
- *kind == $event.reaction.emoji
- } else {
- false
- }
- });
-
- if let Some((_, f)) = res {
- f(context, $event.reaction.message_id, $event.reaction.channel_id);
- }
- } else {
- $dispatch_name(context, $event.reaction, $event_handler, $handle);
- }
- }
-}
-
#[cfg(feature="framework")]
pub fn dispatch<H: EventHandler + 'static>(event: Event,
conn: &Arc<Mutex<Shard>>,
- framework: &Arc<sync::Mutex<Framework>>,
+ framework: &Arc<sync::Mutex<Option<Box<Framework>>>>,
data: &Arc<Mutex<ShareMap>>,
event_handler: &Arc<H>,
tokio_handle: &Handle) {
match event {
Event::MessageCreate(event) => {
let context = context(conn, data);
- let mut framework = framework.lock().unwrap();
-
- if framework.initialized {
+ if let Some(ref mut framework) = *framework.lock().unwrap() {
+ if framework.initialized() {
+ dispatch_message(context.clone(),
+ event.message.clone(),
+ event_handler,
+ tokio_handle);
+
+ framework.dispatch(context, event.message, tokio_handle);
+ } else {
+ dispatch_message(context.clone(),
+ event.message.clone(),
+ event_handler,
+ tokio_handle);
+ }
+ } else {
dispatch_message(context.clone(),
event.message.clone(),
event_handler,
tokio_handle);
-
- framework.dispatch(context, event.message, tokio_handle);
- } else {
- dispatch_message(context, event.message, event_handler, tokio_handle);
}
},
- Event::ReactionAdd(event) => {
- impl_reaction_events!((event, conn, data, event_handler, framework, tokio_handle), Add, dispatch_reaction_add);
- },
- Event::ReactionRemove(event) => {
- impl_reaction_events!((event, conn, data, event_handler, framework, tokio_handle), Remove, dispatch_reaction_remove);
- },
other => handle_event(other, conn, data, event_handler, tokio_handle),
}
}
@@ -139,14 +110,6 @@ pub fn dispatch<H: EventHandler + 'static>(event: Event,
event_handler,
tokio_handle);
},
- Event::ReactionAdd(event) => {
- let context = context(conn, data);
- dispatch_reaction_add(context, event.reaction, tokio_handle);
- },
- Event::ReactionRemove(event) => {
- let context = context(conn, data);
- dispatch_reaction_remove(context, event.reaction, tokio_handle);
- },
other => handle_event(other, conn, data, event_handler, tokio_handle),
}
}
@@ -169,28 +132,6 @@ fn dispatch_message<H: EventHandler + 'static>(context: Context,
});
}
-fn dispatch_reaction_add<H: EventHandler + 'static>(context: Context,
- reaction: Reaction,
- event_handler: &Arc<H>,
- tokio_handle: &Handle) {
- let h = event_handler.clone();
- tokio_handle.spawn_fn(move || {
- h.on_reaction_add(context, reaction);
- Ok(())
- });
-}
-
-fn dispatch_reaction_remove<H: EventHandler + 'static>(context: Context,
- reaction: Reaction,
- event_handler: &Arc<H>,
- tokio_handle: &Handle) {
- let h = event_handler.clone();
- tokio_handle.spawn_fn(move || {
- h.on_reaction_remove(context, reaction);
- Ok(())
- });
-}
-
#[allow(cyclomatic_complexity, unused_assignments, unused_mut)]
fn handle_event<H: EventHandler + 'static>(event: Event,
conn: &Arc<Mutex<Shard>>,
@@ -603,8 +544,22 @@ fn handle_event<H: EventHandler + 'static>(event: Event,
},
// Already handled by the framework check macro
- Event::ReactionAdd(_) => {},
- Event::ReactionRemove(_) => {},
+ Event::ReactionAdd(event) => {
+ let h = event_handler.clone();
+ let context = context(conn, data);
+ tokio_handle.spawn_fn(move || {
+ h.on_reaction_add(context, event.reaction);
+ Ok(())
+ });
+ },
+ Event::ReactionRemove(event) => {
+ let h = event_handler.clone();
+ let context = context(conn, data);
+ tokio_handle.spawn_fn(move || {
+ h.on_reaction_remove(context, event.reaction);
+ Ok(())
+ });
+ },
Event::ReactionRemoveAll(event) => {
let context = context(conn, data);
diff --git a/src/client/mod.rs b/src/client/mod.rs
index 93e09ce..6241b5b 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -51,7 +51,7 @@ use ::internal::prelude::*;
use ::internal::ws_impl::ReceiverExt;
use ::model::event::*;
-#[cfg(feature="framework")]
+#[cfg(any(feature="framework", feature="builtin_framework"))]
use ::framework::Framework;
static HANDLE_STILL: AtomicBool = ATOMIC_BOOL_INIT;
@@ -193,7 +193,7 @@ pub struct Client<H: EventHandler + 'static> {
/// [`on_ready`]: #method.on_ready
event_handler: Arc<H>,
#[cfg(feature="framework")]
- framework: Arc<sync::Mutex<Framework>>,
+ framework: Arc<sync::Mutex<Option<Box<Framework>>>>,
token: Arc<sync::Mutex<String>>,
}
@@ -241,7 +241,7 @@ impl<H: EventHandler + 'static> Client<H> {
Client {
data: Arc::new(Mutex::new(ShareMap::custom())),
event_handler: Arc::new(handler),
- framework: Arc::new(sync::Mutex::new(Framework::default())),
+ framework: Arc::new(sync::Mutex::new(None)),
token: locked,
}
} else {
@@ -268,6 +268,8 @@ impl<H: EventHandler + 'static> Client<H> {
/// # use serenity::prelude::EventHandler;
/// # use std::error::Error;
/// #
+ /// use serenity::framework::BuiltinFramework;
+ ///
/// struct Handler;
///
/// impl EventHandler for Handler {}
@@ -276,7 +278,7 @@ impl<H: EventHandler + 'static> Client<H> {
/// use std::env;
///
/// let mut client = Client::new(&env::var("DISCORD_TOKEN")?, Handler);
- /// client.with_framework(|f| f
+ /// client.with_framework(BuiltinFramework::new()
/// .configure(|c| c.prefix("~"))
/// .command("ping", |c| c.exec_str("Pong!")));
/// # Ok(())
@@ -286,16 +288,69 @@ impl<H: EventHandler + 'static> Client<H> {
/// # try_main().unwrap();
/// # }
/// ```
+ ///
+ /// Using your own framework:
+ ///
+ /// ```rust,ignore
+ /// # use serenity::prelude::EventHandler;
+ /// # use std::error::Error;
+ /// #
+ /// use serenity::framework::Framework;
+ /// use serenity::client::Context;
+ /// use serenity::model::*;
+ /// use tokio_core::reactor::Handle;
+ /// use std::collections::HashMap;
+ ///
+ ///
+ /// struct MyFramework {
+ /// commands: HashMap<String, Box<Fn(Message, Vec<String>)>>,
+ /// }
+ ///
+ /// impl Framework for MyFramework {
+ /// fn dispatch(&mut self, _: Context, msg: Message, tokio_handle: &Handle) {
+ /// let args = msg.content.split_whitespace();
+ /// let command = match args.next() {
+ /// Some(command) => {
+ /// if !command.starts_with('*') { return; }
+ /// command
+ /// },
+ /// None => return,
+ /// };
+ ///
+ /// let command = match self.commands.get(&command) {
+ /// Some(command) => command, None => return,
+ /// };
+ ///
+ /// tokio_handle.spawn_fn(move || { (command)(msg, args); Ok() });
+ /// }
+ /// }
+ ///
+ /// struct Handler;
+ ///
+ /// impl EventHandler for Handler {}
+ ///
+ ///
+ /// # fn try_main() -> Result<(), Box<Error>> {
+ /// use serenity::Client;
+ /// use std::env;
///
+ /// let mut client = Client::new(&env::var("DISCORD_TOKEN")?, Handler);
+ /// client.with_framework(MyFramework { commands: { let mut map = HashMap::new(); map.insert("ping".to_string(), Box::new(|msg, _| msg.channel_id.say("pong!"))); map }});
+ /// # Ok(())
+ /// # }
+ /// #
+ /// # fn main() {
+ /// # try_main().unwrap();
+ /// # }
+ /// ```
/// Refer to the documentation for the `framework` module for more in-depth
/// information.
///
/// [`on_message`]: #method.on_message
/// [framework docs]: ../framework/index.html
#[cfg(feature="framework")]
- pub fn with_framework<F>(&mut self, f: F)
- where F: FnOnce(Framework) -> Framework + Send + Sync + 'static {
- self.framework = Arc::new(sync::Mutex::new(f(Framework::default())));
+ pub fn with_framework<F: Framework + 'static>(&mut self, f: F) {
+ self.framework = Arc::new(sync::Mutex::new(Some(Box::new(f))));
}
/// Establish the connection and start listening for events.
@@ -631,13 +686,13 @@ impl<H: EventHandler + 'static> Client<H> {
// Update the framework's current user if the feature is enabled.
//
// This also acts as a form of check to ensure the token is correct.
- #[cfg(feature="framework")]
+ #[cfg(all(feature="builtin_framework", feature="framework"))]
{
let user = http::get_current_user()?;
- self.framework.lock()
- .unwrap()
- .update_current_user(user.id, user.bot);
+ if let Some(ref mut framework) = *self.framework.lock().unwrap() {
+ framework.update_current_user(user.id, user.bot);
+ }
}
let gateway_url = Arc::new(sync::Mutex::new(url));
@@ -678,6 +733,7 @@ impl<H: EventHandler + 'static> Client<H> {
shard: shard,
shard_info: shard_info,
token: self.token.clone(),
+ _pd: std::marker::PhantomData,
}
}};
@@ -718,7 +774,7 @@ struct BootInfo {
struct MonitorInfo<H: EventHandler + 'static> {
data: Arc<Mutex<ShareMap>>,
event_handler: Arc<H>,
- framework: Arc<sync::Mutex<Framework>>,
+ framework: Arc<sync::Mutex<Option<Box<Framework>>>>,
gateway_url: Arc<sync::Mutex<String>>,
shard: Arc<Mutex<Shard>>,
shard_info: [u64; 2],