[][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<FixedOffset>>,
    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<FixedOffset>>

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.

Methods

impl GuildChannel[src]

pub 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 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));

pub 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 PermissionOverwrite::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)
    .ok_or(ModelError::ItemMissing)?;

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

Creating a permission overwrite for a role by specifying the PermissionOverwrite::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 cache = cache.read();
let channel = cache
    .guild_channel(channel_id)
    .ok_or(ModelError::ItemMissing)?;

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

pub 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 fn delete_messages<T: AsRef<MessageId>, It: IntoIterator<Item = T>>(
    &self,
    http: impl AsRef<Http>,
    message_ids: It
) -> Result<()>
[src]

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

Refer to Channel::delete_messages for more information.

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 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 fn delete_reaction<M, R>(
    &self,
    http: impl AsRef<Http>,
    message_id: M,
    user_id: Option<UserId>,
    reaction_type: R
) -> Result<()> where
    M: Into<MessageId>,
    R: Into<ReactionType>, 
[src]

Deletes the given Reaction from the channel.

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

pub 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));

pub fn edit_message<F, M>(
    &self,
    http: impl AsRef<Http>,
    message_id: M,
    f: F
) -> Result<Message> where
    F: FnOnce(&mut EditMessage) -> &mut EditMessage,
    M: Into<MessageId>, 
[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 fn guild(
    &self,
    cache: impl AsRef<CacheRwLock>
) -> Option<Arc<RwLock<Guild>>>
[src]

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

Note: Right now this performs a clone of the guild. This will be optimized in the future.

pub 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 fn message<M: Into<MessageId>>(
    &self,
    http: impl AsRef<Http>,
    message_id: M
) -> Result<Message>
[src]

Gets a message from the channel.

Requires the Read Message History permission.

pub 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 fn permissions_for<U: Into<UserId>>(
    &self,
    cache: impl AsRef<CacheRwLock>,
    user_id: U
) -> Result<Permissions>
[src]

Deprecated since 0.6.4:

Please use permissions_for_user instead.

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;

impl EventHandler for Handler {
    fn message(&self, context: Context, msg: Message) {
        let channel = match context.cache.read().guild_channel(msg.channel_id) {
            Some(channel) => channel,
            None => return,
        };

        let permissions = channel.read().permissions_for(&context.cache, &msg.author).unwrap();

        println!("The user's permissions: {:?}", permissions);
    }
}
let mut client = Client::new("token", Handler).unwrap();

client.start().unwrap();

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 std::fs::File;

struct Handler;

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

        let current_user_id = context.cache.read().user.id;
        let permissions =
            channel.read().permissions_for(&context.cache, current_user_id).unwrap();

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

            let file = match File::open("./cat.png") {
                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
        });
    }
}

let mut client = Client::new("token", Handler).unwrap();

client.start().unwrap();

Errors

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

pub fn permissions_for_user<U: Into<UserId>>(
    &self,
    cache: impl AsRef<CacheRwLock>,
    user_id: U
) -> 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 fn permissions_for_role<R: Into<RoleId>>(
    &self,
    cache: impl AsRef<CacheRwLock>,
    role_id: R
) -> 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;

impl EventHandler for Handler {
    fn message(&self, context: Context, msg: Message) {
        let channel = match context.cache.read().guild_channel(msg.channel_id) {
            Some(channel) => channel,
            None => return,
        };

        let permissions = channel.read().permissions_for(&context.cache, &msg.author).unwrap();

        println!("The user's permissions: {:?}", permissions);
    }
}
let mut client = Client::new("token", Handler).unwrap();

client.start().unwrap();

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 std::fs::File;

struct Handler;

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

        let current_user_id = context.cache.read().user.id;
        let permissions =
            channel.read().permissions_for(&context.cache, current_user_id).unwrap();

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

            let file = match File::open("./cat.png") {
                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
        });
    }
}

let mut client = Client::new("token", Handler).unwrap();

client.start().unwrap();

Errors

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

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

Pins a Message to the channel.

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

Gets all channel's pins.

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

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

Refer to Channel::reaction_users for more information.

Note: Requires the Read Message History permission.

pub 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 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 ClientError::MessageTooLong will be returned, containing the number of unicode code points over the limit.

pub 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 unpin<M: Into<MessageId>>(
    &self,
    http: impl AsRef<Http>,
    message_id: M
) -> Result<()>
[src]

Unpins a Message in the channel given by its Id.

Requires the Manage Messages permission.

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

Retrieves the channel's webhooks.

Note: Requires the Manage Webhooks permission.

pub fn members(&self, cache: impl AsRef<CacheRwLock>) -> 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.

Trait Implementations

impl Clone for GuildChannel[src]

impl Debug for GuildChannel[src]

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

impl Display for GuildChannel[src]

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

Formats the channel, creating a mention of it.

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

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

Gets the Id of a guild channel.

impl From<GuildChannel> for ChannelId[src]

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> CloneAny for T where
    T: Clone + Any
[src]

impl<T> DebugAny for T where
    T: Any + Debug
[src]

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

impl<T> From<T> 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<T> UnsafeAny for T where
    T: Any

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