Skip to content

Commit

Permalink
Add 'wait' parameter to http::execute_webhook
Browse files Browse the repository at this point in the history
The 'wait' parameter allows you to specify waiting for the Message to be
sent prior to receiving a response, which will have Discord include the
JSON representation of the Message in the body.
  • Loading branch information
Zeyla Hellyer committed Jun 20, 2017
1 parent 515fc76 commit dc73d1a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 15 deletions.
10 changes: 5 additions & 5 deletions src/builder/execute_webhook.rs
Expand Up @@ -44,7 +44,7 @@ use ::internal::prelude::*;
/// .name("Rust by Example")
/// .value("A collection of Rust examples on topics, useable in-browser")));
///
/// let _ = webhook.execute(|w| w
/// let _ = webhook.execute(false, |w| w
/// .content("Here's some information on Rust:")
/// .embeds(vec![website, resources]));
/// ```
Expand All @@ -69,7 +69,7 @@ impl ExecuteWebhook {
/// #
/// let avatar_url = "https://i.imgur.com/KTs6whd.jpg";
///
/// let _ = webhook.execute(|w| w
/// let _ = webhook.execute(false, |w| w
/// .avatar_url(avatar_url)
/// .content("Here's a webhook"));
/// ```
Expand All @@ -93,7 +93,7 @@ impl ExecuteWebhook {
/// #
/// # let webhook = rest::get_webhook_with_token(0, "").unwrap();
/// #
/// if let Err(why) = webhook.execute(|w| w.content("foo")) {
/// if let Err(why) = webhook.execute(false, |w| w.content("foo")) {
/// println!("Err sending webhook: {:?}", why);
/// }
/// ```
Expand Down Expand Up @@ -135,7 +135,7 @@ impl ExecuteWebhook {
/// #
/// # let webhook = rest::get_webhook_with_token(0, "").unwrap();
/// #
/// if let Err(why) = webhook.execute(|w| w.content("hello").tts(true)) {
/// if let Err(why) = webhook.execute(false, |w| w.content("hello").tts(true)) {
/// println!("Err sending webhook: {:?}", why);
/// }
/// ```
Expand All @@ -156,7 +156,7 @@ impl ExecuteWebhook {
/// #
/// # let webhook = rest::get_webhook_with_token(0, "").unwrap();
/// #
/// if let Err(why) = webhook.execute(|w| w.content("hello").username("hakase")) {
/// if let Err(why) = webhook.execute(false, |w| w.content("hello").username("hakase")) {
/// println!("Err sending webhook: {:?}", why);
/// }
/// ```
Expand Down
27 changes: 21 additions & 6 deletions src/http/mod.rs
Expand Up @@ -37,7 +37,9 @@ use hyper::client::{
Response as HyperResponse,
Request,
};
use hyper::header::ContentType;
use hyper::method::Method;
use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper::net::HttpsConnector;
use hyper::{Error as HyperError, Result as HyperResult, Url, header};
use hyper_native_tls::NativeTlsClient;
Expand Down Expand Up @@ -803,28 +805,41 @@ pub fn edit_webhook_with_token(webhook_id: u64, token: &str, map: &JsonMap) -> R
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
/// let map = ObjectBuilder::new().insert("content", "test").build();
///
/// let message = match http::execute_webhook(id, token, map) {
/// Ok(message) => message,
/// let message = match http::execute_webhook(id, token, true, map) {
/// Ok(Some(message)) => message,
/// Ok(None) => {
/// println!("Expected a webhook message");
///
/// return;
/// },
/// Err(why) => {
/// println!("Error executing webhook: {:?}", why);
///
/// return;
/// },
/// };
/// ```
///
/// [`Channel`]: ../model/enum.Channel.html
/// [`Message`]: ../model/struct.Message.html
/// [Discord docs]: https://discordapp.com/developers/docs/resources/webhook#querystring-params
pub fn execute_webhook(webhook_id: u64, token: &str, map: &JsonMap) -> Result<Message> {
pub fn execute_webhook(webhook_id: u64, token: &str, wait: bool, map: &JsonMap)
-> Result<Option<Message>> {
let body = serde_json::to_string(map)?;

let client = request_client!();

let response = retry(|| client
.post(&format!(api!("/webhooks/{}/{}"), webhook_id, token))
.body(&body))
.post(&format!(api!("/webhooks/{}/{}?wait={}"), webhook_id, token, wait))
.body(&body)
.header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))))
.map_err(Error::Hyper)?;

serde_json::from_reader::<HyperResponse, Message>(response).map_err(From::from)
if response.status == StatusCode::NoContent {
return Ok(None);
}

serde_json::from_reader::<HyperResponse, Message>(response).map(Some).map_err(From::from)
}

/// Gets the active maintenances from Discord's Status API.
Expand Down
9 changes: 5 additions & 4 deletions src/model/webhook.rs
Expand Up @@ -148,7 +148,7 @@ impl Webhook {
/// let mut webhook = http::get_webhook_with_token(id, token)
/// .expect("valid webhook");
///
/// let _ = webhook.execute(|w| w.content("test")).expect("Error executing");
/// let _ = webhook.execute(false, |w| w.content("test")).expect("Error executing");
/// ```
///
/// Execute a webhook with message content of `test`, overriding the
Expand All @@ -171,15 +171,16 @@ impl Webhook {
/// thread safety.")
/// .url("https://rust-lang.org"));
///
/// let _ = webhook.execute(|w| w
/// let _ = webhook.execute(false, |w| w
/// .content("test")
/// .username("serenity")
/// .embeds(vec![embed]))
/// .expect("Error executing");
/// ```
#[inline]
pub fn execute<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(&self, f: F) -> Result<Message> {
http::execute_webhook(self.id.0, &self.token, &f(ExecuteWebhook::default()).0)
pub fn execute<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(&self, wait: bool, f: F)
-> Result<Option<Message>> {
http::execute_webhook(self.id.0, &self.token, wait, &f(ExecuteWebhook::default()).0)
}

/// Retrieves the latest information about the webhook, editing the
Expand Down

0 comments on commit dc73d1a

Please sign in to comment.