aboutsummaryrefslogtreecommitdiff
path: root/src/model
diff options
context:
space:
mode:
authorZeyla Hellyer <[email protected]>2017-12-16 08:39:36 -0800
committerZeyla Hellyer <[email protected]>2017-12-16 08:45:26 -0800
commitbcd16dddb8cc3086a13524c79676f3a8bebbc524 (patch)
tree42d254fb4738df957c4b7d9e5766d1cb5bd47323 /src/model
parentFix guild deserialization tests (diff)
downloadserenity-bcd16dddb8cc3086a13524c79676f3a8bebbc524.tar.xz
serenity-bcd16dddb8cc3086a13524c79676f3a8bebbc524.zip
Break up the model module
The `model` module has historically been one giant module re-exporting all of the model types, which is somewhere around 100 types. This can be a lot to look at for a new user and somewhat overwhelming, especially with a large number of fine-grained imports from the module. The module is now neatly split up into submodules, mostly like it has been internally since the early versions of the library. The submodules are: - application - channel - error - event - gateway - guild - id - invite - misc - permissions - prelude - user - voice - webhook Each submodule contains types that are "owned" by the module. For example, the `guild` submodule contains, but not limited to, Emoji, AuditLogsEntry, Role, and Member. `channel` contains, but not limited to, Attachment, Embed, Message, and Reaction. Upgrade path: Instead of glob importing the models via `use serenity::model::*;`, instead glob import via the prelude: ```rust use serenity::model::prelude::*; ``` Instead of importing from the root model module: ```rust use serenity::model::{Guild, Message, OnlineStatus, Role, User}; ``` instead import from the submodules like so: ```rust use serenity::model::channel::Message; use serenity::model::guild::{Guild, Role}; use serenity::model::user::{OnlineStatus, User}; ```
Diffstat (limited to 'src/model')
-rw-r--r--src/model/application.rs84
-rw-r--r--src/model/channel/attachment.rs3
-rw-r--r--src/model/channel/channel_category.rs2
-rw-r--r--src/model/channel/channel_id.rs6
-rw-r--r--src/model/channel/embed.rs2
-rw-r--r--src/model/channel/group.rs2
-rw-r--r--src/model/channel/guild_channel.rs34
-rw-r--r--src/model/channel/message.rs6
-rw-r--r--src/model/channel/mod.rs4
-rw-r--r--src/model/channel/private_channel.rs2
-rw-r--r--src/model/channel/reaction.rs6
-rw-r--r--src/model/error.rs4
-rw-r--r--src/model/event.rs2
-rw-r--r--src/model/gateway.rs12
-rw-r--r--src/model/guild/audit_log.rs11
-rw-r--r--src/model/guild/emoji.rs14
-rw-r--r--src/model/guild/guild_id.rs10
-rw-r--r--src/model/guild/member.rs2
-rw-r--r--src/model/guild/mod.rs59
-rw-r--r--src/model/guild/partial_guild.rs10
-rw-r--r--src/model/guild/role.rs4
-rw-r--r--src/model/id.rs89
-rw-r--r--src/model/invite.rs8
-rw-r--r--src/model/misc.rs4
-rw-r--r--src/model/mod.rs268
-rw-r--r--src/model/prelude.rs25
-rw-r--r--src/model/user.rs14
-rw-r--r--src/model/utils.rs11
-rw-r--r--src/model/voice.rs4
-rw-r--r--src/model/webhook.rs8
30 files changed, 391 insertions, 319 deletions
diff --git a/src/model/application.rs b/src/model/application.rs
new file mode 100644
index 0000000..dca8e41
--- /dev/null
+++ b/src/model/application.rs
@@ -0,0 +1,84 @@
+//! Models about OAuth2 applications.
+
+use super::id::UserId;
+use super::user::User;
+use super::utils::default_true;
+
+/// Information about a user's application. An application does not necessarily
+/// have an associated bot user.
+#[derive(Clone, Debug, Deserialize)]
+pub struct ApplicationInfo {
+ /// The bot user associated with the application. See [`BotApplication`] for
+ /// more information.
+ ///
+ /// [`BotApplication`]: struct.BotApplication.html
+ pub bot: Option<BotApplication>,
+ /// Indicator of whether the bot is public.
+ ///
+ /// If a bot is public, anyone may invite it to their [`Guild`]. While a bot
+ /// is private, only the owner may add it to a guild.
+ ///
+ /// [`Guild`]: struct.Guild.html
+ #[serde(default = "default_true")]
+ pub bot_public: bool,
+ /// Indicator of whether the bot requires an OAuth2 code grant.
+ pub bot_require_code_grant: bool,
+ /// A description of the application, assigned by the application owner.
+ pub description: String,
+ /// A set of bitflags assigned to the application, which represent gated
+ /// feature flags that have been enabled for the application.
+ pub flags: Option<u64>,
+ /// A hash pointing to the application's icon.
+ ///
+ /// This is not necessarily equivalent to the bot user's avatar.
+ pub icon: Option<String>,
+ /// The unique numeric Id of the application.
+ pub id: UserId,
+ /// The name assigned to the application by the application owner.
+ pub name: String,
+ /// A list of redirect URIs assigned to the application.
+ pub redirect_uris: Vec<String>,
+ /// A list of RPC Origins assigned to the application.
+ pub rpc_origins: Vec<String>,
+ /// The given secret to the application.
+ ///
+ /// This is not equivalent to the application's bot user's token.
+ pub secret: String,
+}
+
+/// Information about an application with an application's bot user.
+#[derive(Clone, Debug, Deserialize)]
+pub struct BotApplication {
+ /// The unique Id of the bot user.
+ pub id: UserId,
+ /// A hash of the avatar, if one is assigned.
+ ///
+ /// Can be used to generate a full URL to the avatar.
+ pub avatar: Option<String>,
+ /// Indicator of whether it is a bot.
+ #[serde(default)]
+ pub bot: bool,
+ /// The discriminator assigned to the bot user.
+ ///
+ /// While discriminators are not unique, the `username#discriminator` pair
+ /// is.
+ pub discriminator: u16,
+ /// The bot user's username.
+ pub name: String,
+ /// The token used to authenticate as the bot user.
+ ///
+ /// **Note**: Keep this information private, as untrusted sources can use it
+ /// to perform any action with a bot user.
+ pub token: String,
+}
+
+/// Information about the current application and its owner.
+#[derive(Clone, Debug, Deserialize)]
+pub struct CurrentApplicationInfo {
+ pub description: String,
+ pub icon: Option<String>,
+ pub id: UserId,
+ pub name: String,
+ pub owner: User,
+ #[serde(default)] pub rpc_origins: Vec<String>,
+}
diff --git a/src/model/channel/attachment.rs b/src/model/channel/attachment.rs
index 1836498..a9c625b 100644
--- a/src/model/channel/attachment.rs
+++ b/src/model/channel/attachment.rs
@@ -43,8 +43,8 @@ impl Attachment {
/// Download all of the attachments associated with a [`Message`]:
///
/// ```rust,no_run
+ /// use serenity::model::prelude::*;
/// use serenity::prelude::*;
- /// use serenity::model::*;
/// use std::env;
/// use std::fs::File;
/// use std::io::Write;
@@ -52,7 +52,6 @@ impl Attachment {
///
/// struct Handler;
///
- ///
/// impl EventHandler for Handler {
/// fn message(&self, _: Context, message: Message) {
/// for attachment in message.attachments {
diff --git a/src/model/channel/channel_category.rs b/src/model/channel/channel_category.rs
index 73c50a7..f6df342 100644
--- a/src/model/channel/channel_category.rs
+++ b/src/model/channel/channel_category.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
#[cfg(all(feature = "builder", feature = "model"))]
use builder::EditChannel;
diff --git a/src/model/channel/channel_id.rs b/src/model/channel/channel_id.rs
index acd3704..7ec6dfe 100644
--- a/src/model/channel/channel_id.rs
+++ b/src/model/channel/channel_id.rs
@@ -1,5 +1,5 @@
use internal::RwLockExt;
-use model::*;
+use model::prelude::*;
#[cfg(feature = "model")]
use std::borrow::Cow;
@@ -408,7 +408,7 @@ impl ChannelId {
/// Send files with the paths `/path/to/file.jpg` and `/path/to/file2.jpg`:
///
/// ```rust,no_run
- /// use serenity::model::ChannelId;
+ /// use serenity::model::id::ChannelId;
///
/// let channel_id = ChannelId(7);
///
@@ -420,7 +420,7 @@ impl ChannelId {
/// Send files using `File`:
///
/// ```rust,no_run
- /// use serenity::model::ChannelId;
+ /// use serenity::model::id::ChannelId;
/// use std::fs::File;
///
/// let channel_id = ChannelId(7);
diff --git a/src/model/channel/embed.rs b/src/model/channel/embed.rs
index a839beb..3cbe5ac 100644
--- a/src/model/channel/embed.rs
+++ b/src/model/channel/embed.rs
@@ -78,7 +78,7 @@ impl Embed {
/// Create an embed:
///
/// ```rust,no_run
- /// use serenity::model::Embed;
+ /// use serenity::model::channel::Embed;
///
/// let embed = Embed::fake(|e| e
/// .title("Embed title")
diff --git a/src/model/channel/group.rs b/src/model/channel/group.rs
index dfdfd0f..bff58aa 100644
--- a/src/model/channel/group.rs
+++ b/src/model/channel/group.rs
@@ -1,5 +1,5 @@
use chrono::{DateTime, FixedOffset};
-use model::*;
+use model::prelude::*;
#[cfg(feature = "model")]
use builder::{CreateMessage, GetMessages};
diff --git a/src/model/channel/guild_channel.rs b/src/model/channel/guild_channel.rs
index 54f802d..9b8371d 100644
--- a/src/model/channel/guild_channel.rs
+++ b/src/model/channel/guild_channel.rs
@@ -1,5 +1,5 @@
use chrono::{DateTime, FixedOffset};
-use model::*;
+use model::prelude::*;
#[cfg(all(feature = "cache", feature = "model"))]
use CACHE;
@@ -137,18 +137,17 @@ impl GuildChannel {
/// permissions:
///
/// ```rust,no_run
- /// # use serenity::model::{ChannelId, Permissions, UserId};
+ /// # use serenity::model::id::{ChannelId, UserId};
/// # use std::error::Error;
/// #
/// # fn try_main() -> Result<(), Box<Error>> {
/// # let (channel_id, user_id) = (ChannelId(0), UserId(0));
/// #
- /// use serenity::model::{
- /// ModelError,
+ /// use serenity::model::channel::{
/// PermissionOverwrite,
/// PermissionOverwriteType,
- /// permissions,
/// };
+ /// use serenity::model::{ModelError, Permissions};
/// use serenity::CACHE;
///
/// let allow = Permissions::SEND_MESSAGES;
@@ -179,18 +178,17 @@ impl GuildChannel {
/// permissions:
///
/// ```rust,no_run
- /// # use serenity::model::{ChannelId, Permissions, UserId};
+ /// # use serenity::model::id::{ChannelId, UserId};
/// # use std::error::Error;
/// #
/// # fn try_main() -> Result<(), Box<Error>> {
/// # let (channel_id, user_id) = (ChannelId(0), UserId(0));
/// #
- /// use serenity::model::{
- /// ModelError,
+ /// use serenity::model::channel::{
/// PermissionOverwrite,
/// PermissionOverwriteType,
- /// permissions,
/// };
+ /// use serenity::model::{ModelError, Permissions};
/// use serenity::CACHE;
///
/// let allow = Permissions::SEND_MESSAGES;
@@ -425,7 +423,7 @@ impl GuildChannel {
///
/// ```rust,no_run
/// use serenity::prelude::*;
- /// use serenity::model::*;
+ /// use serenity::model::prelude::*;
/// struct Handler;
///
/// use serenity::CACHE;
@@ -452,10 +450,9 @@ impl GuildChannel {
/// for demonstrative purposes):
///
/// ```rust,no_run
- /// use serenity::prelude::*;
- /// use serenity::model::*;
/// use serenity::CACHE;
- /// use serenity::model::permissions;
+ /// use serenity::prelude::*;
+ /// use serenity::model::prelude::*;
/// use std::fs::File;
///
/// struct Handler;
@@ -468,11 +465,10 @@ impl GuildChannel {
/// };
///
/// let current_user_id = CACHE.read().user.id;
- /// let permissions =
- /// channel.read().permissions_for(current_user_id).unwrap();
+ /// let permissions =
+ /// channel.read().permissions_for(current_user_id).unwrap();
///
- /// if !permissions.contains(Permissions::ATTACH_FILES |
- /// Permissions::SEND_MESSAGES) {
+ /// if !permissions.contains(Permissions::ATTACH_FILES | Permissions::SEND_MESSAGES) {
/// return;
/// }
///
@@ -485,8 +481,8 @@ impl GuildChannel {
/// },
/// };
///
- /// let _ = msg.channel_id.send_files(vec![(&file, "cat.png")], |m|
- /// m.content("here's a cat"));
+ /// let _ = msg.channel_id.send_files(vec![(&file, "cat.png")], |m|
+ /// m.content("here's a cat"));
/// }
/// }
///
diff --git a/src/model/channel/message.rs b/src/model/channel/message.rs
index 65df51a..f139aab 100644
--- a/src/model/channel/message.rs
+++ b/src/model/channel/message.rs
@@ -1,5 +1,7 @@
+//! Models relating to Discord channels.
+
use chrono::{DateTime, FixedOffset};
-use model::*;
+use model::prelude::*;
use serde_json::Value;
#[cfg(feature = "model")]
@@ -85,7 +87,7 @@ impl Message {
/// # impl EventHandler for Handler {}
/// # let mut client = Client::new("token", Handler).unwrap();
/// #
- /// use serenity::model::Channel;
+ /// use serenity::model::channel::Channel;
/// use serenity::framework::StandardFramework;
///
/// client.with_framework(StandardFramework::new()
diff --git a/src/model/channel/mod.rs b/src/model/channel/mod.rs
index 2fc4cbc..479818b 100644
--- a/src/model/channel/mod.rs
+++ b/src/model/channel/mod.rs
@@ -1,3 +1,5 @@
+//! Models relating to channels and types within channels.
+
mod attachment;
mod channel_id;
mod embed;
@@ -19,7 +21,7 @@ pub use self::reaction::*;
pub use self::channel_category::*;
use internal::RwLockExt;
-use model::*;
+use model::prelude::*;
use serde::de::Error as DeError;
use serde_json;
use super::utils::deserialize_u64;
diff --git a/src/model/channel/private_channel.rs b/src/model/channel/private_channel.rs
index a05b750..c9b6524 100644
--- a/src/model/channel/private_channel.rs
+++ b/src/model/channel/private_channel.rs
@@ -1,5 +1,5 @@
use chrono::{DateTime, FixedOffset};
-use model::*;
+use model::prelude::*;
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::deserialize_single_recipient;
diff --git a/src/model/channel/reaction.rs b/src/model/channel/reaction.rs
index b2fdffd..5c1ee4d 100644
--- a/src/model/channel/reaction.rs
+++ b/src/model/channel/reaction.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
use serde::de::{Deserialize, Error as DeError, MapAccess, Visitor};
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite};
@@ -270,7 +270,7 @@ impl From<char> for ReactionType {
/// Reacting to a message with an apple:
///
/// ```rust,no_run
- /// # use serenity::model::ChannelId;
+ /// # use serenity::model::id::ChannelId;
/// # use std::error::Error;
/// #
/// # fn try_main() -> Result<(), Box<Error>> {
@@ -327,7 +327,7 @@ impl<'a> From<&'a str> for ReactionType {
/// rest of the library:
///
/// ```rust
- /// use serenity::model::ReactionType;
+ /// use serenity::model::channel::ReactionType;
///
/// fn foo<R: Into<ReactionType>>(bar: R) {
/// println!("{:?}", bar.into());
diff --git a/src/model/error.rs b/src/model/error.rs
index c2f568b..b3b23b8 100644
--- a/src/model/error.rs
+++ b/src/model/error.rs
@@ -1,3 +1,5 @@
+//! Error enum definition wrapping potential model implementation errors.
+
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::Permissions;
@@ -19,7 +21,7 @@ use super::Permissions;
/// # #[cfg(all(feature = "client", feature = "model"))]
/// # fn try_main() -> Result<(), Box<Error>> {
/// use serenity::prelude::*;
-/// use serenity::model::*;
+/// use serenity::model::prelude::*;
/// use serenity::Error;
/// use serenity::model::ModelError;
/// use std::env;
diff --git a/src/model/event.rs b/src/model/event.rs
index de9c8e2..58a9c23 100644
--- a/src/model/event.rs
+++ b/src/model/event.rs
@@ -5,7 +5,7 @@ use serde::de::Error as DeError;
use serde_json;
use std::collections::HashMap;
use super::utils::deserialize_emojis;
-use super::*;
+use super::prelude::*;
use constants::{OpCode, VoiceOpCode};
use internal::prelude::*;
diff --git a/src/model/gateway.rs b/src/model/gateway.rs
index c1f6fc9..6a3e24d 100644
--- a/src/model/gateway.rs
+++ b/src/model/gateway.rs
@@ -1,9 +1,11 @@
+//! Models pertaining to the gateway.
+
use parking_lot::RwLock;
use serde::de::Error as DeError;
use serde_json;
use std::sync::Arc;
use super::utils::*;
-use super::*;
+use super::prelude::*;
/// A representation of the data retrieved from the bot gateway endpoint.
///
@@ -49,7 +51,7 @@ impl Game {
/// # #[macro_use] extern crate serenity;
/// #
/// use serenity::framework::standard::Args;
- /// use serenity::model::Game;
+ /// use serenity::model::gateway::Game;
///
/// command!(game(ctx, _msg, args) {
/// let name = args.full();
@@ -78,7 +80,7 @@ impl Game {
/// # #[macro_use] extern crate serenity;
/// #
/// use serenity::framework::standard::Args;
- /// use serenity::model::Game;
+ /// use serenity::model::gateway::Game;
///
/// // Assumes command has min_args set to 2.
/// command!(stream(ctx, _msg, args) {
@@ -109,7 +111,7 @@ impl Game {
/// # #[macro_use] extern crate serenity;
/// #
/// use serenity::framework::standard::Args;
- /// use serenity::model::Game;
+ /// use serenity::model::gateway::Game;
///
/// command!(listen(ctx, _msg, args) {
/// let name = args.full();
@@ -138,7 +140,7 @@ impl Game {
/// # #[macro_use] extern crate serenity;
/// #
/// use serenity::framework::standard::Args;
- /// use serenity::model::Game;
+ /// use serenity::model::gateway::Game;
///
/// command!(watch(ctx, _msg, args) {
/// let name = args.full();
diff --git a/src/model/guild/audit_log.rs b/src/model/guild/audit_log.rs
index 51138e0..7437e42 100644
--- a/src/model/guild/audit_log.rs
+++ b/src/model/guild/audit_log.rs
@@ -1,5 +1,6 @@
+use internal::prelude::*;
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
-use super::super::{AuditLogEntryId, User, UserId, ChannelId, Webhook};
+use super::super::prelude::*;
use std::collections::HashMap;
use std::mem::transmute;
use std::fmt;
@@ -147,7 +148,7 @@ pub struct Options {
}
-fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Error> {
+fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> StdResult<Action, D::Error> {
struct ActionVisitor;
impl<'de> Visitor<'de> for ActionVisitor {
@@ -157,7 +158,7 @@ fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Err
formatter.write_str("an integer between 1 to 72")
}
- fn visit_u8<E: de::Error>(self, value: u8) -> Result<Action, E> {
+ fn visit_u8<E: de::Error>(self, value: u8) -> StdResult<Action, E> {
Ok(match value {
1 => Action::GuildUpdate,
10...12 => Action::Channel(unsafe { transmute(value) }),
@@ -177,7 +178,7 @@ fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Err
}
impl<'de> Deserialize<'de> for AuditLogs {
- fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
+ fn deserialize<D: Deserializer<'de>>(de: D) -> StdResult<Self, D::Error> {
#[derive(Deserialize)]
#[serde(field_identifier)]
enum Field {
@@ -195,7 +196,7 @@ impl<'de> Deserialize<'de> for AuditLogs {
formatter.write_str("audit log entries")
}
- fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<AuditLogs, V::Error> {
+ fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> StdResult<AuditLogs, V::Error> {
let mut audit_log_entries = None;
let mut users = None;
let mut webhooks = None;
diff --git a/src/model/guild/emoji.rs b/src/model/guild/emoji.rs
index 31d2a1f..9581f77 100644
--- a/src/model/guild/emoji.rs
+++ b/src/model/guild/emoji.rs
@@ -1,5 +1,5 @@
use std::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite};
-use super::super::{EmojiId, RoleId};
+use super::super::id::{EmojiId, RoleId};
#[cfg(all(feature = "cache", feature = "model"))]
use internal::prelude::*;
@@ -51,7 +51,8 @@ impl Emoji {
/// Delete a given emoji:
///
/// ```rust,no_run
- /// # use serenity::model::{Emoji, EmojiId};
+ /// # use serenity::model::guild::Emoji;
+ /// # use serenity::model::id::EmojiId;
/// #
/// # let mut emoji = Emoji {
/// # id: EmojiId(7),
@@ -88,7 +89,8 @@ impl Emoji {
/// Change the name of an emoji:
///
/// ```rust,no_run
- /// # use serenity::model::{Emoji, EmojiId};
+ /// # use serenity::model::guild::Emoji;
+ /// # use serenity::model::id::EmojiId;
/// #
/// # let mut emoji = Emoji {
/// # id: EmojiId(7),
@@ -132,7 +134,8 @@ impl Emoji {
/// Print the guild id that owns this emoji:
///
/// ```rust,no_run
- /// # use serenity::model::{Emoji, EmojiId};
+ /// # use serenity::model::guild::Emoji;
+ /// # use serenity::model::id::EmojiId;
/// #
/// # let mut emoji = Emoji {
/// # id: EmojiId(7),
@@ -167,7 +170,8 @@ impl Emoji {
/// Print the direct link to the given emoji:
///
/// ```rust,no_run
- /// # use serenity::model::{Emoji, EmojiId};
+ /// # use serenity::model::guild::Emoji;
+ /// # use serenity::model::id::EmojiId;
/// #
/// # let mut emoji = Emoji {
/// # id: EmojiId(7),
diff --git a/src/model/guild/guild_id.rs b/src/model/guild/guild_id.rs
index 37b3886..ad5866d 100644
--- a/src/model/guild/guild_id.rs
+++ b/src/model/guild/guild_id.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
#[cfg(all(feature = "cache", feature = "model"))]
use CACHE;
@@ -73,11 +73,11 @@ impl GuildId {
/// Gets a list of the guild's audit log entries
#[inline]
- pub fn audit_logs(&self, action_type: Option<u8>,
- user_id: Option<UserId>,
+ pub fn audit_logs(&self, action_type: Option<u8>,
+ user_id: Option<UserId>,
before: Option<AuditLogEntryId>,
- limit: Option<u8>) -> Result<AuditLogs> {
- http::get_audit_logs(self.0, action_type, user_id.map(|u| u.0), before.map(|a| a.0), limit)
+ limit: Option<u8>) -> Result<AuditLogs> {
+ http::get_audit_logs(self.0, action_type, user_id.map(|u| u.0), before.map(|a| a.0), limit)
}
/// Gets all of the guild's channels over the REST API.
diff --git a/src/model/guild/member.rs b/src/model/guild/member.rs
index 5353fd4..0e8c4f6 100644
--- a/src/model/guild/member.rs
+++ b/src/model/guild/member.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
use chrono::{DateTime, FixedOffset};
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::deserialize_sync_user;
diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs
index 32b5ee2..d6a2c50 100644
--- a/src/model/guild/mod.rs
+++ b/src/model/guild/mod.rs
@@ -1,3 +1,5 @@
+//! Models relating to guilds and types that it owns.
+
mod emoji;
mod guild_id;
mod integration;
@@ -15,7 +17,7 @@ pub use self::role::*;
pub use self::audit_log::*;
use chrono::{DateTime, FixedOffset};
-use model::*;
+use model::prelude::*;
use serde::de::Error as DeError;
use serde_json;
use super::utils::*;
@@ -1363,7 +1365,7 @@ impl Guild {
/// Obtain a reference to a [`Role`] by its name.
///
/// ```rust,no_run
- /// use serenity::model::*;
+ /// use serenity::model::prelude::*;
/// use serenity::prelude::*;
///
/// struct Handler;
@@ -1583,6 +1585,19 @@ fn closest_to_origin(origin: &str, word_a: &str, word_b: &str) -> std::cmp::Orde
value_a.cmp(&value_b)
}
+/// A container for guilds.
+///
+/// This is used to differentiate whether a guild itself can be used or whether
+/// a guild needs to be retrieved from the cache.
+#[allow(large_enum_variant)]
+#[derive(Clone, Debug)]
+pub enum GuildContainer {
+ /// A guild which can have its contents directly searched.
+ Guild(PartialGuild),
+ /// A guild's id, which can be used to search the cache for a guild.
+ Id(GuildId),
+}
+
/// Information relating to a guild's widget embed.
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct GuildEmbed {
@@ -1747,6 +1762,46 @@ impl MfaLevel {
}
}
+/// The name of a region that a voice server can be located in.
+#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
+pub enum Region {
+ #[serde(rename = "amsterdam")] Amsterdam,
+ #[serde(rename = "brazil")] Brazil,
+ #[serde(rename = "eu-central")] EuCentral,
+ #[serde(rename = "eu-west")] EuWest,
+ #[serde(rename = "frankfurt")] Frankfurt,
+ #[serde(rename = "london")] London,
+ #[serde(rename = "sydney")] Sydney,
+ #[serde(rename = "us-central")] UsCentral,
+ #[serde(rename = "us-east")] UsEast,
+ #[serde(rename = "us-south")] UsSouth,
+ #[serde(rename = "us-west")] UsWest,
+ #[serde(rename = "vip-amsterdam")] VipAmsterdam,
+ #[serde(rename = "vip-us-east")] VipUsEast,
+ #[serde(rename = "vip-us-west")] VipUsWest,
+}
+
+impl Region {
+ pub fn name(&self) -> &str {
+ match *self {
+ Region::Amsterdam => "amsterdam",
+ Region::Brazil => "brazil",
+ Region::EuCentral => "eu-central",
+ Region::EuWest => "eu-west",
+ Region::Frankfurt => "frankfurt",
+ Region::London => "london",
+ Region::Sydney => "sydney",
+ Region::UsCentral => "us-central",
+ Region::UsEast => "us-east",
+ Region::UsSouth => "us-south",
+ Region::UsWest => "us-west",
+ Region::VipAmsterdam => "vip-amsterdam",
+ Region::VipUsEast => "vip-us-east",
+ Region::VipUsWest => "vip-us-west",
+ }
+ }
+}
+
enum_number!(
#[doc="The level to set as criteria prior to a user being able to send
messages in a [`Guild`].
diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs
index 857ef0d..d5312b5 100644
--- a/src/model/guild/partial_guild.rs
+++ b/src/model/guild/partial_guild.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
use super::super::utils::{deserialize_emojis, deserialize_roles};
#[cfg(feature = "model")]
@@ -448,7 +448,7 @@ impl PartialGuild {
/// Obtain a reference to a [`Role`] by its name.
///
/// ```rust,no_run
- /// use serenity::model::*;
+ /// use serenity::model::prelude::*;
/// use serenity::prelude::*;
///
/// struct Handler;
@@ -457,8 +457,10 @@ impl PartialGuild {
///
/// impl EventHandler for Handler {
/// fn message(&self, _: Context, msg: Message) {
- /// if let Some(role) =
- /// msg.guild_id().unwrap().get().unwrap().role_by_name("role_name") {
+ /// let guild = msg.guild_id().unwrap().get().unwrap();
+ /// let possible_role = guild.role_by_name("role_name");
+ ///
+ /// if let Some(role) = possible_role {
/// println!("Obtained role's reference: {:?}", role);
/// }
/// }
diff --git a/src/model/guild/role.rs b/src/model/guild/role.rs
index 97a9cf6..6215c4e 100644
--- a/src/model/guild/role.rs
+++ b/src/model/guild/role.rs
@@ -1,4 +1,4 @@
-use model::*;
+use model::prelude::*;
use std::cmp::Ordering;
#[cfg(all(feature = "builder", feature = "cache", feature = "model"))]
@@ -79,7 +79,7 @@ impl Role {
/// Make a role hoisted:
///
/// ```rust,no_run
- /// # use serenity::model::RoleId;
+ /// # use serenity::model::id::RoleId;
/// # let role = RoleId(7).find().unwrap();
/// // assuming a `role` has already been bound
//
diff --git a/src/model/id.rs b/src/model/id.rs
new file mode 100644
index 0000000..3d8c20c
--- /dev/null
+++ b/src/model/id.rs
@@ -0,0 +1,89 @@
+//! A collection of newtypes defining type-strong IDs.
+
+use chrono::NaiveDateTime;
+use internal::prelude::*;
+use serde::de::{Deserialize, Deserializer};
+use std::fmt::{Display, Formatter, Result as FmtResult};
+use super::utils::U64Visitor;
+
+macro_rules! id_u64 {
+ ($(#[$attr:meta] $name:ident;)*) => {
+ $(
+ #[$attr]
+ #[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialOrd, Ord, Serialize)]
+ #[allow(derive_hash_xor_eq)]
+ pub struct $name(pub u64);
+
+ impl $name {
+ /// Retrieves the time that the Id was created at.
+ pub fn created_at(&self) -> NaiveDateTime {
+ let offset = (self.0 >> 22) / 1000;
+
+ NaiveDateTime::from_timestamp(1_420_070_400 + offset as i64, 0)
+ }
+ }
+
+ // This is a hack so functions can accept iterators that either:
+ // 1. return the id itself (e.g: `MessageId`)
+ // 2. return a reference to it (`&MessageId`).
+ impl AsRef<$name> for $name {
+ fn as_ref(&self) -> &Self {
+ self
+ }
+ }
+
+ impl From<u64> for $name {
+ fn from(id_as_u64: u64) -> $name {
+ $name(id_as_u64)
+ }
+ }
+
+ impl PartialEq for $name {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+ }
+
+ impl PartialEq<u64> for $name {
+ fn eq(&self, u: &u64) -> bool {
+ self.0 == *u
+ }
+ }
+
+ impl Display for $name {
+ fn fmt(&self, f: &mut Formatter) -> FmtResult {
+ Display::fmt(&self.0, f)
+ }
+ }
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
+ deserializer.deserialize_any(U64Visitor).map($name)
+ }
+ }
+ )*
+ }
+}
+
+id_u64! {
+ /// An identifier for an Application.
+ ApplicationId;
+ /// An identifier for a Channel
+ ChannelId;
+ /// An identifier for an Emoji
+ EmojiId;
+ /// An identifier for a Guild
+ GuildId;
+ /// An identifier for an Integration
+ IntegrationId;
+ /// An identifier for a Message
+ MessageId;
+ /// An identifier for a Role
+ RoleId;
+ /// An identifier for a User
+ UserId;
+ /// An identifier for a [`Webhook`](struct.Webhook.html).
+ WebhookId;
+ /// An identifier for an audit log entry.
+ AuditLogEntryId;
+}
diff --git a/src/model/invite.rs b/src/model/invite.rs
index 8e5c18b..ed3455c 100644
--- a/src/model/invite.rs
+++ b/src/model/invite.rs
@@ -1,5 +1,7 @@
+//! Models for server and channel invites.
+
use chrono::{DateTime, FixedOffset};
-use super::*;
+use super::prelude::*;
#[cfg(feature = "model")]
use builder::CreateInvite;
@@ -123,7 +125,7 @@ impl Invite {
/// Retrieve the URL for an invite with the code `WxZumR`:
///
/// ```rust
- /// # use serenity::model::*;
+ /// # use serenity::model::prelude::*;
/// #
/// # let invite = Invite {
/// # approximate_member_count: Some(1812),
@@ -289,7 +291,7 @@ impl RichInvite {
/// Retrieve the URL for an invite with the code `WxZumR`:
///
/// ```rust
- /// # use serenity::model::*;
+ /// # use serenity::model::prelude::*;
/// #
/// # let invite = RichInvite {
/// # code: "WxZumR".to_string(),
diff --git a/src/model/misc.rs b/src/model/misc.rs
index b959115..ee048af 100644
--- a/src/model/misc.rs
+++ b/src/model/misc.rs
@@ -1,4 +1,6 @@
-use super::*;
+//! Miscellaneous helper traits, enums, and structs for models.
+
+use super::prelude::*;
use internal::RwLockExt;
#[cfg(all(feature = "model", feature = "utils"))]
diff --git a/src/model/mod.rs b/src/model/mod.rs
index 1dd5192..6ecf343 100644
--- a/src/model/mod.rs
+++ b/src/model/mod.rs
@@ -3,37 +3,46 @@
//!
//! Models can optionally have additional helper methods compiled, by enabling
//! the `model` feature.
+//!
+//! Normally you can import models through the sub-modules:
+//!
+//! ```rust,no_run
+//! use serenity::model::channel::{ChannelType, GuildChannel, Message};
+//! use serenity::model::id::{ChannelId, GuildId};
+//! use serenity::model::user::User;
+//! ```
+//!
+//! This can get a bit tedious - especially with a large number of imports - so
+//! this can be simplified by simply glob importing everything from the prelude:
+//!
+//! ```rust,no_run
+//! use serenity::model::prelude::*;
+//! ```
#[macro_use]
mod utils;
+pub mod application;
+pub mod channel;
+pub mod error;
pub mod event;
+pub mod gateway;
+pub mod guild;
+pub mod id;
+pub mod invite;
+pub mod misc;
pub mod permissions;
+pub mod prelude;
+pub mod user;
+pub mod voice;
+pub mod webhook;
-mod channel;
-mod error;
-mod gateway;
-mod guild;
-mod invite;
-mod misc;
-mod user;
-mod voice;
-mod webhook;
-
-pub use self::channel::*;
pub use self::error::Error as ModelError;
-pub use self::gateway::*;
-pub use self::guild::*;
-pub use self::invite::*;
-pub use self::misc::*;
pub use self::permissions::Permissions;
-pub use self::user::*;
-pub use self::voice::*;
-pub use self::webhook::*;
-use chrono::NaiveDateTime;
use internal::prelude::*;
use parking_lot::RwLock;
+use self::id::GuildId;
use self::utils::*;
use serde::de::Visitor;
use std::collections::HashMap;
@@ -43,226 +52,5 @@ use std::sync::Arc;
#[cfg(feature = "utils")]
use utils::Colour;
-fn default_true() -> bool { true }
-
-macro_rules! id_u64 {
- ($(#[$attr:meta] $name:ident;)*) => {
- $(
- #[$attr]
- #[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialOrd, Ord, Serialize)]
- #[allow(derive_hash_xor_eq)]
- pub struct $name(pub u64);
-
- impl $name {
- /// Retrieves the time that the Id was created at.
- pub fn created_at(&self) -> NaiveDateTime {
- let offset = (self.0 >> 22) / 1000;
-
- NaiveDateTime::from_timestamp(1_420_070_400 + offset as i64, 0)
- }
- }
-
- // This is a hack so functions can accept iterators that either:
- // 1. return the id itself (e.g: `MessageId`)
- // 2. return a reference to it (`&MessageId`).
- impl AsRef<$name> for $name {
- fn as_ref(&self) -> &Self {
- self
- }
- }
-
- impl From<u64> for $name {
- fn from(id_as_u64: u64) -> $name {
- $name(id_as_u64)
- }
- }
-
- impl PartialEq for $name {
- fn eq(&self, other: &Self) -> bool {
- self.0 == other.0
- }
- }
-
- impl PartialEq<u64> for $name {
- fn eq(&self, u: &u64) -> bool {
- self.0 == *u
- }
- }
-
- impl Display for $name {
- fn fmt(&self, f: &mut Formatter) -> FmtResult {
- Display::fmt(&self.0, f)
- }
- }
-
- impl<'de> Deserialize<'de> for $name {
- fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
- deserializer.deserialize_any(U64Visitor).map($name)
- }
- }
- )*
- }
-}
-
-id_u64! {
- /// An identifier for an Application.
- ApplicationId;
- /// An identifier for a Channel
- ChannelId;
- /// An identifier for an Emoji
- EmojiId;
- /// An identifier for a Guild
- GuildId;
- /// An identifier for an Integration
- IntegrationId;
- /// An identifier for a Message
- MessageId;
- /// An identifier for a Role
- RoleId;
- /// An identifier for a User
- UserId;
- /// An identifier for a [`Webhook`](struct.Webhook.html).
- WebhookId;
- /// An identifier for an audit log entry.
- AuditLogEntryId;
-}
-
-/// A container for guilds.
-///
-/// This is used to differentiate whether a guild itself can be used or whether
-/// a guild needs to be retrieved from the cache.
-#[allow(large_enum_variant)]
-#[derive(Clone, Debug)]
-pub enum GuildContainer {
- /// A guild which can have its contents directly searched.
- Guild(PartialGuild),
- /// A guild's id, which can be used to search the cache for a guild.
- Id(GuildId),
-}
-
-/// Information about a user's application. An application does not necessarily
-/// have an associated bot user.
-#[derive(Clone, Debug, Deserialize)]
-pub struct ApplicationInfo {
- /// The bot user associated with the application. See [`BotApplication`] for
- /// more information.
- ///
- /// [`BotApplication`]: struct.BotApplication.html
- pub bot: Option<BotApplication>,
- /// Indicator of whether the bot is public.
- ///
- /// If a bot is public, anyone may invite it to their [`Guild`]. While a bot
- /// is private, only the owner may add it to a guild.
- ///
- /// [`Guild`]: struct.Guild.html
- #[serde(default = "default_true")]
- pub bot_public: bool,
- /// Indicator of whether the bot requires an OAuth2 code grant.
- pub bot_require_code_grant: bool,
- /// A description of the application, assigned by the application owner.
- pub description: String,
- /// A set of bitflags assigned to the application, which represent gated
- /// feature flags that have been enabled for the application.
- pub flags: Option<u64>,
- /// A hash pointing to the application's icon.
- ///
- /// This is not necessarily equivalent to the bot user's avatar.
- pub icon: Option<String>,
- /// The unique numeric Id of the application.
- pub id: UserId,
- /// The name assigned to the application by the application owner.
- pub name: String,
- /// A list of redirect URIs assigned to the application.
- pub redirect_uris: Vec<String>,
- /// A list of RPC Origins assigned to the application.
- pub rpc_origins: Vec<String>,
- /// The given secret to the application.
- ///
- /// This is not equivalent to the application's bot user's token.
- pub secret: String,
-}
-
-/// Information about an application with an application's bot user.
-#[derive(Clone, Debug, Deserialize)]
-pub struct BotApplication {
- /// The unique Id of the bot user.
- pub id: UserId,
- /// A hash of the avatar, if one is assigned.
- ///
- /// Can be used to generate a full URL to the avatar.
- pub avatar: Option<String>,
- /// Indicator of whether it is a bot.
- #[serde(default)]
- pub bot: bool,
- /// The discriminator assigned to the bot user.
- ///
- /// While discriminators are not unique, the `username#discriminator` pair
- /// is.
- pub discriminator: u16,
- /// The bot user's username.
- pub name: String,
- /// The token used to authenticate as the bot user.
- ///
- /// **Note**: Keep this information private, as untrusted sources can use it
- /// to perform any action with a bot user.
- pub token: String,
-}
-
-/// Information about the current application and its owner.
-#[derive(Clone, Debug, Deserialize)]
-pub struct CurrentApplicationInfo {
- pub description: String,
- pub icon: Option<String>,
- pub id: UserId,
- pub name: String,
- pub owner: User,
- #[serde(default)] pub rpc_origins: Vec<String>,
-}
-
-/// The name of a region that a voice server can be located in.
-#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
-pub enum Region {
- #[serde(rename = "amsterdam")] Amsterdam,
- #[serde(rename = "brazil")] Brazil,
- #[serde(rename = "eu-central")] EuCentral,
- #[serde(rename = "eu-west")] EuWest,
- #[serde(rename = "frankfurt")] Frankfurt,
- #[serde(rename = "london")] London,
- #[serde(rename = "sydney")] Sydney,
- #[serde(rename = "us-central")] UsCentral,
- #[serde(rename = "us-east")] UsEast,
- #[serde(rename = "us-south")] UsSouth,
- #[serde(rename = "us-west")] UsWest,
- #[serde(rename = "vip-amsterdam")] VipAmsterdam,
- #[serde(rename = "vip-us-east")] VipUsEast,
- #[serde(rename = "vip-us-west")] VipUsWest,
-}
-
-impl Region {
- pub fn name(&self) -> &str {
- match *self {
- Region::Amsterdam => "amsterdam",
- Region::Brazil => "brazil",
- Region::EuCentral => "eu-central",
- Region::EuWest => "eu-west",
- Region::Frankfurt => "frankfurt",
- Region::London => "london",
- Region::Sydney => "sydney",
- Region::UsCentral => "us-central",
- Region::UsEast => "us-east",
- Region::UsSouth => "us-south",
- Region::UsWest => "us-west",
- Region::VipAmsterdam => "vip-amsterdam",
- Region::VipUsEast => "vip-us-east",
- Region::VipUsWest => "vip-us-west",
- }
- }
-}
-
use serde::{Deserialize, Deserializer};
use std::result::Result as StdResult;
-
-fn deserialize_sync_user<'de, D: Deserializer<'de>>(deserializer: D)
- -> StdResult<Arc<RwLock<User>>, D::Error> {
- Ok(Arc::new(RwLock::new(User::deserialize(deserializer)?)))
-}
diff --git a/src/model/prelude.rs b/src/model/prelude.rs
new file mode 100644
index 0000000..b03a02a
--- /dev/null
+++ b/src/model/prelude.rs
@@ -0,0 +1,25 @@
+//! The model prelude re-exports all types in the model sub-modules.
+//!
+//! This allows for quick and easy access to all of the model types.
+//!
+//! # Examples
+//!
+//! Import all model types into scope:
+//!
+//! ```rust,no_run
+//! use serenity::model::prelude::*;
+//! ```
+
+pub use super::application::*;
+pub use super::channel::*;
+pub use super::event::*;
+pub use super::guild::*;
+pub use super::gateway::*;
+pub use super::id::*;
+pub use super::invite::*;
+pub use super::misc::*;
+pub use super::permissions::*;
+pub use super::user::*;
+pub use super::voice::*;
+pub use super::webhook::*;
+pub use super::*;
diff --git a/src/model/user.rs b/src/model/user.rs
index 2732f2b..6068da1 100644
--- a/src/model/user.rs
+++ b/src/model/user.rs
@@ -1,7 +1,9 @@
+//! User information-related models.
+
use serde_json;
use std::fmt;
use super::utils::deserialize_u16;
-use super::*;
+use super::prelude::*;
use internal::prelude::*;
use model::misc::Mentionable;
@@ -159,7 +161,7 @@ impl CurrentUser {
/// #
/// # let mut cache = CACHE.write();
///
- /// use serenity::model::permissions::Permissions;
+ /// use serenity::model::Permissions;
///
/// // assuming the cache has been unlocked
/// let url = match cache.user.invite_url(Permissions::empty()) {
@@ -408,7 +410,7 @@ impl User {
///
/// ```rust,no_run
/// # use serenity::prelude::*;
- /// # use serenity::model::*;
+ /// # use serenity::model::prelude::*;
/// #
/// use serenity::model::Permissions;
/// use serenity::CACHE;
@@ -611,7 +613,7 @@ impl User {
///
/// ```rust,no_run
/// # use serenity::prelude::*;
- /// # use serenity::model::*;
+ /// # use serenity::model::prelude::*;
/// #
/// struct Handler;
///
@@ -623,7 +625,7 @@ impl User {
///
/// let mut client = Client::new("token", Handler).unwrap();
/// #
- /// use serenity::model::UserId;
+ /// use serenity::model::id::UserId;
/// use serenity::CACHE;
/// use std::thread;
/// use std::time::Duration;
@@ -680,7 +682,7 @@ impl User {
///
/// ```rust,no_run
/// # use serenity::prelude::*;
- /// # use serenity::model::*;
+ /// # use serenity::model::prelude::*;
/// #
/// use serenity::utils::MessageBuilder;
/// use serenity::utils::ContentModifier::Bold;
diff --git a/src/model/utils.rs b/src/model/utils.rs
index 52e3bbc..9d4ca88 100644
--- a/src/model/utils.rs
+++ b/src/model/utils.rs
@@ -2,7 +2,7 @@ use parking_lot::RwLock;
use serde::de::Error as DeError;
use std::collections::HashMap;
use std::sync::Arc;
-use super::*;
+use super::prelude::*;
#[cfg(feature = "cache")]
use internal::prelude::*;
@@ -12,6 +12,10 @@ use super::permissions::Permissions;
#[cfg(all(feature = "cache", feature = "model"))]
use CACHE;
+pub fn default_true() -> bool {
+ true
+}
+
pub fn deserialize_emojis<'de, D: Deserializer<'de>>(
deserializer: D)
-> StdResult<HashMap<EmojiId, Emoji>, D::Error> {
@@ -112,6 +116,11 @@ pub fn deserialize_single_recipient<'de, D: Deserializer<'de>>(
Ok(Arc::new(RwLock::new(user)))
}
+pub fn deserialize_sync_user<'de, D>(deserializer: D)
+ -> StdResult<Arc<RwLock<User>>, D::Error> where D: Deserializer<'de> {
+ Ok(Arc::new(RwLock::new(User::deserialize(deserializer)?)))
+}
+
pub fn deserialize_users<'de, D: Deserializer<'de>>(
deserializer: D)
-> StdResult<HashMap<UserId, Arc<RwLock<User>>>, D::Error> {
diff --git a/src/model/voice.rs b/src/model/voice.rs
index 10c74b2..558be4f 100644
--- a/src/model/voice.rs
+++ b/src/model/voice.rs
@@ -1,4 +1,6 @@
-use super::*;
+//! Representations of voice information.
+
+use super::id::{ChannelId, UserId};
/// Information about an available voice region.
#[derive(Clone, Debug, Deserialize)]
diff --git a/src/model/webhook.rs b/src/model/webhook.rs
index 2bb1c49..d834502 100644
--- a/src/model/webhook.rs
+++ b/src/model/webhook.rs
@@ -1,4 +1,8 @@
-use super::*;
+//! Webhook model and implementations.
+
+use super::channel::Message;
+use super::id::{ChannelId, GuildId, WebhookId};
+use super::user::User;
#[cfg(feature = "model")]
use builder::ExecuteWebhook;
@@ -157,7 +161,7 @@ impl Webhook {
///
/// ```rust,no_run
/// use serenity::http;
- /// use serenity::model::Embed;
+ /// use serenity::model::channel::Embed;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";