[][src]Struct serenity::model::channel::GuildChannel

pub struct GuildChannel {
    pub id: ChannelId,
    pub bitrate: Option<u64>,
    pub category_id: Option<ChannelId>,
    pub guild_id: GuildId,
    pub kind: ChannelType,
    pub last_message_id: Option<MessageId>,
    pub last_pin_timestamp: Option<DateTime<Utc>>,
    pub name: String,
    pub permission_overwrites: Vec<PermissionOverwrite>,
    pub position: i64,
    pub topic: Option<String>,
    pub user_limit: Option<u64>,
    pub nsfw: bool,
    pub slow_mode_rate: Option<u64>,
    // some fields omitted
}

Represents a guild's text, news, or voice channel. Some methods are available only for voice channels and some are only available for text channels. News channels are a subset of text channels and lack slow mode hence slow_mode_rate will be None.

Fields

id: ChannelId

The unique Id of the channel.

The default channel Id shares the Id of the guild and the default role.

bitrate: Option<u64>

The bitrate of the channel.

Note: This is only available for voice channels.

category_id: Option<ChannelId>

Whether this guild channel belongs in a category.

guild_id: GuildId

The Id of the guild the channel is located in.

If this matches with the id, then this is the default text channel.

The original voice channel has an Id equal to the guild's Id, incremented by one.

kind: ChannelType

The type of the channel.

last_message_id: Option<MessageId>

The Id of the last message sent in the channel.

Note: This is only available for text channels.

last_pin_timestamp: Option<DateTime<Utc>>

The timestamp of the time a pin was most recently made.

Note: This is only available for text channels.

name: String

The name of the channel.

permission_overwrites: Vec<PermissionOverwrite>

Permission overwrites for Members and for Roles.

position: i64

The position of the channel.

The default text channel will almost always have a position of -1 or 0.

topic: Option<String>

The topic of the channel.

Note: This is only available for text channels.

user_limit: Option<u64>

The maximum number of members allowed in the channel.

Note: This is only available for voice channels.

nsfw: bool

Used to tell if the channel is not safe for work. Note however, it's recommended to use is_nsfw as it's gonna be more accurate.

slow_mode_rate: Option<u64>

A rate limit that applies per user and excludes bots.

Note: This is only available for text channels excluding news channels.

Implementations

impl GuildChannel[src]

pub async fn broadcast_typing<'_>(
    &'_ self,
    http: impl AsRef<Http>
) -> Result<()>
[src]

Broadcasts to the channel that the current user is typing.

For bots, this is a good indicator for long-running commands.

Note: Requires the Send Messages permission.

Errors

Returns a ModelError::InvalidPermissions if the current user does not have the required permissions.

pub async fn create_invite<F, '_>(
    &'_ self,
    cache_http: impl CacheHttp,
    f: F
) -> Result<RichInvite> where
    F: FnOnce(&mut CreateInvite) -> &mut CreateInvite
[src]

Creates an invite leading to the given channel.

Examples

Create an invite that can only be used 5 times:

This example is not tested
let invite = channel.create_invite(&context, |i| i.max_uses(5)).await;

pub async fn create_permission<'_, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    target: &'_ PermissionOverwrite
) -> Result<()>
[src]

Creates a permission overwrite for either a single Member or Role within a Channel.

Refer to the documentation for PermissionOverwrites for more information.

Requires the Manage Channels permission.

Examples

Creating a permission overwrite for a member by specifying the PermissionOverwriteType::Member variant, allowing it the Send Messages permission, but denying the Send TTS Messages and Attach Files permissions:

use serenity::model::channel::{
    PermissionOverwrite,
    PermissionOverwriteType,
};
use serenity::model::{ModelError, Permissions};
let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
let overwrite = PermissionOverwrite {
    allow: allow,
    deny: deny,
    kind: PermissionOverwriteType::Member(user_id),
};
// assuming the cache has been unlocked
let channel = cache
    .guild_channel(channel_id)
    .await
    .ok_or(ModelError::ItemMissing)?;

channel.create_permission(&http, &overwrite).await?;

Creating a permission overwrite for a role by specifying the PermissionOverwriteType::Role variant, allowing it the Manage Webhooks permission, but denying the Send TTS Messages and Attach Files permissions:

use serenity::model::channel::{
    PermissionOverwrite,
    PermissionOverwriteType,
};
use serenity::model::{ModelError, Permissions, channel::Channel};

let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
let overwrite = PermissionOverwrite {
    allow: allow,
    deny: deny,
    kind: PermissionOverwriteType::Member(user_id),
};

let channel = cache
    .guild_channel(channel_id)
    .await
    .ok_or(ModelError::ItemMissing)?;

channel.create_permission(&http, &overwrite).await?;

pub async fn delete<'_>(&'_ self, cache_http: impl CacheHttp) -> Result<Channel>[src]

Deletes this channel, returning the channel on a successful deletion.

Note: If the cache-feature is enabled permissions will be checked and upon owning the required permissions the HTTP-request will be issued.

pub async fn delete_messages<T, It, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_ids: It
) -> Result<()> where
    T: AsRef<MessageId>,
    It: IntoIterator<Item = T>, 
[src]

Deletes all messages by Ids from the given vector in the channel.

The minimum amount of messages is 2 and the maximum amount is 100.

Requires the Manage Messages permission.

Note: Messages that are older than 2 weeks can't be deleted using this method.

Errors

Returns ModelError::BulkDeleteAmount if an attempt was made to delete either 0 or more than 100 messages.

pub async fn delete_permission<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    permission_type: PermissionOverwriteType
) -> Result<()>
[src]

Deletes all permission overrides in the channel from a member or role.

Note: Requires the Manage Channel permission.

pub async fn delete_reaction<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>,
    user_id: Option<UserId>,
    reaction_type: impl Into<ReactionType>
) -> Result<()>
[src]

Deletes the given Reaction from the channel.

Note: Requires the Manage Messages permission, if the current user did not perform the reaction.

pub async fn edit<F, '_>(
    &'_ mut self,
    cache_http: impl CacheHttp,
    f: F
) -> Result<()> where
    F: FnOnce(&mut EditChannel) -> &mut EditChannel
[src]

Modifies a channel's settings, such as its position or name.

Refer to EditChannels documentation for a full list of methods.

Examples

Change a voice channels name and bitrate:

This example is not tested
channel.edit(&context, |c| c.name("test").bitrate(86400)).await;

pub async fn edit_message<F, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>,
    f: F
) -> Result<Message> where
    F: FnOnce(&mut EditMessage) -> &mut EditMessage
[src]

Edits a Message in the channel given its Id.

Message editing preserves all unchanged message data.

Refer to the documentation for EditMessage for more information regarding message restrictions and requirements.

Note: Requires that the current user be the author of the message.

Errors

Returns a ModelError::MessageTooLong if the content of the message is over the the limit, containing the number of unicode code points over the limit.

pub async fn guild<'_>(&'_ self, cache: impl AsRef<Cache>) -> Option<Guild>[src]

Attempts to find this channel's guild in the Cache.

pub async fn invites<'_>(
    &'_ self,
    http: impl AsRef<Http>
) -> Result<Vec<RichInvite>>
[src]

Gets all of the channel's invites.

Requires the [Manage Channels] permission. [Manage Channels]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_CHANNELS

pub fn is_nsfw(&self) -> bool[src]

Determines if the channel is NSFW.

Only text channels are taken into consideration as being NSFW. voice channels are never NSFW.

pub async fn message<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>
) -> Result<Message>
[src]

Gets a message from the channel.

Requires the Read Message History permission.

pub async fn messages<F, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    builder: F
) -> Result<Vec<Message>> where
    F: FnOnce(&mut GetMessages) -> &mut GetMessages
[src]

Gets messages from the channel.

Refer to the GetMessages-builder for more information on how to use builder.

Requires the Read Message History permission.

pub fn name(&self) -> &str[src]

Returns the name of the guild channel.

pub async fn permissions_for_user<'_>(
    &'_ self,
    cache: impl AsRef<Cache>,
    user_id: impl Into<UserId>
) -> Result<Permissions>
[src]

Calculates the permissions of a member.

The Id of the argument must be a Member of the Guild that the channel is in.

Examples

Calculate the permissions of a User who posted a Message in a channel:

use serenity::prelude::*;
use serenity::model::prelude::*;
struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn message(&self, context: Context, msg: Message) {
        let channel = match context.cache.guild_channel(msg.channel_id).await {
            Some(channel) => channel,
            None => return,
        };

        if let Ok(permissions) = channel.permissions_for_user(&context.cache, &msg.author).await {
            println!("The user's permissions: {:?}", permissions);
        }
    }
}

let mut client =Client::builder("token").event_handler(Handler).await?;

client.start().await?;

Check if the current user has the Attach Files and Send Messages permissions (note: serenity will automatically check this for; this is for demonstrative purposes):

use serenity::prelude::*;
use serenity::model::prelude::*;
use serenity::model::channel::Channel;
use tokio::fs::File;

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn message(&self, context: Context, mut msg: Message) {
        let channel = match context.cache.guild_channel(msg.channel_id).await {
            Some(channel) => channel,
            None => return,
        };

        let current_user_id = context.cache.current_user().await.id;
        if let Ok(permissions) = channel.permissions_for_user(&context.cache, current_user_id).await {

            if !permissions.contains(Permissions::ATTACH_FILES | Permissions::SEND_MESSAGES) {
                return;
            }

            let file = match File::open("./cat.png").await {
                Ok(file) => file,
                Err(why) => {
                    println!("Err opening file: {:?}", why);

                    return;
                },
            };

            let _ = msg.channel_id.send_files(&context.http, vec![(&file, "cat.png")], |mut m| {
                m.content("here's a cat");
                m
            })
            .await;
        }
    }
}

let mut client =Client::builder("token").event_handler(Handler).await?;

client.start().await?;

Errors

Returns a ModelError::GuildNotFound if the channel's guild could not be found in the Cache.

pub async fn permissions_for_role<'_>(
    &'_ self,
    cache: impl AsRef<Cache>,
    role_id: impl Into<RoleId>
) -> Result<Permissions>
[src]

Calculates the permissions of a role.

The Id of the argument must be a Role of the Guild that the channel is in.

Errors

Returns a ModelError::GuildNotFound if the channel's guild could not be found in the Cache.

Returns a ModelError::RoleNotFound if the given role could not be found in the Cache.

pub async fn pin<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>
) -> Result<()>
[src]

Pins a Message to the channel.

pub async fn pins<'_>(&'_ self, http: impl AsRef<Http>) -> Result<Vec<Message>>[src]

Gets all channel's pins.

pub async fn reaction_users<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>,
    reaction_type: impl Into<ReactionType>,
    limit: Option<u8>,
    after: impl Into<Option<UserId>>
) -> Result<Vec<User>>
[src]

Gets the list of Users who have reacted to a Message with a certain Emoji.

The default limit is 50 - specify otherwise to receive a different maximum number of users. The maximum that may be retrieve at a time is 100, if a greater number is provided then it is automatically reduced.

The optional after attribute is to retrieve the users after a certain user. This is useful for pagination.

Note: Requires the Read Message History permission.

pub async fn say<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    content: impl Display
) -> Result<Message>
[src]

Sends a message with just the given message content in the channel.

Errors

Returns a ModelError::MessageTooLong if the content of the message is over the above limit, containing the number of unicode code points over the limit.

pub async fn send_files<'a, F, T, It, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    files: It,
    f: F
) -> Result<Message> where
    F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
    T: Into<AttachmentType<'a>>,
    It: IntoIterator<Item = T>, 
[src]

Sends (a) file(s) along with optional message contents.

Refer to ChannelId::send_files for examples and more information.

The Attach Files and Send Messages permissions are required.

Note: Message contents must be under 2000 unicode code points.

Errors

If the content of the message is over the above limit, then a ModelError::MessageTooLong will be returned, containing the number of unicode code points over the limit.

pub async fn send_message<'a, F, '_>(
    &'_ self,
    cache_http: impl CacheHttp,
    f: F
) -> Result<Message> where
    F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>, 
[src]

Sends a message to the channel with the given content.

Note: This will only work when a Message is received.

Note: Requires the Send Messages permission.

Errors

Returns a ModelError::MessageTooLong if the content of the message is over the above limit, containing the number of unicode code points over the limit.

Returns a ModelError::InvalidPermissions if the current user does not have the required permissions.

pub fn start_typing(self, http: &Arc<Http>) -> Result<Typing>[src]

Starts typing in the channel for an indefinite period of time.

Returns Typing that is used to trigger the typing. Typing::stop must be called on the returned struct to stop typing. Note that on some clients, typing may persist for a few seconds after stop is called. Typing is also stopped when the struct is dropped.

If a message is sent while typing is triggered, the user will stop typing for a brief period of time and then resume again until either stop is called or the struct is dropped.

This should rarely be used for bots, although it is a good indicator that a long-running command is still being processed.

Examples

// Initiate typing (assuming http is `Arc<Http>` and `channel` is bound)
let typing = channel.start_typing(&http)?;

// Run some long-running process
long_process();

// Stop typing
typing.stop();

pub async fn unpin<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    message_id: impl Into<MessageId>
) -> Result<()>
[src]

Unpins a Message in the channel given by its Id.

Requires the Manage Messages permission.

pub async fn webhooks<'_>(
    &'_ self,
    http: impl AsRef<Http>
) -> Result<Vec<Webhook>>
[src]

Retrieves the channel's webhooks.

Note: Requires the Manage Webhooks permission.

pub async fn members<'_>(
    &'_ self,
    cache: impl AsRef<Cache>
) -> Result<Vec<Member>>
[src]

Retrieves Members from the current channel.

ChannelType::Voice returns Members using the channel. ChannelType::Text and ChannelType::News return Members that can read the channel.

Other ChannelTypes lack the concept of Members and will return: ModelError::InvalidChannelType.

pub fn await_reply<'a>(
    &self,
    shard_messenger: &'a impl AsRef<ShardMessenger>
) -> CollectReply<'a>

Notable traits for CollectReply<'a>

impl<'a> Future for CollectReply<'a> type Output = Option<Arc<Message>>;
[src]

Returns a future that will await one message by this guild.

pub fn await_replies<'a>(
    &self,
    shard_messenger: &'a impl AsRef<ShardMessenger>
) -> MessageCollectorBuilder<'a>

Notable traits for MessageCollectorBuilder<'a>

impl<'a> Future for MessageCollectorBuilder<'a> type Output = MessageCollector;
[src]

Returns a stream builder which can be awaited to obtain a stream of messages sent by this guild.

pub fn await_reaction<'a>(
    &self,
    shard_messenger: &'a impl AsRef<ShardMessenger>
) -> CollectReaction<'a>

Notable traits for CollectReaction<'a>

impl<'a> Future for CollectReaction<'a> type Output = Option<Arc<ReactionAction>>;
[src]

Await a single reaction by this guild.

pub fn await_reactions<'a>(
    &self,
    shard_messenger: &'a impl AsRef<ShardMessenger>
) -> ReactionCollectorBuilder<'a>
[src]

Returns a stream builder which can be awaited to obtain a stream of reactions sent by this guild.

pub async fn create_webhook<'_>(
    &'_ self,
    http: impl AsRef<Http>,
    name: impl Display
) -> Result<Webhook>
[src]

Sends a message with just the given message content in the channel.

Errors

Returns a ModelError::NameTooShort if the name of the webhook is under the limit of 2 characters. Returns a ModelError::NameTooLong if the name of the webhook is over the limit of 100 characters. Returns a ModelError::InvalidChannelType if the channel type is not text.

pub async fn create_webhook_with_avatar<'a, '_>(
    &'_ self,
    http: impl AsRef<Http>,
    name: impl Display,
    avatar: impl Into<AttachmentType<'a>>
) -> Result<Webhook>
[src]

Avatar must be a 128x128 image.

Trait Implementations

impl Clone for GuildChannel[src]

impl Debug for GuildChannel[src]

impl<'de> Deserialize<'de> for GuildChannel[src]

impl Display for GuildChannel[src]

pub fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult[src]

Formats the channel, creating a mention of it.

impl<'a> From<&'a GuildChannel> for ChannelId[src]

pub fn from(public_channel: &GuildChannel) -> ChannelId[src]

Gets the Id of a guild channel.

impl From<GuildChannel> for ChannelId[src]

pub fn from(public_channel: GuildChannel) -> ChannelId[src]

Gets the Id of a guild channel.

impl Mentionable for GuildChannel[src]

impl Serialize for GuildChannel[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> DeserializeOwned for T where
    T: for<'de> Deserialize<'de>, 
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>, 

impl<T> WithSubscriber for T[src]