code
stringlengths
40
729k
docstring
stringlengths
22
46.3k
func_name
stringlengths
1
97
language
stringclasses
1 value
repo
stringlengths
6
48
path
stringlengths
8
176
url
stringlengths
47
228
license
stringclasses
7 values
pub fn emoji( &self, emoji_id: Id<EmojiMarker>, ) -> Option<Reference<'_, Id<EmojiMarker>, GuildResource<CacheModels::Emoji>>> { self.emojis.get(&emoji_id).map(Reference::new) }
Gets an emoji by ID. This requires the [`GUILD_EMOJIS_AND_STICKERS`] intent. [`GUILD_EMOJIS_AND_STICKERS`]: ::twilight_model::gateway::Intents::GUILD_EMOJIS_AND_STICKERS
emoji
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, CacheModels::Guild>> { self.guilds.get(&guild_id).map(Reference::new) }
Gets a guild by ID. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
guild
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_channels( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<ChannelMarker>>>> { self.guild_channels.get(&guild_id).map(Reference::new) }
Gets the set of channels in a guild. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
guild_channels
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_emojis( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<EmojiMarker>>>> { self.guild_emojis.get(&guild_id).map(Reference::new) }
Gets the set of emojis in a guild. This requires both the [`GUILDS`] and [`GUILD_EMOJIS_AND_STICKERS`] intents. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS [`GUILD_EMOJIS_AND_STICKERS`]: ::twilight_model::gateway::Intents::GUILD_EMOJIS_AND_STICKERS
guild_emojis
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_integrations( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<IntegrationMarker>>>> { self.guild_integrations.get(&guild_id).map(Reference::new) }
Gets the set of integrations in a guild. This requires the [`GUILD_INTEGRATIONS`] intent. The [`ResourceType::INTEGRATION`] resource type must be enabled. [`GUILD_INTEGRATIONS`]: twilight_model::gateway::Intents::GUILD_INTEGRATIONS
guild_integrations
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_members( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>> { self.guild_members.get(&guild_id).map(Reference::new) }
Gets the set of members in a guild. This list may be incomplete if not all members have been cached. This requires the [`GUILD_MEMBERS`] intent. [`GUILD_MEMBERS`]: ::twilight_model::gateway::Intents::GUILD_MEMBERS
guild_members
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_presences( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>> { self.guild_presences.get(&guild_id).map(Reference::new) }
Gets the set of presences in a guild. This list may be incomplete if not all members have been cached. This requires the [`GUILD_PRESENCES`] intent. [`GUILD_PRESENCES`]: ::twilight_model::gateway::Intents::GUILD_PRESENCES
guild_presences
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_roles( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<RoleMarker>>>> { self.guild_roles.get(&guild_id).map(Reference::new) }
Gets the set of roles in a guild. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
guild_roles
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn scheduled_events( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<ScheduledEventMarker>>>> { self.guild_scheduled_events .get(&guild_id) .map(Reference::new) }
Gets the scheduled events in a guild. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
scheduled_events
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_stage_instances( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<StageMarker>>>> { self.guild_stage_instances .get(&guild_id) .map(Reference::new) }
Gets the set of stage instances in a guild. This requires the [`GUILDS`] intent. [`GUILDS`]: twilight_model::gateway::Intents::GUILDS
guild_stage_instances
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_stickers( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<StickerMarker>>>> { self.guild_stickers.get(&guild_id).map(Reference::new) }
Gets the set of the stickers in a guild. This is an O(m) operation, where m is the amount of stickers in the guild. This requires the [`GUILDS`] and [`GUILD_EMOJIS_AND_STICKERS`] intents and the [`STICKER`] resource type. [`GUILDS`]: twilight_model::gateway::Intents::GUILDS [`GUILD_EMOJIS_AND_STICKERS`]: ::twilight_model::gateway::Intents::GUILD_EMOJIS_AND_STICKERS [`STICKER`]: crate::config::ResourceType::STICKER
guild_stickers
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn guild_voice_states( &self, guild_id: Id<GuildMarker>, ) -> Option<Reference<'_, Id<GuildMarker>, HashSet<Id<UserMarker>>>> { self.voice_state_guilds.get(&guild_id).map(Reference::new) }
Gets the set of voice states in a guild. This requires both the [`GUILDS`] and [`GUILD_VOICE_STATES`] intents. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS [`GUILD_VOICE_STATES`]: ::twilight_model::gateway::Intents::GUILD_VOICE_STATES
guild_voice_states
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn message( &self, message_id: Id<MessageMarker>, ) -> Option<Reference<'_, Id<MessageMarker>, CacheModels::Message>> { self.messages.get(&message_id).map(Reference::new) }
Gets a message by ID. This requires one or both of the [`GUILD_MESSAGES`] or [`DIRECT_MESSAGES`] intents. [`GUILD_MESSAGES`]: ::twilight_model::gateway::Intents::GUILD_MESSAGES [`DIRECT_MESSAGES`]: ::twilight_model::gateway::Intents::DIRECT_MESSAGES
message
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn role( &self, role_id: Id<RoleMarker>, ) -> Option<Reference<'_, Id<RoleMarker>, GuildResource<CacheModels::Role>>> { self.roles.get(&role_id).map(Reference::new) }
Gets a role by ID. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
role
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn scheduled_event( &self, event_id: Id<ScheduledEventMarker>, ) -> Option< Reference<'_, Id<ScheduledEventMarker>, GuildResource<CacheModels::GuildScheduledEvent>>, > { self.scheduled_events.get(&event_id).map(Reference::new) }
Gets a scheduled event by ID. This requires the [`GUILDS`] intent. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS
scheduled_event
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn stage_instance( &self, stage_id: Id<StageMarker>, ) -> Option<Reference<'_, Id<StageMarker>, GuildResource<CacheModels::StageInstance>>> { self.stage_instances.get(&stage_id).map(Reference::new) }
Gets a stage instance by ID. This requires the [`GUILDS`] intent. [`GUILDS`]: twilight_model::gateway::Intents::GUILDS
stage_instance
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn sticker( &self, sticker_id: Id<StickerMarker>, ) -> Option<Reference<'_, Id<StickerMarker>, GuildResource<CacheModels::Sticker>>> { self.stickers.get(&sticker_id).map(Reference::new) }
Gets a sticker by ID. This is the O(1) operation. This requires the [`GUILDS`] and the [`GUILD_EMOJIS_AND_STICKERS`] intents and the [`STICKER`] resource type. [`GUILDS`]: twilight_model::gateway::Intents::GUILDS [`GUILD_EMOJIS_AND_STICKERS`]: ::twilight_model::gateway::Intents::GUILD_EMOJIS_AND_STICKERS [`STICKER`]: crate::config::ResourceType::STICKER
sticker
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn user( &self, user_id: Id<UserMarker>, ) -> Option<Reference<'_, Id<UserMarker>, CacheModels::User>> { self.users.get(&user_id).map(Reference::new) }
Gets a user by ID. This requires the [`GUILD_MEMBERS`] intent. [`GUILD_MEMBERS`]: ::twilight_model::gateway::Intents::GUILD_MEMBERS
user
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn user_guilds( &self, user_id: Id<UserMarker>, ) -> Option<Reference<'_, Id<UserMarker>, HashSet<Id<GuildMarker>>>> { self.user_guilds.get(&user_id).map(Reference::new) }
Get the guilds a user is in by ID. Users are cached from a range of events such as [`InteractionCreate`] and [`MemberAdd`], so although no specific intent is required to cache users the intents required for different events are required. Requires the [`USER`] resource type. [`MemberAdd`]: twilight_model::gateway::payload::incoming::MemberAdd [`InteractionCreate`]: twilight_model::gateway::payload::incoming::InteractionCreate [`USER`]: crate::config::ResourceType::USER
user_guilds
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn voice_channel_states( &self, channel_id: Id<ChannelMarker>, ) -> Option<VoiceChannelStates<'_, CacheModels::VoiceState>> { let user_ids = self.voice_state_channels.get(&channel_id)?; Some(VoiceChannelStates { index: 0, user_ids, voice_states: &self.voice_states, }) }
Gets the voice states within a voice channel. This requires both the [`GUILDS`] and [`GUILD_VOICE_STATES`] intents. [`GUILDS`]: ::twilight_model::gateway::Intents::GUILDS [`GUILD_VOICE_STATES`]: ::twilight_model::gateway::Intents::GUILD_VOICE_STATES
voice_channel_states
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub fn member_highest_role( &self, guild_id: Id<GuildMarker>, user_id: Id<UserMarker>, ) -> Option<Id<RoleMarker>> { let member = self.members.get(&(guild_id, user_id))?; let mut highest_role: Option<(i64, Id<RoleMarker>)> = None; for role_id in member.roles() { if let Some(role) = self.role(*role_id) { if let Some((position, id)) = highest_role { if role.position() < position || (role.position() == position && role.id() > id) { continue; } } highest_role = Some((role.position(), role.id())); } } highest_role.map(|(_, id)| id) }
Gets the highest role of a member. This requires both the [`GUILDS`] and [`GUILD_MEMBERS`] intents. [`GUILDS`]: twilight_model::gateway::Intents::GUILDS [`GUILD_MEMBERS`]: twilight_model::gateway::Intents::GUILD_MEMBERS
member_highest_role
rust
twilight-rs/twilight
twilight-cache-inmemory/src/lib.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs
ISC
pub const fn check_member_communication_disabled( mut self, check_member_communication_disabled: bool, ) -> Self { self.check_member_communication_disabled = check_member_communication_disabled; self }
Whether to check whether a [member's communication is disabled][field]. Refer to the [module level] documentation for information and caveats. Defaults to being enabled. [field]: crate::model::CachedMember::communication_disabled_until [module level]: crate::permission
check_member_communication_disabled
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
pub fn in_channel( &self, user_id: Id<UserMarker>, channel_id: Id<ChannelMarker>, ) -> Result<Permissions, ChannelError> { let channel = self.cache.channels.get(&channel_id).ok_or(ChannelError { kind: ChannelErrorType::ChannelUnavailable { channel_id }, source: None, })?; let guild_id = channel.guild_id().ok_or(ChannelError { kind: ChannelErrorType::ChannelNotInGuild { channel_id }, source: None, })?; if self.is_owner(user_id, guild_id) { return Ok(Permissions::all()); } let member = self.cache.member(guild_id, user_id).ok_or(ChannelError { kind: ChannelErrorType::MemberUnavailable { guild_id, user_id }, source: None, })?; let MemberRoles { assigned, everyone } = self .member_roles(guild_id, &member) .map_err(ChannelError::from_member_roles)?; let overwrites = match channel.kind() { ChannelType::AnnouncementThread | ChannelType::PrivateThread | ChannelType::PublicThread => self.parent_overwrites(&channel)?, _ => channel.permission_overwrites().unwrap_or_default().to_vec(), }; let calculator = PermissionCalculator::new(guild_id, user_id, everyone, assigned.as_slice()); let permissions = calculator.in_channel(channel.kind(), overwrites.as_slice()); Ok(self.disable_member_communication(&member, permissions)) }
Calculate the permissions of a member in a guild channel. Returns [`Permissions::all`] if the user is the owner of the guild. If the member's [communication has been disabled] then they will be restricted to [read-only permissions]. Refer to the [module level] documentation for more information. The following [`ResourceType`]s must be enabled: - [`ResourceType::CHANNEL`] - [`ResourceType::MEMBER`] - [`ResourceType::ROLE`] # Examples ```no_run # fn main() -> Result<(), Box<dyn std::error::Error>> { use twilight_cache_inmemory::DefaultInMemoryCache; use twilight_model::id::Id; let cache = DefaultInMemoryCache::new(); // later on... let channel_id = Id::new(4); let user_id = Id::new(5); let permissions = cache.permissions().in_channel(user_id, channel_id)?; println!("User {user_id} in channel {channel_id} has permissions {permissions:?}"); # Ok(()) } ``` # Errors Returns a [`ChannelErrorType::ChannelUnavailable`] error type if the guild channel is not in the cache. Returns a [`ChannelErrorType::MemberUnavailable`] error type if the member for the user in the guild is not present. Returns a [`ChannelErrorType::RoleUnavailable`] error type if one of the member's roles is not in the cache. [`Permissions::all`]: twilight_model::guild::Permissions::all [`ResourceType::CHANNEL`]: crate::ResourceType::CHANNEL [`ResourceType::MEMBER`]: crate::ResourceType::MEMBER [`ResourceType::ROLE`]: crate::ResourceType::ROLE [`ResourceType`]: crate::ResourceType [communication has been disabled]: crate::model::CachedMember::communication_disabled_until [module level]: crate::permission [read-only permissions]: MEMBER_COMMUNICATION_DISABLED_ALLOWLIST
in_channel
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
pub fn root( &self, user_id: Id<UserMarker>, guild_id: Id<GuildMarker>, ) -> Result<Permissions, RootError> { if self.is_owner(user_id, guild_id) { return Ok(Permissions::all()); } let member = self.cache.member(guild_id, user_id).ok_or(RootError { kind: RootErrorType::MemberUnavailable { guild_id, user_id }, source: None, })?; let MemberRoles { assigned, everyone } = self .member_roles(guild_id, &member) .map_err(RootError::from_member_roles)?; let calculator = PermissionCalculator::new(guild_id, user_id, everyone, assigned.as_slice()); let permissions = calculator.root(); Ok(self.disable_member_communication(&member, permissions)) }
Calculate the guild-level permissions of a member. Returns [`Permissions::all`] if the user is the owner of the guild. If the member's [communication has been disabled] then they will be restricted to [read-only permissions]. Refer to the [module level] documentation for more information. The following [`ResourceType`]s must be enabled: - [`ResourceType::MEMBER`] - [`ResourceType::ROLE`] # Examples ```no_run # fn main() -> Result<(), Box<dyn std::error::Error>> { use twilight_cache_inmemory::DefaultInMemoryCache; use twilight_model::id::Id; let cache = DefaultInMemoryCache::new(); // later on... let guild_id = Id::new(4); let user_id = Id::new(5); let permissions = cache.permissions().root(user_id, guild_id)?; println!("User {user_id} in guild {guild_id} has permissions {permissions:?}"); # Ok(()) } ``` # Errors Returns a [`RootErrorType::MemberUnavailable`] error type if the member for the user in the guild is not present. Returns a [`RootErrorType::RoleUnavailable`] error type if one of the member's roles is not in the cache. [`Permissions::all`]: twilight_model::guild::Permissions::all [`ResourceType::MEMBER`]: crate::ResourceType::MEMBER [`ResourceType::ROLE`]: crate::ResourceType::ROLE [`ResourceType`]: crate::ResourceType [communication has been disabled]: crate::model::CachedMember::communication_disabled_until [module level]: crate::permission [read-only permissions]: MEMBER_COMMUNICATION_DISABLED_ALLOWLIST
root
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
fn disable_member_communication( &self, member: &CacheModels::Member, permissions: Permissions, ) -> Permissions { // Administrators are never disabled. if !self.check_member_communication_disabled || permissions.contains(Permissions::ADMINISTRATOR) { return permissions; } let micros = if let Some(until) = member.communication_disabled_until() { until.as_micros() } else { return permissions; }; let Ok(absolute) = micros.try_into() else { return permissions; }; let ends = SystemTime::UNIX_EPOCH + Duration::from_micros(absolute); let now = SystemTime::now(); if now > ends { return permissions; } permissions.intersection(MEMBER_COMMUNICATION_DISABLED_ALLOWLIST) }
Determine whether the provided member is disabled and restrict them to [read-only permissions] if they are. Only members whose [`communication_disabled_until`] values is in the future count as being currently disabled. Members with the [administrator permission] are never disabled. [`communication_disabled_until`]: CachedMember::communication_disabled_until [administrator permission]: Permissions::ADMINISTRATOR [read-only permissions]: MEMBER_COMMUNICATION_DISABLED_ALLOWLIST
disable_member_communication
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
fn is_owner(&self, user_id: Id<UserMarker>, guild_id: Id<GuildMarker>) -> bool { self.cache .guilds .get(&guild_id) .is_some_and(|r| r.owner_id() == user_id) }
Determine whether a given user is the owner of a guild. Returns true if the user is or false if the user is definitively not the owner of the guild or the guild is not in the cache.
is_owner
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
fn member_roles( &self, guild_id: Id<GuildMarker>, member: &'a CacheModels::Member, ) -> Result<MemberRoles, MemberRolesErrorType> { let mut member_roles = Vec::with_capacity(member.roles().len()); for role_id in member.roles() { let Some(role) = self.cache.roles.get(role_id) else { return Err(MemberRolesErrorType::RoleMissing { role_id: *role_id }); }; member_roles.push((*role_id, role.permissions())); } let everyone_role_id = guild_id.cast(); if let Some(everyone_role) = self.cache.roles.get(&everyone_role_id) { Ok(MemberRoles { assigned: member_roles, everyone: everyone_role.permissions(), }) } else { Err(MemberRolesErrorType::RoleMissing { role_id: everyone_role_id, }) } }
Retrieve a member's roles' permissions and the guild's `@everyone` role's permissions. # Errors Returns [`MemberRolesErrorType::RoleMissing`] if a role is missing from the cache.
member_roles
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
fn parent_overwrites( &self, thread: &CacheModels::Channel, ) -> Result<Vec<PermissionOverwrite>, ChannelError> { let parent_id = thread.parent_id().ok_or(ChannelError { kind: ChannelErrorType::ParentChannelNotPresent { thread_id: thread.id(), }, source: None, })?; let channel = self.cache.channels.get(&parent_id).ok_or(ChannelError { kind: ChannelErrorType::ChannelUnavailable { channel_id: parent_id, }, source: None, })?; if channel.guild_id().is_some() { let channel_overwrites = channel.permission_overwrites().unwrap_or_default(); let thread_overwrites = thread.permission_overwrites().unwrap_or_default(); let mut overwrites = Vec::with_capacity(channel_overwrites.len() + thread_overwrites.len()); overwrites.extend_from_slice(channel_overwrites); overwrites.extend_from_slice(thread_overwrites); Ok(overwrites) } else { Err(ChannelError { kind: ChannelErrorType::ChannelNotInGuild { channel_id: channel.id(), }, source: None, }) } }
Given a thread channel, retrieve its parent from the cache, and combine parent and child permissions.
parent_overwrites
rust
twilight-rs/twilight
twilight-cache-inmemory/src/permission.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/permission.rs
ISC
pub fn channel_messages(&self, channel_id: Id<ChannelMarker>) -> Option<usize> { let channel = self.0.channel_messages.get(&channel_id)?; Some(channel.len()) }
Number of messages in a given channel in the cache. Returns `None` if the channel hasn't yet been cached or there are no messages in the channel. However, the provided number may still be 0 if some number is returned.
channel_messages
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn channel_voice_states(&self, channel_id: Id<ChannelMarker>) -> Option<usize> { let channel = self.0.voice_state_channels.get(&channel_id)?; Some(channel.len()) }
Number of voice states in a given channel in the cache. Returns `None` if the channel hasn't yet been cached or there are no voice states in the channel. However, the provided number may still be 0 if some number is returned.
channel_voice_states
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_channels(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.guild_channels.get(&guild_id)?; Some(guild.len()) }
Number of channels in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_channels
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_emojis(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.guild_emojis.get(&guild_id)?; Some(guild.len()) }
Number of emojis in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_emojis
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_members(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.guild_members.get(&guild_id)?; Some(guild.len()) }
Number of members in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_members
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_presences(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.guild_presences.get(&guild_id)?; Some(guild.len()) }
Number of presences in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_presences
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_roles(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.guild_roles.get(&guild_id)?; Some(guild.len()) }
Number of roles in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_roles
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub fn guild_voice_states(&self, guild_id: Id<GuildMarker>) -> Option<usize> { let guild = self.0.voice_state_guilds.get(&guild_id)?; Some(guild.len()) }
Number of voice states in a given guild in the cache. Returns `None` if the guild hasn't yet been cached.
guild_voice_states
rust
twilight-rs/twilight
twilight-cache-inmemory/src/stats.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/stats.rs
ISC
pub(crate) fn delete_channel(&self, channel_id: Id<ChannelMarker>) { if let Some((_, channel)) = self.channels.remove(&channel_id) { if let Some(guild_id) = channel.guild_id() { let maybe_channels = self.guild_channels.get_mut(&guild_id); if let Some(mut channels) = maybe_channels { channels.remove(&channel_id); } } } }
Delete a guild channel from the cache. The guild channel data itself and the channel entry in its guild's list of channels will be deleted.
delete_channel
rust
twilight-rs/twilight
twilight-cache-inmemory/src/event/channel.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/event/channel.rs
ISC
pub fn features(&self) -> Features<'_> { Features { inner: self.features.iter(), } }
Enabled [guild features]. [guild features]: https://discord.com/developers/docs/resources/guild#guild-object-guild-features
features
rust
twilight-rs/twilight
twilight-cache-inmemory/src/model/guild.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/model/guild.rs
ISC
pub fn send(&self, json: String) -> Result<(), ChannelError> { self.command.send(json).map_err(|source| ChannelError { kind: ChannelErrorType::Closed, source: Some(Box::new(source)), }) }
Send a JSON encoded gateway event to the associated shard. # Errors Returns a [`ChannelErrorType::Closed`] error type if the channel is closed.
send
rust
twilight-rs/twilight
twilight-gateway/src/channel.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/channel.rs
ISC
pub fn close(&self, close_frame: CloseFrame<'static>) -> Result<(), ChannelError> { if let Err(source @ mpsc::error::TrySendError::Closed(_)) = self.close.try_send(close_frame) { Err(ChannelError { kind: ChannelErrorType::Closed, source: Some(Box::new(source)), }) } else { Ok(()) } }
Send a Websocket close frame to the associated shard. Subsequent calls may be queued up to be sent once the shard's reestablished a Websocket connection or ignored if the queue is full. The internal queue capacity is currently `1`. See the [`Shard::close`] docs for further information. # Errors Returns a [`ChannelErrorType::Closed`] error type if the channel is closed. [`Shard::close`]: crate::Shard::close
close
rust
twilight-rs/twilight
twilight-gateway/src/channel.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/channel.rs
ISC
pub(crate) fn from_utf8_error(source: std::string::FromUtf8Error) -> Self { Self { kind: CompressionErrorType::NotUtf8, source: Some(Box::new(source)), } }
Shortcut to create a new error for a not UTF-8 message.
from_utf8_error
rust
twilight-rs/twilight
twilight-gateway/src/compression.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/compression.rs
ISC
pub fn decompress(&mut self, message: &[u8]) -> Result<String, CompressionError> { let mut input = zstd_safe::InBuffer::around(message); // Decompressed message. `Vec::extend_from_slice` efficiently allocates // only what's necessary. let mut decompressed = Vec::new(); loop { let mut output = zstd_safe::OutBuffer::around(self.buffer.as_mut()); self.ctx .decompress_stream(&mut output, &mut input) .map_err(CompressionError::from_code)?; decompressed.extend_from_slice(output.as_slice()); // Break when message has been fully decompressed. if input.pos == input.src.len() && output.pos() != output.capacity() { break; } } String::from_utf8(decompressed).map_err(CompressionError::from_utf8_error) }
Decompress a message. # Errors Returns a [`CompressionErrorType::Decompressing`] error type if the message could not be decompressed. Returns a [`CompressionErrorType::NotUtf8`] error type if the decompressed message is not UTF-8.
decompress
rust
twilight-rs/twilight
twilight-gateway/src/compression.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/compression.rs
ISC
pub fn new(token: String, intents: Intents) -> Self { ConfigBuilder::new(token, intents).build() }
Create a new default shard configuration. # Panics Panics if loading TLS certificates fails.
new
rust
twilight-rs/twilight
twilight-gateway/src/config.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/config.rs
ISC
pub fn new(mut token: String, intents: Intents) -> Self { if !token.starts_with("Bot ") { token.insert_str(0, "Bot "); } Self { inner: Config { identify_properties: None, intents, large_threshold: 50, presence: None, proxy_url: None, queue: InMemoryQueue::default(), ratelimit_messages: true, resume_url: None, session: None, tls: Arc::new(Connector::new().unwrap()), token: Token::new(token.into_boxed_str()), }, } }
Create a new builder to configure and construct a shard. Refer to each method to learn their default values. # Panics Panics if loading TLS certificates fails.
new
rust
twilight-rs/twilight
twilight-gateway/src/config.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/config.rs
ISC
pub fn queue<NewQ>(self, queue: NewQ) -> ConfigBuilder<NewQ> { let Config { identify_properties, intents, large_threshold, presence, proxy_url, queue: _, ratelimit_messages, resume_url, session, tls, token, } = self.inner; ConfigBuilder { inner: Config { identify_properties, intents, large_threshold, presence, proxy_url, queue, ratelimit_messages, resume_url, session, tls, token, }, } }
Set the queue to use for queueing shard sessions. Defaults to [`InMemoryQueue`] with its default settings. Note that [`InMemoryQueue`] with a `max_concurrency` of `0` effectively turns itself into a no-op.
queue
rust
twilight-rs/twilight
twilight-gateway/src/config.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/config.rs
ISC
fn clear(&mut self) { if self.compressed.capacity() != 0 && self.last_shrank.elapsed().as_secs() > 60 { self.compressed.shrink_to_fit(); tracing::trace!( compressed.capacity = self.compressed.capacity(), "shrank capacity to the size of the last message" ); self.last_shrank = Instant::now(); } self.compressed.clear(); }
Clear the compressed buffer and periodically shrink its capacity.
clear
rust
twilight-rs/twilight
twilight-gateway/src/inflater.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/inflater.rs
ISC
pub(crate) fn inflate(&mut self, message: &[u8]) -> Result<Option<String>, CompressionError> { // Complete message. Tries to bypass the `self.compressed` buffer if the // message is incomplete. let message = if self.compressed.is_empty() { if is_incomplete_message(message) { tracing::trace!("received incomplete message"); self.compressed.extend_from_slice(message); return Ok(None); } message } else { self.compressed.extend_from_slice(message); if is_incomplete_message(&self.compressed) { tracing::trace!("received incomplete message"); return Ok(None); } &self.compressed }; let processed_pre = self.processed(); let mut processed = 0; // Decompressed message. `Vec::extend_from_slice` efficiently allocates // only what's necessary. let mut decompressed = Vec::new(); loop { let produced_pre = self.produced(); // Use Sync to ensure data is flushed to the buffer. self.decompress .decompress( &message[processed..], &mut self.buffer, FlushDecompress::Sync, ) .map_err(|source| CompressionError { kind: CompressionErrorType::Decompressing, source: Some(Box::new(source)), })?; processed = (self.processed() - processed_pre).try_into().unwrap(); let produced = (self.produced() - produced_pre).try_into().unwrap(); decompressed.extend_from_slice(&self.buffer[..produced]); // Break when message has been fully decompressed. if processed == message.len() { break; } tracing::trace!(bytes.compressed.remaining = message.len() - processed); } { #[allow(clippy::cast_precision_loss)] let total_percentage_compressed = self.processed() as f64 * 100.0 / self.produced() as f64; let total_percentage_saved = 100.0 - total_percentage_compressed; let total_kib_saved = (self.produced() - self.processed()) / 1024; tracing::trace!( bytes.compressed = message.len(), bytes.decompressed = decompressed.len(), total_percentage_saved, "{total_kib_saved} KiB saved in total", ); } self.clear(); String::from_utf8(decompressed) .map(Some) .map_err(CompressionError::from_utf8_error) }
Decompress message. Returns `None` if the message is incomplete, saving its content to be combined with the next one. # Errors Returns a [`CompressionErrorType::Decompressing`] error type if the message could not be decompressed. Returns a [`CompressionErrorType::NotUtf8`] error type if the decompressed message is not UTF-8.
inflate
rust
twilight-rs/twilight
twilight-gateway/src/inflater.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/inflater.rs
ISC
pub fn parse( event: String, wanted_event_types: EventTypeFlags, ) -> Result<Option<GatewayEvent>, ReceiveMessageError> { let Some(gateway_deserializer) = GatewayEventDeserializer::from_json(&event) else { return Err(ReceiveMessageError { kind: ReceiveMessageErrorType::Deserializing { event }, source: None, }); }; let Some(opcode) = OpCode::from(gateway_deserializer.op()) else { return Ok(None); }; let event_type = gateway_deserializer.event_type(); let Ok(event_type) = EventTypeFlags::try_from((opcode, event_type)) else { return Ok(None); }; if wanted_event_types.contains(event_type) { #[cfg(feature = "simd-json")] let gateway_deserializer = gateway_deserializer.into_owned(); #[cfg(feature = "simd-json")] let mut bytes = event.into_bytes(); #[cfg(feature = "simd-json")] let mut json_deserializer = match simd_json::Deserializer::from_slice(&mut bytes) { Ok(deserializer) => deserializer, Err(source) => { return Err(ReceiveMessageError { kind: ReceiveMessageErrorType::Deserializing { event: String::from_utf8_lossy(&bytes).into_owned(), }, source: Some(Box::new(source)), }) } }; #[cfg(not(feature = "simd-json"))] let mut json_deserializer = serde_json::Deserializer::from_str(&event); gateway_deserializer .deserialize(&mut json_deserializer) .map(Some) .map_err(|source| ReceiveMessageError { kind: ReceiveMessageErrorType::Deserializing { #[cfg(feature = "simd-json")] event: String::from_utf8_lossy(&bytes).into_owned(), #[cfg(not(feature = "simd-json"))] event, }, source: Some(Box::new(source)), }) } else { Ok(None) } }
Parse a JSON encoded gateway event into a `GatewayEvent` if `wanted_event_types` contains its type. # Errors Returns a [`ReceiveMessageErrorType::Deserializing`] error if the *known* event could not be deserialized.
parse
rust
twilight-rs/twilight
twilight-gateway/src/json.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/json.rs
ISC
pub(crate) const fn new() -> Self { Self { latency_sum: Duration::ZERO, periods: 0, received: None, recent: [Duration::MAX; Self::RECENT_LEN], sent: None, } }
Create a new instance for tracking shard latency.
new
rust
twilight-rs/twilight
twilight-gateway/src/latency.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/latency.rs
ISC
pub fn recent(&self) -> &[Duration] { // We use the sentinel value of Duration::MAX since using // `Duration::ZERO` would cause tests depending on elapsed time on fast // CPUs to flake. See issue #2114. let maybe_zero_idx = self .recent .iter() .position(|duration| *duration == Duration::MAX); &self.recent[0..maybe_zero_idx.unwrap_or(Self::RECENT_LEN)] }
Most recent latencies from newest to oldest.
recent
rust
twilight-rs/twilight
twilight-gateway/src/latency.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/latency.rs
ISC
pub(crate) fn record_sent(&mut self) { self.received = None; self.sent = Some(Instant::now()); }
Record that a heartbeat was sent, beginning a new period. The current time is stored to be used in [`record_received`]. [`record_received`]: Self::record_received
record_sent
rust
twilight-rs/twilight
twilight-gateway/src/latency.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/latency.rs
ISC
pub const fn is_close(&self) -> bool { matches!(self, Self::Close(_)) }
Whether the message is a close message.
is_close
rust
twilight-rs/twilight
twilight-gateway/src/message.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/message.rs
ISC
pub const fn is_text(&self) -> bool { matches!(self, Self::Text(_)) }
Whether the message is a text message.
is_text
rust
twilight-rs/twilight
twilight-gateway/src/message.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/message.rs
ISC
pub(crate) fn from_websocket_msg(msg: &WebsocketMessage) -> Option<Self> { if msg.is_close() { let (code, reason) = msg.as_close().unwrap(); let frame = (code != CloseCode::NO_STATUS_RECEIVED).then(|| CloseFrame { code: code.into(), reason: Cow::Owned(reason.to_string()), }); Some(Self::Close(frame)) } else if msg.is_text() { Some(Self::Text(msg.as_text().unwrap().to_owned())) } else { None } }
Convert a `tokio-websockets` websocket message into a `twilight` websocket message.
from_websocket_msg
rust
twilight-rs/twilight
twilight-gateway/src/message.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/message.rs
ISC
pub(crate) fn into_websocket_msg(self) -> WebsocketMessage { match self { Self::Close(frame) => WebsocketMessage::close( frame .as_ref() .and_then(|f| CloseCode::try_from(f.code).ok()), frame.map(|f| f.reason).as_deref().unwrap_or_default(), ), Self::Text(string) => WebsocketMessage::text(string), } }
Convert a `twilight` websocket message into a `tokio-websockets` websocket message.
into_websocket_msg
rust
twilight-rs/twilight
twilight-gateway/src/message.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/message.rs
ISC
fn next_acquired_position(&self, now: Instant) -> Option<usize> { self.queue .iter() .map(|&m| self.delay.deadline() + Duration::from_millis(m.into())) .position(|deadline| deadline > now) }
Searches for the first acquired timestamp, returning its index. If every timestamp is released, it returns `None`.
next_acquired_position
rust
twilight-rs/twilight
twilight-gateway/src/ratelimiter.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/ratelimiter.rs
ISC
fn from_close_code(close_code: Option<u16>) -> Self { match close_code.map(CloseCode::try_from) { Some(Ok(close_code)) if !close_code.can_reconnect() => Self::FatallyClosed, _ => Self::Disconnected { reconnect_attempts: 0, }, } }
Determine the connection status from the close code. Defers to [`CloseCode::can_reconnect`] to determine whether the connection can be reconnected, defaulting to [`Self::Disconnected`] if the close code is unknown.
from_close_code
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
const fn is_disconnected(self) -> bool { matches!(self, Self::Disconnected { .. }) }
Whether the shard has disconnected but may reconnect in the future.
is_disconnected
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
pub const fn is_identified(self) -> bool { matches!(self, Self::Active | Self::Resuming) }
Whether the shard is identified with an active session. `true` if the status is [`Active`] or [`Resuming`]. [`Active`]: Self::Active [`Resuming`]: Self::Resuming
is_identified
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
pub fn new(id: ShardId, token: String, intents: Intents) -> Self { Self::with_config(id, Config::new(token, intents)) }
Create a new shard with the default configuration.
new
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
pub fn with_config(shard_id: ShardId, mut config: Config<Q>) -> Self { let session = config.take_session(); let mut resume_url = config.take_resume_url(); //ensure resume_url is only used if we have a session to resume if session.is_none() { resume_url = None; } Self { config, connection_future: None, connection: None, #[cfg(feature = "zstd")] decompressor: Decompressor::new(), heartbeat_interval: None, heartbeat_interval_event: false, id: shard_id, identify_rx: None, #[allow(deprecated)] #[cfg(all( any(feature = "zlib-stock", feature = "zlib-simd"), not(feature = "zstd") ))] inflater: Inflater::new(), pending: None, latency: Latency::new(), ratelimiter: None, resume_url, session, state: ShardState::Disconnected { reconnect_attempts: 0, }, user_channel: MessageChannel::new(), } }
Create a new shard with the provided configuration.
with_config
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
pub fn close(&self, close_frame: CloseFrame<'static>) { _ = self.user_channel.close_tx.try_send(close_frame); }
Queue a websocket close frame. Invalidates the session and shows the application's bot as offline if the close frame code is `1000` or `1001`. Otherwise Discord will continue showing the bot as online until its presence times out. To read all remaining messages, continue calling [`poll_next`] until it returns [`Message::Close`]. # Example Close the shard and process remaining messages: ```no_run # use twilight_gateway::{Intents, Shard, ShardId}; # #[tokio::main] async fn main() { # let mut shard = Shard::new(ShardId::ONE, String::new(), Intents::empty()); use tokio_stream::StreamExt; use twilight_gateway::{error::ReceiveMessageErrorType, CloseFrame, Message}; shard.close(CloseFrame::NORMAL); while let Some(item) = shard.next().await { match item { Ok(Message::Close(_)) => break, Ok(Message::Text(_)) => unimplemented!(), Err(source) => unimplemented!(), } } # } ``` [`poll_next`]: Shard::poll_next
close
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
fn disconnect(&mut self, initiator: CloseInitiator) { // May not send any additional WebSocket messages. self.heartbeat_interval = None; self.ratelimiter = None; // Abort identify. self.identify_rx = None; self.state = match initiator { CloseInitiator::Gateway(close_code) => ShardState::from_close_code(close_code), _ => ShardState::Disconnected { reconnect_attempts: 0, }, }; if let CloseInitiator::Shard(frame) = initiator { // Not resuming, drop session and resume URL. // https://discord.com/developers/docs/topics/gateway#initiating-a-disconnect if matches!(frame.code, 1000 | 1001) { self.resume_url = None; self.session = None; } self.pending = Some(Pending { gateway_event: Some(Message::Close(Some(frame))), is_heartbeat: false, }); } }
Update internal state from gateway disconnect.
disconnect
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
fn parse_event<T: DeserializeOwned>( json: &str, ) -> Result<MinimalEvent<T>, ReceiveMessageError> { json::from_str::<MinimalEvent<T>>(json).map_err(|source| ReceiveMessageError { kind: ReceiveMessageErrorType::Deserializing { event: json.to_owned(), }, source: Some(Box::new(source)), }) }
Parse a JSON message into an event with minimal data for [processing]. # Errors Returns a [`ReceiveMessageErrorType::Deserializing`] error type if the gateway event isn't a recognized structure, which may be the case for new or undocumented events. [processing]: Self::process
parse_event
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
fn poll_send(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), WebsocketError>> { loop { if let Some(pending) = self.pending.as_mut() { ready!(Pin::new(self.connection.as_mut().unwrap()).poll_ready(cx))?; if let Some(message) = &pending.gateway_event { if let Some(ratelimiter) = self.ratelimiter.as_mut() { if message.is_text() && !pending.is_heartbeat { ready!(ratelimiter.poll_acquire(cx)); } } let ws_message = pending.gateway_event.take().unwrap().into_websocket_msg(); Pin::new(self.connection.as_mut().unwrap()).start_send(ws_message)?; } ready!(Pin::new(self.connection.as_mut().unwrap()).poll_flush(cx))?; if pending.is_heartbeat { self.latency.record_sent(); } self.pending = None; } if !self.state.is_disconnected() { if let Poll::Ready(frame) = self.user_channel.close_rx.poll_recv(cx) { let frame = frame.expect("shard owns channel"); tracing::debug!("sending close frame from user channel"); self.disconnect(CloseInitiator::Shard(frame)); continue; } } if self .heartbeat_interval .as_mut() .is_some_and(|heartbeater| heartbeater.poll_tick(cx).is_ready()) { // Discord never responded after the last heartbeat, connection // is failed or "zombied", see // https://discord.com/developers/docs/topics/gateway#heartbeat-interval-example-heartbeat-ack // Note that unlike documented *any* event is okay; it does not // have to be a heartbeat ACK. if self.latency.sent().is_some() && !self.heartbeat_interval_event { tracing::info!("connection is failed or \"zombied\""); return Poll::Ready(Err(WebsocketError::Io(io::ErrorKind::TimedOut.into()))); } tracing::debug!("sending heartbeat"); self.pending = Pending::text( json::to_string(&Heartbeat::new(self.session().map(Session::sequence))) .expect("serialization cannot fail"), true, ); self.heartbeat_interval_event = false; continue; } let not_ratelimited = self.ratelimiter.as_mut().map_or(true, |ratelimiter| { ratelimiter.poll_available(cx).is_ready() }); if not_ratelimited { if let Some(Poll::Ready(canceled)) = self .identify_rx .as_mut() .map(|rx| Pin::new(rx).poll(cx).map(|r| r.is_err())) { if canceled { self.identify_rx = Some(self.config.queue().enqueue(self.id.number())); continue; } tracing::debug!("sending identify"); self.pending = Pending::text( json::to_string(&Identify::new(IdentifyInfo { compress: false, intents: self.config.intents(), large_threshold: self.config.large_threshold(), presence: self.config.presence().cloned(), properties: self .config .identify_properties() .cloned() .unwrap_or_else(default_identify_properties), shard: Some(self.id), token: self.config.token().to_owned(), })) .expect("serialization cannot fail"), false, ); self.identify_rx = None; continue; } } if not_ratelimited && self.state.is_identified() { if let Poll::Ready(command) = self.user_channel.command_rx.poll_recv(cx) { let command = command.expect("shard owns channel"); tracing::debug!("sending command from user channel"); self.pending = Some(Pending { gateway_event: Some(Message::Text(command)), is_heartbeat: false, }); continue; } } return Poll::Ready(Ok(())); } }
Attempts to send due commands to the gateway. # Returns * `Poll::Pending` if sending is in progress * `Poll::Ready(Ok)` if no more scheduled commands remain * `Poll::Ready(Err)` if sending a command failed.
poll_send
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
fn default_identify_properties() -> IdentifyProperties { IdentifyProperties::new("twilight.rs", "twilight.rs", OS) }
Default identify properties to use when the user hasn't customized it in [`Config::identify_properties`]. [`Config::identify_properties`]: Config::identify_properties
default_identify_properties
rust
twilight-rs/twilight
twilight-gateway/src/shard.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway/src/shard.rs
ISC
async fn runner( mut rx: mpsc::UnboundedReceiver<Message>, Settings { max_concurrency, mut remaining, reset_after, mut total, }: Settings, ) { let (interval, reset_at) = { let now = Instant::now(); (sleep_until(now), sleep_until(now + reset_after)) }; tokio::pin!(interval, reset_at); let mut queues = iter::repeat_with(VecDeque::new) .take(max_concurrency.into()) .collect::<Box<_>>(); #[allow(clippy::ignored_unit_patterns)] loop { tokio::select! { biased; _ = &mut reset_at, if remaining != total => { remaining = total; } message = rx.recv() => { match message { Some(Message::Request { shard, tx }) => { if queues.is_empty() { _ = tx.send(()); } else { let key = shard as usize % queues.len(); queues[key].push_back((shard, tx)); } } Some(Message::Update(update)) => { let (max_concurrency, reset_after); Settings { max_concurrency, remaining, reset_after, total, } = update; if remaining != total { reset_at.as_mut().reset(Instant::now() + reset_after); } if max_concurrency as usize != queues.len() { let unbalanced = queues.into_vec().into_iter().flatten(); queues = iter::repeat_with(VecDeque::new) .take(max_concurrency.into()) .collect(); for (shard, tx) in unbalanced { let key = (shard % u32::from(max_concurrency)) as usize; queues[key].push_back((shard, tx)); } } } None => break, } } _ = &mut interval, if queues.iter().any(|queue| !queue.is_empty()) => { let now = Instant::now(); let span = tracing::info_span!("bucket", moment = ?now); interval.as_mut().reset(now + IDENTIFY_DELAY); if remaining == total { reset_at.as_mut().reset(now + LIMIT_PERIOD); } for (key, queue) in queues.iter_mut().enumerate() { if remaining == 0 { tracing::debug!( refill_delay = ?reset_at.deadline().saturating_duration_since(now), "exhausted available permits" ); (&mut reset_at).await; remaining = total; break; } while let Some((shard, tx)) = queue.pop_front() { if tx.send(()).is_err() { continue; } tracing::debug!(parent: &span, key, shard); remaining -= 1; // Reschedule behind shard for ordering correctness. yield_now().await; break; } } } } } }
[`InMemoryQueue`]'s background task runner. Buckets requests such that only one timer is necessary.
runner
rust
twilight-rs/twilight
twilight-gateway-queue/src/in_memory.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway-queue/src/in_memory.rs
ISC
pub fn new(max_concurrency: u16, remaining: u32, reset_after: Duration, total: u32) -> Self { assert!(total >= remaining); let (tx, rx) = mpsc::unbounded_channel(); tokio::spawn(runner( rx, Settings { max_concurrency, remaining, reset_after, total, }, )); Self { tx } }
Creates a new `InMemoryQueue` with custom settings. # Panics Panics if `total` < `remaining`.
new
rust
twilight-rs/twilight
twilight-gateway-queue/src/in_memory.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway-queue/src/in_memory.rs
ISC
pub async fn reset_after_started(queue: impl Queue) { advance(LIMIT_PERIOD / 2).await; let t1 = queue.enqueue(0); let t2 = queue.enqueue(0); _ = t1.await; let now = Instant::now(); _ = t2.await; assert!( (now.elapsed().as_secs_f64() - LIMIT_PERIOD.as_secs_f64()).abs() <= 1e-2, "queue misstimed remaining refill" ); }
Requires a fresh queue with `remaining` of 1.
reset_after_started
rust
twilight-rs/twilight
twilight-gateway-queue/tests/common/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-gateway-queue/tests/common/mod.rs
ISC
pub fn write_param(&mut self, key: &str, value: &impl Display) -> std::fmt::Result { if self.is_first { self.formatter.write_char('?')?; self.is_first = false; } else { self.formatter.write_char('&')?; } self.formatter.write_str(key)?; self.formatter.write_char('=')?; Display::fmt(value, self.formatter) }
Writes a query parameter to the formatter. # Errors This returns a [`std::fmt::Error`] if the formatter returns an error.
write_param
rust
twilight-rs/twilight
twilight-http/src/query_formatter.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/query_formatter.rs
ISC
pub fn write_opt_param(&mut self, key: &str, value: Option<&impl Display>) -> std::fmt::Result { if let Some(value) = value { self.write_param(key, value) } else { Ok(()) } }
Writes a query parameter to the formatter. # Errors This returns a [`std::fmt::Error`] if the formatter returns an error.
write_opt_param
rust
twilight-rs/twilight
twilight-http/src/query_formatter.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/query_formatter.rs
ISC
pub fn default_allowed_mentions(mut self, allowed_mentions: AllowedMentions) -> Self { self.default_allowed_mentions.replace(allowed_mentions); self }
Set the default allowed mentions setting to use on all messages sent through the HTTP client.
default_allowed_mentions
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub fn proxy(mut self, proxy_url: String, use_http: bool) -> Self { self.proxy.replace(proxy_url.into_boxed_str()); self.use_http = use_http; self }
Set the proxy to use for all HTTP(S) requests. **Note** that this isn't currently a traditional proxy, but is for working with something like [twilight's HTTP proxy server]. # Examples Set the proxy to `twilight_http_proxy.internal`: ``` use twilight_http::Client; # fn main() -> Result<(), Box<dyn std::error::Error>> { let client = Client::builder() .proxy("twilight_http_proxy.internal".to_owned(), true) .build(); # Ok(()) } ``` [twilight's HTTP proxy server]: https://github.com/twilight-rs/http-proxy
proxy
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub const fn timeout(mut self, duration: Duration) -> Self { self.timeout = duration; self }
Set the timeout for HTTP requests. The default is 10 seconds.
timeout
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub fn default_headers(mut self, headers: HeaderMap) -> Self { self.default_headers.replace(headers); self }
Set a group headers which are sent in every request.
default_headers
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub const fn remember_invalid_token(mut self, remember: bool) -> Self { self.remember_invalid_token = remember; self }
Whether to remember whether the client has encountered an Unauthorized response status. If the client remembers encountering an Unauthorized response, then it will not process future requests. Defaults to true.
remember_invalid_token
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub fn token(mut self, mut token: String) -> Self { let is_bot = token.starts_with("Bot "); let is_bearer = token.starts_with("Bearer "); // Make sure it is either a bot or bearer token, and assume it's a bot // token if no prefix is given if !is_bot && !is_bearer { token.insert_str(0, "Bot "); } self.token.replace(Token::new(token.into_boxed_str())); self }
Set the token to use for HTTP requests.
token
rust
twilight-rs/twilight
twilight-http/src/client/builder.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/builder.rs
ISC
pub fn create() -> Connector { #[cfg(not(feature = "hickory"))] let mut connector = HttpConnector::new(); #[cfg(feature = "hickory")] let mut connector = hyper_hickory::TokioHickoryResolver::default().into_http_connector(); connector.enforce_http(false); #[cfg(any( feature = "rustls-native-roots", feature = "rustls-platform-verifier", feature = "rustls-webpki-roots" ))] let connector = { #[cfg(not(any(feature = "rustls-ring", feature = "rustls-aws_lc_rs")))] let crypto_provider = rustls::crypto::CryptoProvider::get_default() .expect("No default crypto provider installed or configured via crate features") .clone(); #[cfg(feature = "rustls-aws_lc_rs")] let crypto_provider = rustls::crypto::aws_lc_rs::default_provider(); #[cfg(all(feature = "rustls-ring", not(feature = "rustls-aws_lc_rs")))] let crypto_provider = rustls::crypto::ring::default_provider(); #[cfg(all( feature = "rustls-native-roots", not(feature = "rustls-platform-verifier") ))] let connector = hyper_rustls::HttpsConnectorBuilder::new() .with_provider_and_native_roots(crypto_provider) .expect("no native roots found") .https_or_http() .enable_http1() .enable_http2() .wrap_connector(connector); #[cfg(feature = "rustls-platform-verifier")] let connector = hyper_rustls::HttpsConnectorBuilder::new() .with_provider_and_platform_verifier(crypto_provider) .expect("no usable cipher suites in crypto provider") .https_or_http() .enable_http1() .enable_http2() .wrap_connector(connector); #[cfg(all( feature = "rustls-webpki-roots", not(any(feature = "rustls-native-roots", feature = "rustls-platform-verifier")) ))] let connector = hyper_rustls::HttpsConnectorBuilder::new() .with_provider_and_webpki_roots(crypto_provider) .expect("no usable cipher suites in crypto provider") .https_or_http() .enable_http1() .enable_http2() .wrap_connector(connector); connector }; #[cfg(all( feature = "native-tls", not(feature = "rustls-native-roots"), not(feature = "rustls-platform-verifier"), not(feature = "rustls-webpki-roots") ))] let connector = hyper_tls::HttpsConnector::new_with_connector(connector); connector }
Create a connector with the specified features.
create
rust
twilight-rs/twilight
twilight-http/src/client/connector.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/connector.rs
ISC
pub(super) const fn new(client: &'a Client, application_id: Id<ApplicationMarker>) -> Self { Self { application_id, client, } }
Create a new interface for using interactions.
new
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn global_command(&self, command_id: Id<CommandMarker>) -> GetGlobalCommand<'_> { GetGlobalCommand::new(self.client, self.application_id, command_id) }
Fetch a global command for your application.
global_command
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn global_commands(&self) -> GetGlobalCommands<'_> { GetGlobalCommands::new(self.client, self.application_id) }
Fetch all global commands for your application.
global_commands
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn update_global_command( &self, command_id: Id<CommandMarker>, ) -> UpdateGlobalCommand<'_> { UpdateGlobalCommand::new(self.client, self.application_id, command_id) }
Edit a global command, by ID. You must specify a name and description. See [Discord Docs/Edit Global Application Command]. [Discord Docs/Edit Global Application Command]: https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command
update_global_command
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn delete_guild_command( &self, guild_id: Id<GuildMarker>, command_id: Id<CommandMarker>, ) -> DeleteGuildCommand<'_> { DeleteGuildCommand::new(self.client, self.application_id, guild_id, command_id) }
Delete a command in a guild, by ID.
delete_guild_command
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn guild_command( &self, guild_id: Id<GuildMarker>, command_id: Id<CommandMarker>, ) -> GetGuildCommand<'_> { GetGuildCommand::new(self.client, self.application_id, guild_id, command_id) }
Fetch a guild command for your application.
guild_command
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn guild_commands(&self, guild_id: Id<GuildMarker>) -> GetGuildCommands<'_> { GetGuildCommands::new(self.client, self.application_id, guild_id) }
Fetch all commands for a guild, by ID.
guild_commands
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn update_guild_command( &self, guild_id: Id<GuildMarker>, command_id: Id<CommandMarker>, ) -> UpdateGuildCommand<'_> { UpdateGuildCommand::new(self.client, self.application_id, guild_id, command_id) }
Edit a command in a guild, by ID. You must specify a name and description. See [Discord Docs/Edit Guild Application Command]. [Discord Docs/Edit Guild Application Command]: https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command
update_guild_command
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn command_permissions( &self, guild_id: Id<GuildMarker>, command_id: Id<CommandMarker>, ) -> GetCommandPermissions<'_> { GetCommandPermissions::new(self.client, self.application_id, guild_id, command_id) }
Fetch command permissions for a command from the current application in a guild.
command_permissions
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn guild_command_permissions( &self, guild_id: Id<GuildMarker>, ) -> GetGuildCommandPermissions<'_> { GetGuildCommandPermissions::new(self.client, self.application_id, guild_id) }
Fetch command permissions for all commands from the current application in a guild.
guild_command_permissions
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub fn update_command_permissions( &'a self, guild_id: Id<GuildMarker>, command_id: Id<CommandMarker>, permissions: &'a [CommandPermission], ) -> UpdateCommandPermissions<'a> { UpdateCommandPermissions::new( self.client, self.application_id, guild_id, command_id, permissions, ) }
Update command permissions for a single command in a guild. This overwrites the command permissions so the full set of permissions have to be sent every time. This request requires that the client was configured with an OAuth2 Bearer token. # Errors Returns an error of type [`PermissionsCountInvalid`] if the permissions are invalid. [`PermissionsCountInvalid`]: twilight_validate::command::CommandValidationErrorType::PermissionsCountInvalid
update_command_permissions
rust
twilight-rs/twilight
twilight-http/src/client/interaction.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/interaction.rs
ISC
pub const fn interaction( &self, application_id: Id<ApplicationMarker>, ) -> InteractionClient<'_> { InteractionClient::new(self, application_id) }
Create an interface for using interactions. An application ID is required to be passed in to use interactions. The ID may be retrieved via [`current_user_application`] and cached for use with this method. # Examples Retrieve the application ID and then use an interaction request: ```no_run # #[tokio::main] # async fn main() -> Result<(), Box<dyn std::error::Error>> { use std::env; use twilight_http::Client; let client = Client::new(env::var("DISCORD_TOKEN")?); // Cache the application ID for repeated use later in the process. let application_id = { let response = client.current_user_application().await?; response.model().await?.id }; // Later in the process... let commands = client .interaction(application_id) .global_commands() .await? .models() .await?; println!("there are {} global commands", commands.len()); # Ok(()) } ``` [`current_user_application`]: Self::current_user_application
interaction
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn auto_moderation_rule( &self, guild_id: Id<GuildMarker>, auto_moderation_rule_id: Id<AutoModerationRuleMarker>, ) -> GetAutoModerationRule<'_> { GetAutoModerationRule::new(self, guild_id, auto_moderation_rule_id) }
Get an auto moderation rule in a guild. Requires the [`MANAGE_GUILD`] permission. [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
auto_moderation_rule
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn auto_moderation_rules( &self, guild_id: Id<GuildMarker>, ) -> GetGuildAutoModerationRules<'_> { GetGuildAutoModerationRules::new(self, guild_id) }
Get the auto moderation rules in a guild. Requires the [`MANAGE_GUILD`] permission. [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
auto_moderation_rules
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn create_auto_moderation_rule<'a>( &'a self, guild_id: Id<GuildMarker>, name: &'a str, event_type: AutoModerationEventType, ) -> CreateAutoModerationRule<'a> { CreateAutoModerationRule::new(self, guild_id, name, event_type) }
Create an auto moderation rule within a guild. Requires the [`MANAGE_GUILD`] permission. # Examples Create a rule that deletes messages that contain the word "darn": ```no_run # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { use twilight_http::Client; use twilight_model::{guild::auto_moderation::AutoModerationEventType, id::Id}; let client = Client::new("my token".to_owned()); let guild_id = Id::new(1); client .create_auto_moderation_rule(guild_id, "no darns", AutoModerationEventType::MessageSend) .action_block_message() .enabled(true) .with_keyword(&["darn"], &["d(?:4|a)rn"], &["darn it"]) .await?; # Ok(()) } ``` [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
create_auto_moderation_rule
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn delete_auto_moderation_rule( &self, guild_id: Id<GuildMarker>, auto_moderation_rule_id: Id<AutoModerationRuleMarker>, ) -> DeleteAutoModerationRule<'_> { DeleteAutoModerationRule::new(self, guild_id, auto_moderation_rule_id) }
Delete an auto moderation rule in a guild. Requires the [`MANAGE_GUILD`] permission. [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
delete_auto_moderation_rule
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn update_auto_moderation_rule( &self, guild_id: Id<GuildMarker>, auto_moderation_rule_id: Id<AutoModerationRuleMarker>, ) -> UpdateAutoModerationRule<'_> { UpdateAutoModerationRule::new(self, guild_id, auto_moderation_rule_id) }
Update an auto moderation rule in a guild. Requires the [`MANAGE_GUILD`] permission. [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
update_auto_moderation_rule
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn audit_log(&self, guild_id: Id<GuildMarker>) -> GetAuditLog<'_> { GetAuditLog::new(self, guild_id) }
Get the audit log for a guild. # Examples ```no_run # use twilight_http::Client; use twilight_model::id::Id; # #[tokio::main] # async fn main() -> Result<(), Box<dyn std::error::Error>> { # let client = Client::new("token".to_owned()); let guild_id = Id::new(101); let audit_log = client.audit_log(guild_id).await?; # Ok(()) } ```
audit_log
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn bans(&self, guild_id: Id<GuildMarker>) -> GetBans<'_> { GetBans::new(self, guild_id) }
Retrieve the bans for a guild. # Examples Retrieve the bans for guild `1`: ```no_run # use twilight_http::Client; use twilight_model::id::Id; # # #[tokio::main] # async fn main() -> Result<(), Box<dyn std::error::Error>> { # let client = Client::new("my token".to_owned()); # let guild_id = Id::new(1); let bans = client.bans(guild_id).await?; # Ok(()) } ```
bans
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn ban(&self, guild_id: Id<GuildMarker>, user_id: Id<UserMarker>) -> GetBan<'_> { GetBan::new(self, guild_id, user_id) }
Get information about a ban of a guild. Includes the user banned and the reason.
ban
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn create_ban( &self, guild_id: Id<GuildMarker>, user_id: Id<UserMarker>, ) -> CreateBan<'_> { CreateBan::new(self, guild_id, user_id) }
Bans a user from a guild, optionally with the number of seconds' worth of messages to delete and the reason. # Examples Ban user `200` from guild `100`, deleting `86_400` second's (this is equivalent to `1` day) worth of messages, for the reason `"memes"`: ```no_run # use twilight_http::{request::AuditLogReason, Client}; use twilight_model::id::Id; # # #[tokio::main] # async fn main() -> Result<(), Box<dyn std::error::Error>> { # let client = Client::new("my token".to_owned()); # let guild_id = Id::new(100); let user_id = Id::new(200); client .create_ban(guild_id, user_id) .delete_message_seconds(86_400) .reason("memes") .await?; # Ok(()) } ```
create_ban
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC
pub const fn delete_ban( &self, guild_id: Id<GuildMarker>, user_id: Id<UserMarker>, ) -> DeleteBan<'_> { DeleteBan::new(self, guild_id, user_id) }
Remove a ban from a user in a guild. # Examples Unban user `200` from guild `100`: ```no_run # use twilight_http::Client; use twilight_model::id::Id; # # #[tokio::main] # async fn main() -> Result<(), Box<dyn std::error::Error>> { # let client = Client::new("my token".to_owned()); # let guild_id = Id::new(100); let user_id = Id::new(200); client.delete_ban(guild_id, user_id).await?; # Ok(()) } ```
delete_ban
rust
twilight-rs/twilight
twilight-http/src/client/mod.rs
https://github.com/twilight-rs/twilight/blob/master/twilight-http/src/client/mod.rs
ISC