diff options
| author | Zeyla Hellyer <[email protected]> | 2018-02-04 07:50:53 -0800 |
|---|---|---|
| committer | Zeyla Hellyer <[email protected]> | 2018-02-04 07:54:31 -0800 |
| commit | a9966371def331cd848f642e222627ee9decf354 (patch) | |
| tree | 316c75854ddea79230f98b66708c3f815b836227 /examples/01_basic_ping_bot | |
| parent | Partially revert the video url change (diff) | |
| download | serenity-a9966371def331cd848f642e222627ee9decf354.tar.xz serenity-a9966371def331cd848f642e222627ee9decf354.zip | |
Rewrite the library to use Futures
Rewrites the library to use Futures. This rewrites all of the gateway,
client, cache, most model methods, HTTP, and in a later commit the
framework and voice.
HTTP has been mostly rewritten to be ergonomic so that it can be used by
the user, and has been upgraded to hyper v0.11.
The gateway now uses `tokio-tungstenite` v0.4.
The client isn't yet in a working state.
The models now have a `client` optionally attached to them to make use
of `http` and `cache`-utilizing methods. The client isn't needed, in the
case that someone is using the library just to deserialize models.
The cache is now built around `Rc`s and `RefCell`s, instead of `Arc`s
and `RwLock`s.
Refer to example 01 for a working example. Much of the library still
doesn't work.
Diffstat (limited to 'examples/01_basic_ping_bot')
| -rw-r--r-- | examples/01_basic_ping_bot/Cargo.toml | 2 | ||||
| -rw-r--r-- | examples/01_basic_ping_bot/src/main.rs | 90 |
2 files changed, 49 insertions, 43 deletions
diff --git a/examples/01_basic_ping_bot/Cargo.toml b/examples/01_basic_ping_bot/Cargo.toml index 30ce62c..7c30ce7 100644 --- a/examples/01_basic_ping_bot/Cargo.toml +++ b/examples/01_basic_ping_bot/Cargo.toml @@ -4,4 +4,6 @@ version = "0.1.0" authors = ["my name <[email protected]>"] [dependencies] +futures-await = "~0.1" serenity = { path = "../../", default-features = true } +tokio-core = "~0.1" diff --git a/examples/01_basic_ping_bot/src/main.rs b/examples/01_basic_ping_bot/src/main.rs index 3bccb74..7d858f1 100644 --- a/examples/01_basic_ping_bot/src/main.rs +++ b/examples/01_basic_ping_bot/src/main.rs @@ -1,56 +1,60 @@ +#![feature(proc_macro, conservative_impl_trait, generators)] + +extern crate futures_await as futures; extern crate serenity; +extern crate tokio_core; -use serenity::prelude::*; -use serenity::model::channel::Message; -use serenity::model::gateway::Ready; +use futures::prelude::*; +use serenity::gateway::Shard; +use serenity::model::event::{Event, GatewayEvent}; +use serenity::model::gateway::Game; +use serenity::model::user::OnlineStatus; +use std::error::Error; use std::env; +use tokio_core::reactor::{Core, Handle}; -struct Handler; - -impl EventHandler for Handler { - // Set a handler for the `message` event - so that whenever a new message - // is received - the closure (or function) passed will be called. - // - // Event handlers are dispatched through a threadpool, and so multiple - // events can be dispatched simultaneously. - fn message(&self, _: Context, msg: Message) { - if msg.content == "!ping" { - // Sending a message can fail, due to a network error, an - // authentication error, or lack of permissions to post in the - // channel, so log to stdout when some error happens, with a - // description of it. - if let Err(why) = msg.channel_id.say("Pong!") { - println!("Error sending message: {:?}", why); - } - } - } +fn main() { + let mut core = Core::new().expect("Error creating event loop"); + let future = try_main(core.handle()); - // Set a handler to be called on the `ready` event. This is called when a - // shard is booted, and a READY payload is sent by Discord. This payload - // contains data like the current user's guild Ids, current user data, - // private channels, and more. - // - // In this case, just print what the current user's username is. - fn ready(&self, _: Context, ready: Ready) { - println!("{} is connected!", ready.user.name); - } + core.run(future).expect("Error running event loop"); } -fn main() { +#[async] +fn try_main(handle: Handle) -> Result<(), Box<Error + 'static>> { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); - // Create a new instance of the Client, logging in as a bot. This will - // automatically prepend your bot token with "Bot ", which is a requirement - // by Discord for bot users. - let mut client = Client::new(&token, Handler).expect("Err creating client"); - - // Finally, start a single shard, and start listening to events. - // - // Shards will automatically attempt to reconnect, and will perform - // exponential backoff until it reconnects. - if let Err(why) = client.start() { - println!("Client error: {:?}", why); + // Create a new shard, specifying the token, the ID of the shard (0 of 1), + // and a handle to the event loop + let mut shard = await!(Shard::new(token, [0, 1], handle))?; + + // Loop over websocket messages. + #[async] + for message in shard.messages() { + // Parse the websocket message into a serenity GatewayEvent. + let event = shard.parse(message)?; + + // Have the shard process the WebSocket event, in case it needs to + // mutate its state, send a packet, etc. + shard.process(&event); + + // Now you can do whatever you want with the event. + match event { + GatewayEvent::Dispatch(_, Event::MessageCreate(ev)) => { + if ev.message.content == "!ping" { + println!("Pong!"); + } + }, + GatewayEvent::Dispatch(_, Event::Ready(_)) => { + println!("Connected to Discord!"); + }, + _ => { + // Ignore all other messages. + }, + } } + + Ok(()) } |