diff options
Diffstat (limited to 'src/builder')
| -rw-r--r-- | src/builder/create_embed.rs | 192 | ||||
| -rw-r--r-- | src/builder/create_invite.rs | 47 | ||||
| -rw-r--r-- | src/builder/create_message.rs | 22 | ||||
| -rw-r--r-- | src/builder/edit_channel.rs | 20 | ||||
| -rw-r--r-- | src/builder/edit_guild.rs | 26 | ||||
| -rw-r--r-- | src/builder/edit_member.rs | 20 | ||||
| -rw-r--r-- | src/builder/edit_profile.rs | 29 | ||||
| -rw-r--r-- | src/builder/edit_role.rs | 48 | ||||
| -rw-r--r-- | src/builder/execute_webhook.rs | 33 | ||||
| -rw-r--r-- | src/builder/get_messages.rs | 12 | ||||
| -rw-r--r-- | src/builder/mod.rs | 2 |
11 files changed, 175 insertions, 276 deletions
diff --git a/src/builder/create_embed.rs b/src/builder/create_embed.rs index b38984c..ae0975b 100644 --- a/src/builder/create_embed.rs +++ b/src/builder/create_embed.rs @@ -16,11 +16,13 @@ //! [here]: https://discordapp.com/developers/docs/resources/channel#embed-object use chrono::{DateTime, TimeZone}; +use internal::prelude::*; +use model::Embed; use serde_json::Value; +use std::collections::HashMap; use std::default::Default; use std::fmt::Display; -use internal::prelude::*; -use model::Embed; +use utils; #[cfg(feature = "utils")] use utils::Colour; @@ -37,7 +39,7 @@ use utils::Colour; /// [`Embed`]: ../model/struct.Embed.html /// [`ExecuteWebhook::embeds`]: struct.ExecuteWebhook.html#method.embeds #[derive(Clone, Debug)] -pub struct CreateEmbed(pub Map<String, Value>); +pub struct CreateEmbed(pub HashMap<&'static str, Value>); impl CreateEmbed { /// Set the author of the embed. @@ -48,9 +50,9 @@ impl CreateEmbed { /// [`CreateEmbedAuthor`]: struct.CreateEmbedAuthor.html pub fn author<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedAuthor) -> CreateEmbedAuthor { - let author = f(CreateEmbedAuthor::default()).0; + let map = utils::hashmap_to_json_map(f(CreateEmbedAuthor::default()).0); - self.0.insert("author".to_string(), Value::Object(author)); + self.0.insert("author", Value::Object(map)); CreateEmbed(self.0) } @@ -68,7 +70,7 @@ impl CreateEmbed { #[cfg(feature = "utils")] pub fn colour<C: Into<Colour>>(mut self, colour: C) -> Self { self.0.insert( - "color".to_string(), + "color", Value::Number(Number::from(u64::from(colour.into().0))), ); @@ -88,7 +90,7 @@ impl CreateEmbed { #[cfg(not(feature = "utils"))] pub fn colour(mut self, colour: u32) -> Self { self.0 - .insert("color".to_string(), Value::Number(Number::from(colour))); + .insert("color", Value::Number(Number::from(colour))); CreateEmbed(self.0) } @@ -98,8 +100,8 @@ impl CreateEmbed { /// **Note**: This can't be longer than 2048 characters. pub fn description<D: Display>(mut self, description: D) -> Self { self.0.insert( - "description".to_string(), - Value::String(format!("{}", description)), + "description", + Value::String(description.to_string()), ); CreateEmbed(self.0) @@ -115,54 +117,35 @@ impl CreateEmbed { /// name and 1024 in a field value and a field is inline by default. /// /// [`CreateEmbedField`]: struct.CreateEmbedField.html - pub fn field<F>(mut self, f: F) -> Self - where F: FnOnce(CreateEmbedField) -> CreateEmbedField { - let field = f(CreateEmbedField::default()).0; - + pub fn field<T, U>(mut self, name: T, value: U, inline: bool) -> Self + where T: Display, U: Display { { - let key = "fields".to_string(); - - let entry = self.0.remove(&key).unwrap_or_else(|| Value::Array(vec![])); - let mut arr = match entry { - Value::Array(inner) => inner, - _ => { - // The type of `entry` should always be a `Value::Array`. - // - // Theoretically this never happens, but you never know. - // - // In the event that it does, just return the current value. - return CreateEmbed(self.0); - }, - }; - arr.push(Value::Object(field)); - - self.0.insert("fields".to_string(), Value::Array(arr)); + let entry = self.0 + .entry("fields") + .or_insert_with(|| Value::Array(vec![])); + + if let Value::Array(ref mut inner) = *entry { + inner.push(json!({ + "inline": inline, + "name": name.to_string(), + "value": value.to_string(), + })); + } } - CreateEmbed(self.0) + self } /// Adds multiple fields at once. - pub fn fields<It: IntoIterator<Item=CreateEmbedField>>(mut self, fields: It) -> Self { - let fields = fields - .into_iter() - .map(|m| Value::Object(m.0)) - .collect::<Vec<Value>>(); - - { - let key = "fields".to_string(); - - let entry = self.0.remove(&key).unwrap_or_else(|| Value::Array(vec![])); - let mut arr = match entry { - Value::Array(inner) => inner, - _ => return CreateEmbed(self.0), - }; - arr.extend(fields); - - self.0.insert("fields".to_string(), Value::Array(arr)); + pub fn fields<T, U, It>(mut self, fields: It) -> Self + where It: IntoIterator<Item=(T, U, bool)>, + T: Display, + U: Display { + for field in fields { + self = self.field(field.0.to_string(), field.1.to_string(), field.2); } - CreateEmbed(self.0) + self } /// Set the footer of the embed. @@ -174,8 +157,9 @@ impl CreateEmbed { pub fn footer<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedFooter) -> CreateEmbedFooter { let footer = f(CreateEmbedFooter::default()).0; + let map = utils::hashmap_to_json_map(footer); - self.0.insert("footer".to_string(), Value::Object(footer)); + self.0.insert("footer", Value::Object(map)); CreateEmbed(self.0) } @@ -186,7 +170,7 @@ impl CreateEmbed { "url": url.to_string() }); - self.0.insert("image".to_string(), image); + self.0.insert("image", image); CreateEmbed(self.0) } @@ -197,7 +181,7 @@ impl CreateEmbed { "url": url.to_string(), }); - self.0.insert("thumbnail".to_string(), thumbnail); + self.0.insert("thumbnail", thumbnail); CreateEmbed(self.0) } @@ -223,8 +207,9 @@ impl CreateEmbed { /// # use serenity::model::*; /// # /// struct Handler; + /// /// impl EventHandler for Handler { - /// fn on_message(&self, _: Context, msg: Message) { + /// fn message(&self, _: Context, msg: Message) { /// if msg.content == "~embed" { /// let _ = msg.channel_id.send_message(|m| m /// .embed(|e| e @@ -234,7 +219,9 @@ impl CreateEmbed { /// } /// } /// - /// let mut client = Client::new("token", Handler); client.start().unwrap(); + /// let mut client = Client::new("token", Handler).unwrap(); + /// + /// client.start().unwrap(); /// ``` /// /// Creating a join-log: @@ -246,23 +233,24 @@ impl CreateEmbed { /// # use serenity::model::*; /// # /// struct Handler; + /// /// impl EventHandler for Handler { - /// fn on_guild_member_addition(&self, _: Context, guild_id: GuildId, member: Member) { + /// fn guild_member_addition(&self, _: Context, guild_id: GuildId, member: Member) { /// use serenity::CACHE; - /// let cache = CACHE.read().unwrap(); + /// let cache = CACHE.read(); /// /// if let Some(guild) = cache.guild(guild_id) { - /// let guild = guild.read().unwrap(); + /// let guild = guild.read(); /// /// let channel_search = guild /// .channels /// .values() - /// .find(|c| c.read().unwrap().name == "join-log"); + /// .find(|c| c.read().name == "join-log"); /// /// if let Some(channel) = channel_search { - /// let user = member.user.read().unwrap(); + /// let user = member.user.read(); /// - /// let _ = channel.read().unwrap().send_message(|m| m + /// let _ = channel.read().send_message(|m| m /// .embed(|e| { /// let mut e = e /// .author(|a| a.icon_url(&user.face()).name(&user.name)) @@ -279,11 +267,13 @@ impl CreateEmbed { /// } /// } /// - /// let mut client = Client::new("token", Handler); client.start().unwrap(); + /// let mut client = Client::new("token", Handler).unwrap(); + /// + /// client.start().unwrap(); /// ``` pub fn timestamp<T: Into<Timestamp>>(mut self, timestamp: T) -> Self { self.0 - .insert("timestamp".to_string(), Value::String(timestamp.into().ts)); + .insert("timestamp", Value::String(timestamp.into().ts)); CreateEmbed(self.0) } @@ -291,7 +281,7 @@ impl CreateEmbed { /// Set the title of the embed. pub fn title<D: Display>(mut self, title: D) -> Self { self.0 - .insert("title".to_string(), Value::String(format!("{}", title))); + .insert("title", Value::String(title.to_string())); CreateEmbed(self.0) } @@ -299,7 +289,7 @@ impl CreateEmbed { /// Set the URL to direct to when clicking on the title. pub fn url(mut self, url: &str) -> Self { self.0 - .insert("url".to_string(), Value::String(url.to_string())); + .insert("url", Value::String(url.to_string())); CreateEmbed(self.0) } @@ -318,8 +308,8 @@ impl CreateEmbed { impl Default for CreateEmbed { /// Creates a builder with default values, setting the `type` to `rich`. fn default() -> CreateEmbed { - let mut map = Map::new(); - map.insert("type".to_string(), Value::String("rich".to_string())); + let mut map = HashMap::new(); + map.insert("type", Value::String("rich".to_string())); CreateEmbed(map) } @@ -353,9 +343,7 @@ impl From<Embed> for CreateEmbed { } for field in embed.fields { - b = b.field(move |f| { - f.inline(field.inline).name(&field.name).value(&field.value) - }); + b = b.field(field.name, field.value, field.inline); } if let Some(image) = embed.image { @@ -391,81 +379,31 @@ impl From<Embed> for CreateEmbed { /// [`CreateEmbed::author`]: struct.CreateEmbed.html#method.author /// [`name`]: #method.name #[derive(Clone, Debug, Default)] -pub struct CreateEmbedAuthor(pub Map<String, Value>); +pub struct CreateEmbedAuthor(pub HashMap<&'static str, Value>); impl CreateEmbedAuthor { /// Set the URL of the author's icon. pub fn icon_url(mut self, icon_url: &str) -> Self { - self.0 - .insert("icon_url".to_string(), Value::String(icon_url.to_string())); + self.0.insert("icon_url", Value::String(icon_url.to_string())); self } /// Set the author's name. pub fn name(mut self, name: &str) -> Self { - self.0 - .insert("name".to_string(), Value::String(name.to_string())); + self.0.insert("name", Value::String(name.to_string())); self } /// Set the author's URL. pub fn url(mut self, url: &str) -> Self { - self.0 - .insert("url".to_string(), Value::String(url.to_string())); + self.0.insert("url", Value::String(url.to_string())); self } } -/// A builder to create a fake [`Embed`] object's field, for use with the -/// [`CreateEmbed::field`] method. -/// -/// This does not require any field be set. `inline` is set to `true` by -/// default. -/// -/// [`Embed`]: ../model/struct.Embed.html -/// [`CreateEmbed::field`]: struct.CreateEmbed.html#method.field -#[derive(Clone, Debug)] -pub struct CreateEmbedField(pub Map<String, Value>); - -impl CreateEmbedField { - /// Set whether the field is inlined. Set to true by default. - pub fn inline(mut self, inline: bool) -> Self { - self.0.insert("inline".to_string(), Value::Bool(inline)); - - self - } - - /// Set the field's name. It can't be longer than 256 characters. - pub fn name<D: Display>(mut self, name: D) -> Self { - self.0 - .insert("name".to_string(), Value::String(format!("{}", name))); - - self - } - - /// Set the field's value. It can't be longer than 1024 characters. - pub fn value<D: Display>(mut self, value: D) -> Self { - self.0 - .insert("value".to_string(), Value::String(format!("{}", value))); - - self - } -} - -impl Default for CreateEmbedField { - /// Creates a builder with default values, setting the value of `inline` to - /// `true`. - fn default() -> CreateEmbedField { - let mut map = Map::new(); - map.insert("inline".to_string(), Value::Bool(true)); - - CreateEmbedField(map) - } -} - /// A builder to create a fake [`Embed`] object's footer, for use with the /// [`CreateEmbed::footer`] method. /// @@ -474,21 +412,19 @@ impl Default for CreateEmbedField { /// [`Embed`]: ../model/struct.Embed.html /// [`CreateEmbed::footer`]: struct.CreateEmbed.html#method.footer #[derive(Clone, Debug, Default)] -pub struct CreateEmbedFooter(pub Map<String, Value>); +pub struct CreateEmbedFooter(pub HashMap<&'static str, Value>); impl CreateEmbedFooter { /// Set the icon URL's value. This only supports HTTP(S). pub fn icon_url(mut self, icon_url: &str) -> Self { - self.0 - .insert("icon_url".to_string(), Value::String(icon_url.to_string())); + self.0.insert("icon_url", Value::String(icon_url.to_string())); self } /// Set the footer's text. pub fn text<D: Display>(mut self, text: D) -> Self { - self.0 - .insert("text".to_string(), Value::String(format!("{}", text))); + self.0.insert("text", Value::String(text.to_string())); self } diff --git a/src/builder/create_invite.rs b/src/builder/create_invite.rs index 645d401..269c51c 100644 --- a/src/builder/create_invite.rs +++ b/src/builder/create_invite.rs @@ -1,6 +1,7 @@ +use internal::prelude::*; use serde_json::Value; +use std::collections::HashMap; use std::default::Default; -use internal::prelude::*; /// A builder to create a [`RichInvite`] for use via [`GuildChannel::create_invite`]. /// @@ -18,10 +19,10 @@ use internal::prelude::*; /// struct Handler; /// /// impl EventHandler for Handler { -/// fn on_message(&self, _: Context, msg: Message) { +/// fn message(&self, _: Context, msg: Message) { /// use serenity::CACHE; /// if msg.content == "!createinvite" { -/// let channel = match CACHE.read().unwrap().guild_channel(msg.channel_id) { +/// let channel = match CACHE.read().guild_channel(msg.channel_id) { /// Some(channel) => channel, /// None => { /// let _ = msg.channel_id.say("Error creating invite"); @@ -30,7 +31,7 @@ use internal::prelude::*; /// }, /// }; /// -/// let reader = channel.read().unwrap(); +/// let reader = channel.read(); /// /// let invite = match reader.create_invite(|i| i.max_age(3600).max_uses(10)) { /// Ok(invite) => invite, @@ -52,13 +53,16 @@ use internal::prelude::*; /// } /// } /// } -/// let mut client = Client::new("token", Handler); client.start().unwrap(); +/// +/// let mut client = Client::new("token", Handler).unwrap(); +/// +/// client.start().unwrap(); /// ``` /// /// [`GuildChannel::create_invite`]: ../model/struct.GuildChannel.html#method.create_invite /// [`RichInvite`]: ../model/struct.Invite.html #[derive(Clone, Debug)] -pub struct CreateInvite(pub JsonMap); +pub struct CreateInvite(pub HashMap<&'static str, Value>); impl CreateInvite { /// The duration that the invite will be valid for. @@ -77,8 +81,8 @@ impl CreateInvite { /// # use std::error::Error; /// # /// # fn try_main() -> Result<(), Box<Error>> { - /// # let channel = CACHE.read().unwrap().guild_channel(81384788765712384).unwrap(); - /// # let channel = channel.read().unwrap(); + /// # let channel = CACHE.read().guild_channel(81384788765712384).unwrap(); + /// # let channel = channel.read(); /// # /// let invite = channel.create_invite(|i| i.max_age(3600))?; /// # Ok(()) @@ -89,8 +93,7 @@ impl CreateInvite { /// # } /// ``` pub fn max_age(mut self, max_age: u64) -> Self { - self.0 - .insert("max_age".to_string(), Value::Number(Number::from(max_age))); + self.0.insert("max_age", Value::Number(Number::from(max_age))); self } @@ -111,8 +114,8 @@ impl CreateInvite { /// # use std::error::Error; /// # /// # fn try_main() -> Result<(), Box<Error>> { - /// # let channel = CACHE.read().unwrap().guild_channel(81384788765712384).unwrap(); - /// # let channel = channel.read().unwrap(); + /// # let channel = CACHE.read().guild_channel(81384788765712384).unwrap(); + /// # let channel = channel.read(); /// # /// let invite = channel.create_invite(|i| i.max_uses(5))?; /// # Ok(()) @@ -123,8 +126,7 @@ impl CreateInvite { /// # } /// ``` pub fn max_uses(mut self, max_uses: u64) -> Self { - self.0 - .insert("max_uses".to_string(), Value::Number(Number::from(max_uses))); + self.0.insert("max_uses", Value::Number(Number::from(max_uses))); self } @@ -143,8 +145,8 @@ impl CreateInvite { /// # use std::error::Error; /// # /// # fn try_main() -> Result<(), Box<Error>> { - /// # let channel = CACHE.read().unwrap().guild_channel(81384788765712384).unwrap(); - /// # let channel = channel.read().unwrap(); + /// # let channel = CACHE.read().guild_channel(81384788765712384).unwrap(); + /// # let channel = channel.read(); /// # /// let invite = channel.create_invite(|i| i.temporary(true))?; /// # Ok(()) @@ -155,8 +157,7 @@ impl CreateInvite { /// # } /// ``` pub fn temporary(mut self, temporary: bool) -> Self { - self.0 - .insert("temporary".to_string(), Value::Bool(temporary)); + self.0.insert("temporary", Value::Bool(temporary)); self } @@ -175,8 +176,8 @@ impl CreateInvite { /// # use std::error::Error; /// # /// # fn try_main() -> Result<(), Box<Error>> { - /// # let channel = CACHE.read().unwrap().guild_channel(81384788765712384).unwrap(); - /// # let channel = channel.read().unwrap(); + /// # let channel = CACHE.read().guild_channel(81384788765712384).unwrap(); + /// # let channel = channel.read(); /// # /// let invite = channel.create_invite(|i| i.unique(true))?; /// # Ok(()) @@ -187,7 +188,7 @@ impl CreateInvite { /// # } /// ``` pub fn unique(mut self, unique: bool) -> Self { - self.0.insert("unique".to_string(), Value::Bool(unique)); + self.0.insert("unique", Value::Bool(unique)); self } @@ -206,8 +207,8 @@ impl Default for CreateInvite { /// let invite_builder = CreateInvite::default(); /// ``` fn default() -> CreateInvite { - let mut map = Map::new(); - map.insert("validate".to_string(), Value::Null); + let mut map = HashMap::new(); + map.insert("validate", Value::Null); CreateInvite(map) } diff --git a/src/builder/create_message.rs b/src/builder/create_message.rs index 821048b..bd5996a 100644 --- a/src/builder/create_message.rs +++ b/src/builder/create_message.rs @@ -1,7 +1,9 @@ -use super::CreateEmbed; -use model::ReactionType; use internal::prelude::*; +use model::ReactionType; +use std::collections::HashMap; use std::fmt::Display; +use super::CreateEmbed; +use utils; /// A builder to specify the contents of an [`http::send_message`] request, /// primarily meant for use through [`ChannelId::send_message`]. @@ -39,15 +41,14 @@ use std::fmt::Display; /// [`embed`]: #method.embed /// [`http::send_message`]: ../http/fn.send_message.html #[derive(Clone, Debug)] -pub struct CreateMessage(pub Map<String, Value>, pub Option<Vec<ReactionType>>); +pub struct CreateMessage(pub HashMap<&'static str, Value>, pub Option<Vec<ReactionType>>); impl CreateMessage { /// Set the content of the message. /// /// **Note**: Message contents must be under 2000 unicode code points. pub fn content<D: Display>(mut self, content: D) -> Self { - self.0 - .insert("content".to_string(), Value::String(format!("{}", content))); + self.0.insert("content", Value::String(content.to_string())); CreateMessage(self.0, self.1) } @@ -55,9 +56,10 @@ impl CreateMessage { /// Set an embed for the message. pub fn embed<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbed) -> CreateEmbed { - let embed = Value::Object(f(CreateEmbed::default()).0); + let map = utils::hashmap_to_json_map(f(CreateEmbed::default()).0); + let embed = Value::Object(map); - self.0.insert("embed".to_string(), embed); + self.0.insert("embed", embed); CreateMessage(self.0, self.1) } @@ -68,7 +70,7 @@ impl CreateMessage { /// /// Defaults to `false`. pub fn tts(mut self, tts: bool) -> Self { - self.0.insert("tts".to_string(), Value::Bool(tts)); + self.0.insert("tts", Value::Bool(tts)); CreateMessage(self.0, self.1) } @@ -88,8 +90,8 @@ impl Default for CreateMessage { /// [`Message`]: ../model/struct.Message.html /// [`tts`]: #method.tts fn default() -> CreateMessage { - let mut map = Map::default(); - map.insert("tts".to_string(), Value::Bool(false)); + let mut map = HashMap::default(); + map.insert("tts", Value::Bool(false)); CreateMessage(map, None) } diff --git a/src/builder/edit_channel.rs b/src/builder/edit_channel.rs index 1ed1551..96455e2 100644 --- a/src/builder/edit_channel.rs +++ b/src/builder/edit_channel.rs @@ -1,4 +1,5 @@ use internal::prelude::*; +use std::collections::HashMap; /// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`] /// @@ -18,7 +19,7 @@ use internal::prelude::*; /// [`GuildChannel`]: ../model/struct.GuildChannel.html /// [`GuildChannel::edit`]: ../model/struct.GuildChannel.html#method.edit #[derive(Clone, Debug, Default)] -pub struct EditChannel(pub JsonMap); +pub struct EditChannel(pub HashMap<&'static str, Value>); impl EditChannel { /// The bitrate of the channel in bits. @@ -27,8 +28,7 @@ impl EditChannel { /// /// [voice]: ../model/enum.ChannelType.html#variant.Voice pub fn bitrate(mut self, bitrate: u64) -> Self { - self.0 - .insert("bitrate".to_string(), Value::Number(Number::from(bitrate))); + self.0.insert("bitrate", Value::Number(Number::from(bitrate))); self } @@ -37,16 +37,14 @@ impl EditChannel { /// /// Must be between 2 and 100 characters long. pub fn name(mut self, name: &str) -> Self { - self.0 - .insert("name".to_string(), Value::String(name.to_string())); + self.0.insert("name", Value::String(name.to_string())); self } /// The position of the channel in the channel list. pub fn position(mut self, position: u64) -> Self { - self.0 - .insert("position".to_string(), Value::Number(Number::from(position))); + self.0.insert("position", Value::Number(Number::from(position))); self } @@ -59,8 +57,7 @@ impl EditChannel { /// /// [text]: ../model/enum.ChannelType.html#variant.Text pub fn topic(mut self, topic: &str) -> Self { - self.0 - .insert("topic".to_string(), Value::String(topic.to_string())); + self.0.insert("topic", Value::String(topic.to_string())); self } @@ -71,10 +68,7 @@ impl EditChannel { /// /// [voice]: ../model/enum.ChannelType.html#variant.Voice pub fn user_limit(mut self, user_limit: u64) -> Self { - self.0.insert( - "user_limit".to_string(), - Value::Number(Number::from(user_limit)), - ); + self.0.insert("user_limit", Value::Number(Number::from(user_limit))); self } diff --git a/src/builder/edit_guild.rs b/src/builder/edit_guild.rs index 0719305..45969fe 100644 --- a/src/builder/edit_guild.rs +++ b/src/builder/edit_guild.rs @@ -1,5 +1,6 @@ use internal::prelude::*; use model::{ChannelId, Region, UserId, VerificationLevel}; +use std::collections::HashMap; /// A builder to optionally edit certain fields of a [`Guild`]. This is meant /// for usage with [`Guild::edit`]. @@ -11,7 +12,7 @@ use model::{ChannelId, Region, UserId, VerificationLevel}; /// [`Guild`]: ../model/struct.Guild.html /// [Manage Guild]: ../model/permissions/constant.MANAGE_GUILD.html #[derive(Clone, Debug, Default)] -pub struct EditGuild(pub Map<String, Value>); +pub struct EditGuild(pub HashMap<&'static str, Value>); impl EditGuild { /// Set the "AFK voice channel" that users are to move to if they have been @@ -24,7 +25,7 @@ impl EditGuild { /// [`afk_timeout`]: #method.afk_timeout pub fn afk_channel<C: Into<ChannelId>>(mut self, channel: Option<C>) -> Self { self.0.insert( - "afk_channel_id".to_string(), + "afk_channel_id", match channel { Some(channel) => Value::Number(Number::from(channel.into().0)), None => Value::Null, @@ -40,7 +41,7 @@ impl EditGuild { /// [`afk_channel`]: #method.afk_channel pub fn afk_timeout(mut self, timeout: u64) -> Self { self.0.insert( - "afk_timeout".to_string(), + "afk_timeout", Value::Number(Number::from(timeout)), ); @@ -78,7 +79,7 @@ impl EditGuild { /// [`utils::read_image`]: ../utils/fn.read_image.html pub fn icon(mut self, icon: Option<&str>) -> Self { self.0.insert( - "icon".to_string(), + "icon", icon.map_or_else(|| Value::Null, |x| Value::String(x.to_string())), ); @@ -89,8 +90,7 @@ impl EditGuild { /// /// **Note**: Must be between (and including) 2-100 chracters. pub fn name(mut self, name: &str) -> Self { - self.0 - .insert("name".to_string(), Value::String(name.to_string())); + self.0.insert("name", Value::String(name.to_string())); self } @@ -99,10 +99,8 @@ impl EditGuild { /// /// **Note**: The current user must be the owner of the guild. pub fn owner<U: Into<UserId>>(mut self, user_id: U) -> Self { - self.0.insert( - "owner_id".to_string(), - Value::Number(Number::from(user_id.into().0)), - ); + let id = Value::Number(Number::from(user_id.into().0)); + self.0.insert("owner_id", id); self } @@ -134,8 +132,7 @@ impl EditGuild { /// /// [`Region::UsWest`]: ../model/enum.Region.html#variant.UsWest pub fn region(mut self, region: Region) -> Self { - self.0 - .insert("region".to_string(), Value::String(region.name().to_string())); + self.0.insert("region", Value::String(region.name().to_string())); self } @@ -149,8 +146,7 @@ impl EditGuild { /// [`features`]: ../model/struct.LiveGuild.html#structfield.features pub fn splash(mut self, splash: Option<&str>) -> Self { let splash = splash.map_or(Value::Null, |x| Value::String(x.to_string())); - - self.0.insert("splash".to_string(), splash); + self.0.insert("splash", splash); self } @@ -189,7 +185,7 @@ impl EditGuild { where V: Into<VerificationLevel> { let num = Value::Number(Number::from(verification_level.into().num())); - self.0.insert("verification_level".to_string(), num); + self.0.insert("verification_level", num); self } diff --git a/src/builder/edit_member.rs b/src/builder/edit_member.rs index 560d241..e68fc43 100644 --- a/src/builder/edit_member.rs +++ b/src/builder/edit_member.rs @@ -1,5 +1,6 @@ -use model::{ChannelId, RoleId}; use internal::prelude::*; +use model::{ChannelId, RoleId}; +use std::collections::HashMap; /// A builder which edits the properties of a [`Member`], to be used in /// conjunction with [`Member::edit`]. @@ -7,7 +8,7 @@ use internal::prelude::*; /// [`Member`]: ../model/struct.Member.html /// [`Member::edit`]: ../model/struct.Member.html#method.edit #[derive(Clone, Debug, Default)] -pub struct EditMember(pub JsonMap); +pub struct EditMember(pub HashMap<&'static str, Value>); impl EditMember { /// Whether to deafen the member. @@ -16,7 +17,7 @@ impl EditMember { /// /// [Deafen Members]: ../model/permissions/constant.DEAFEN_MEMBERS.html pub fn deafen(mut self, deafen: bool) -> Self { - self.0.insert("deaf".to_string(), Value::Bool(deafen)); + self.0.insert("deaf", Value::Bool(deafen)); self } @@ -27,7 +28,7 @@ impl EditMember { /// /// [Mute Members]: ../model/permissions/constant.MUTE_MEMBERS.html pub fn mute(mut self, mute: bool) -> Self { - self.0.insert("mute".to_string(), Value::Bool(mute)); + self.0.insert("mute", Value::Bool(mute)); self } @@ -39,8 +40,7 @@ impl EditMember { /// /// [Manage Nicknames]: ../model/permissions/constant.MANAGE_NICKNAMES.html pub fn nickname(mut self, nickname: &str) -> Self { - self.0 - .insert("nick".to_string(), Value::String(nickname.to_string())); + self.0.insert("nick", Value::String(nickname.to_string())); self } @@ -56,7 +56,7 @@ impl EditMember { .map(|x| Value::Number(Number::from(x.as_ref().0))) .collect(); - self.0.insert("roles".to_string(), Value::Array(role_ids)); + self.0.insert("roles", Value::Array(role_ids)); self } @@ -67,10 +67,8 @@ impl EditMember { /// /// [Move Members]: ../model/permissions/constant.MOVE_MEMBERS.html pub fn voice_channel<C: Into<ChannelId>>(mut self, channel_id: C) -> Self { - self.0.insert( - "channel_id".to_string(), - Value::Number(Number::from(channel_id.into().0)), - ); + let num = Value::Number(Number::from(channel_id.into().0)); + self.0.insert("channel_id", num); self } diff --git a/src/builder/edit_profile.rs b/src/builder/edit_profile.rs index ae0bbd5..09d3337 100644 --- a/src/builder/edit_profile.rs +++ b/src/builder/edit_profile.rs @@ -1,11 +1,12 @@ use internal::prelude::*; +use std::collections::HashMap; /// A builder to edit the current user's settings, to be used in conjunction /// with [`CurrentUser::edit`]. /// /// [`CurrentUser::edit`]: ../model/struct.CurrentUser.html#method.edit #[derive(Clone, Debug, Default)] -pub struct EditProfile(pub JsonMap); +pub struct EditProfile(pub HashMap<&'static str, Value>); impl EditProfile { /// Sets the avatar of the current user. `None` can be passed to remove an @@ -23,8 +24,9 @@ impl EditProfile { /// # use serenity::model::*; /// # /// # struct Handler; + /// /// # impl EventHandler for Handler { - /// # fn on_message(&self, context: Context, _: Message) { + /// # fn message(&self, context: Context, _: Message) { /// use serenity::utils; /// /// // assuming a `context` has been bound @@ -37,15 +39,16 @@ impl EditProfile { /// }); /// # } /// } - - /// # let mut client = Client::new("token", Handler); client.start().unwrap(); + /// # + /// # let mut client = Client::new("token", Handler).unwrap(); + /// # + /// # client.start().unwrap(); /// ``` /// /// [`utils::read_image`]: ../fn.read_image.html pub fn avatar(mut self, avatar: Option<&str>) -> Self { let avatar = avatar.map_or(Value::Null, |x| Value::String(x.to_string())); - - self.0.insert("avatar".to_string(), avatar); + self.0.insert("avatar", avatar); self } @@ -61,8 +64,7 @@ impl EditProfile { /// /// [provided]: #method.password pub fn email(mut self, email: &str) -> Self { - self.0 - .insert("email".to_string(), Value::String(email.to_string())); + self.0.insert("email", Value::String(email.to_string())); self } @@ -74,10 +76,7 @@ impl EditProfile { /// /// [provided]: #method.password pub fn new_password(mut self, new_password: &str) -> Self { - self.0.insert( - "new_password".to_string(), - Value::String(new_password.to_string()), - ); + self.0.insert("new_password", Value::String(new_password.to_string())); self } @@ -88,8 +87,7 @@ impl EditProfile { /// [modifying the password]: #method.new_password /// [modifying the associated email address]: #method.email pub fn password(mut self, password: &str) -> Self { - self.0 - .insert("password".to_string(), Value::String(password.to_string())); + self.0.insert("password", Value::String(password.to_string())); self } @@ -101,8 +99,7 @@ impl EditProfile { /// If there are no available discriminators with the requested username, /// an error will occur. pub fn username(mut self, username: &str) -> Self { - self.0 - .insert("username".to_string(), Value::String(username.to_string())); + self.0.insert("username", Value::String(username.to_string())); self } diff --git a/src/builder/edit_role.rs b/src/builder/edit_role.rs index 0702450..7e2ff17 100644 --- a/src/builder/edit_role.rs +++ b/src/builder/edit_role.rs @@ -1,4 +1,5 @@ use internal::prelude::*; +use std::collections::HashMap; use model::{Permissions, Role}; /// A builer to create or edit a [`Role`] for use via a number of model methods. @@ -38,48 +39,38 @@ use model::{Permissions, Role}; /// [`Role`]: ../model/struct.Role.html /// [`Role::edit`]: ../model/struct.Role.html#method.edit #[derive(Clone, Debug, Default)] -pub struct EditRole(pub JsonMap); +pub struct EditRole(pub HashMap<&'static str, Value>); impl EditRole { /// Creates a new builder with the values of the given [`Role`]. /// /// [`Role`]: ../model/struct.Role.html pub fn new(role: &Role) -> Self { - let mut map = Map::new(); + let mut map = HashMap::new(); #[cfg(feature = "utils")] { - map.insert( - "color".to_string(), - Value::Number(Number::from(role.colour.0)), - ); + map.insert("color", Value::Number(Number::from(role.colour.0))); } #[cfg(not(feature = "utils"))] { - map.insert("color".to_string(), Value::Number(Number::from(role.colour))); + map.insert("color", Value::Number(Number::from(role.colour))); } - map.insert("hoist".to_string(), Value::Bool(role.hoist)); - map.insert("managed".to_string(), Value::Bool(role.managed)); - map.insert("mentionable".to_string(), Value::Bool(role.mentionable)); - map.insert("name".to_string(), Value::String(role.name.clone())); - map.insert( - "permissions".to_string(), - Value::Number(Number::from(role.permissions.bits())), - ); - map.insert( - "position".to_string(), - Value::Number(Number::from(role.position)), - ); + map.insert("hoist", Value::Bool(role.hoist)); + map.insert("managed", Value::Bool(role.managed)); + map.insert("mentionable", Value::Bool(role.mentionable)); + map.insert("name", Value::String(role.name.clone())); + map.insert("permissions",Value::Number(Number::from(role.permissions.bits()))); + map.insert("position", Value::Number(Number::from(role.position))); EditRole(map) } /// Sets the colour of the role. pub fn colour(mut self, colour: u64) -> Self { - self.0 - .insert("color".to_string(), Value::Number(Number::from(colour))); + self.0.insert("color", Value::Number(Number::from(colour))); self } @@ -87,15 +78,14 @@ impl EditRole { /// Whether or not to hoist the role above lower-positioned role in the user /// list. pub fn hoist(mut self, hoist: bool) -> Self { - self.0.insert("hoist".to_string(), Value::Bool(hoist)); + self.0.insert("hoist", Value::Bool(hoist)); self } /// Whether or not to make the role mentionable, notifying its users. pub fn mentionable(mut self, mentionable: bool) -> Self { - self.0 - .insert("mentionable".to_string(), Value::Bool(mentionable)); + self.0.insert("mentionable", Value::Bool(mentionable)); self } @@ -103,17 +93,14 @@ impl EditRole { /// The name of the role to set. pub fn name(mut self, name: &str) -> Self { self.0 - .insert("name".to_string(), Value::String(name.to_string())); + .insert("name", Value::String(name.to_string())); self } /// The set of permissions to assign the role. pub fn permissions(mut self, permissions: Permissions) -> Self { - self.0.insert( - "permissions".to_string(), - Value::Number(Number::from(permissions.bits())), - ); + self.0.insert("permissions", Value::Number(Number::from(permissions.bits()))); self } @@ -121,8 +108,7 @@ impl EditRole { /// The position to assign the role in the role list. This correlates to the /// role's position in the user list. pub fn position(mut self, position: u8) -> Self { - self.0 - .insert("position".to_string(), Value::Number(Number::from(position))); + self.0.insert("position", Value::Number(Number::from(position))); self } diff --git a/src/builder/execute_webhook.rs b/src/builder/execute_webhook.rs index ba1668e..6276da1 100644 --- a/src/builder/execute_webhook.rs +++ b/src/builder/execute_webhook.rs @@ -1,6 +1,6 @@ use serde_json::Value; +use std::collections::HashMap; use std::default::Default; -use internal::prelude::*; /// A builder to create the inner content of a [`Webhook`]'s execution. /// @@ -35,14 +35,8 @@ use internal::prelude::*; /// .title("Rust Resources") /// .description("A few resources to help with learning Rust") /// .colour(0xDEA584) -/// .field(|f| f -/// .inline(false) -/// .name("The Rust Book") -/// .value("A comprehensive resource for all topics related to Rust")) -/// .field(|f| f -/// .inline(false) -/// .name("Rust by Example") -/// .value("A collection of Rust examples on topics, useable in-browser"))); +/// .field("The Rust Book", "A comprehensive resource for Rust.", false) +/// .field("Rust by Example", "A collection of Rust examples", false)); /// /// let _ = webhook.execute(false, |w| w /// .content("Here's some information on Rust:") @@ -53,7 +47,7 @@ use internal::prelude::*; /// [`Webhook::execute`]: ../model/struct.Webhook.html#method.execute /// [`execute_webhook`]: ../http/fn.execute_webhook.html #[derive(Clone, Debug)] -pub struct ExecuteWebhook(pub JsonMap); +pub struct ExecuteWebhook(pub HashMap<&'static str, Value>); impl ExecuteWebhook { /// Override the default avatar of the webhook with an image URL. @@ -74,10 +68,7 @@ impl ExecuteWebhook { /// .content("Here's a webhook")); /// ``` pub fn avatar_url(mut self, avatar_url: &str) -> Self { - self.0.insert( - "avatar_url".to_string(), - Value::String(avatar_url.to_string()), - ); + self.0.insert("avatar_url", Value::String(avatar_url.to_string())); self } @@ -103,8 +94,7 @@ impl ExecuteWebhook { /// /// [`embeds`]: #method.embeds pub fn content(mut self, content: &str) -> Self { - self.0 - .insert("content".to_string(), Value::String(content.to_string())); + self.0.insert("content", Value::String(content.to_string())); self } @@ -123,7 +113,7 @@ impl ExecuteWebhook { /// [`Webhook::execute`]: ../model/struct.Webhook.html#method.execute /// [struct-level documentation]: #examples pub fn embeds(mut self, embeds: Vec<Value>) -> Self { - self.0.insert("embeds".to_string(), Value::Array(embeds)); + self.0.insert("embeds", Value::Array(embeds)); self } @@ -144,7 +134,7 @@ impl ExecuteWebhook { /// } /// ``` pub fn tts(mut self, tts: bool) -> Self { - self.0.insert("tts".to_string(), Value::Bool(tts)); + self.0.insert("tts", Value::Bool(tts)); self } @@ -165,8 +155,7 @@ impl ExecuteWebhook { /// } /// ``` pub fn username(mut self, username: &str) -> Self { - self.0 - .insert("username".to_string(), Value::String(username.to_string())); + self.0.insert("username", Value::String(username.to_string())); self } @@ -190,8 +179,8 @@ impl Default for ExecuteWebhook { /// [`Webhook`]: ../model/struct.Webhook.html /// [`tts`]: #method.tts fn default() -> ExecuteWebhook { - let mut map = Map::new(); - map.insert("tts".to_string(), Value::Bool(false)); + let mut map = HashMap::new(); + map.insert("tts", Value::Bool(false)); ExecuteWebhook(map) } diff --git a/src/builder/get_messages.rs b/src/builder/get_messages.rs index 71af9e5..e59584f 100644 --- a/src/builder/get_messages.rs +++ b/src/builder/get_messages.rs @@ -1,5 +1,5 @@ -use std::collections::BTreeMap; use model::MessageId; +use std::collections::HashMap; /// Builds a request for a request to the API to retrieve messages. /// @@ -50,13 +50,13 @@ use model::MessageId; /// /// [`GuildChannel::messages`]: ../model/struct.GuildChannel.html#method.messages #[derive(Clone, Debug, Default)] -pub struct GetMessages(pub BTreeMap<String, u64>); +pub struct GetMessages(pub HashMap<&'static str, u64>); impl GetMessages { /// Indicates to retrieve the messages after a specific message, given by /// its Id. pub fn after<M: Into<MessageId>>(mut self, message_id: M) -> Self { - self.0.insert("after".to_string(), message_id.into().0); + self.0.insert("after", message_id.into().0); self } @@ -64,7 +64,7 @@ impl GetMessages { /// Indicates to retrieve the messages _around_ a specific message in either /// direction (before+after) the given message. pub fn around<M: Into<MessageId>>(mut self, message_id: M) -> Self { - self.0.insert("around".to_string(), message_id.into().0); + self.0.insert("around", message_id.into().0); self } @@ -72,7 +72,7 @@ impl GetMessages { /// Indicates to retrieve the messages before a specific message, given by /// its Id. pub fn before<M: Into<MessageId>>(mut self, message_id: M) -> Self { - self.0.insert("before".to_string(), message_id.into().0); + self.0.insert("before", message_id.into().0); self } @@ -86,7 +86,7 @@ impl GetMessages { /// reduced. pub fn limit(mut self, limit: u64) -> Self { self.0 - .insert("limit".to_string(), if limit > 100 { 100 } else { limit }); + .insert("limit", if limit > 100 { 100 } else { limit }); self } diff --git a/src/builder/mod.rs b/src/builder/mod.rs index 496d7e1..3c59c0d 100644 --- a/src/builder/mod.rs +++ b/src/builder/mod.rs @@ -16,7 +16,7 @@ mod edit_role; mod execute_webhook; mod get_messages; -pub use self::create_embed::{CreateEmbed, CreateEmbedAuthor, CreateEmbedField, CreateEmbedFooter}; +pub use self::create_embed::{CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter}; pub use self::create_invite::CreateInvite; pub use self::create_message::CreateMessage; pub use self::edit_channel::EditChannel; |