Struct serenity::model::user::User[][src]

#[non_exhaustive]
pub struct User { pub id: UserId, pub avatar: Option<String>, pub bot: bool, pub discriminator: u16, pub name: String, pub public_flags: Option<UserPublicFlags>, }
Expand description

Information about a user.

Fields (Non-exhaustive)

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct {{ .. }} syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
id: UserId
Expand description

The unique Id of the user. Can be used to calculate the account’s creation date.

avatar: Option<String>
Expand description

Optional avatar hash.

bot: bool
Expand description

Indicator of whether the user is a bot.

discriminator: u16
Expand description

The account’s discriminator to differentiate the user from others with the same Self::name. The name+discriminator pair is always unique.

name: String
Expand description

The account’s username. Changing username will trigger a discriminator change if the username+discriminator pair becomes non-unique.

public_flags: Option<UserPublicFlags>
Expand description

the public flags on a user’s account

Implementations

impl User[src]

pub fn avatar_url(&self) -> Option<String>[src]

Returns the formatted URL of the user’s icon, if one exists.

This will produce a WEBP image URL, or GIF if the user has a GIF avatar.

pub async fn create_dm_channel(
    &self,
    cache_http: impl CacheHttp
) -> Result<PrivateChannel>
[src]

Creates a direct message channel between the current user and the user. This can also retrieve the channel if one already exists.

Errors

See UserId::create_dm_channel for what errors may be returned.

pub fn created_at(&self) -> DateTime<Utc>[src]

Retrieves the time that this user was created at.

pub fn default_avatar_url(&self) -> String[src]

Returns the formatted URL to the user’s default avatar URL.

This will produce a PNG URL.

pub async fn direct_message<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 a user through a direct message channel. This is a channel that can only be accessed by you and the recipient.

Examples

When a user sends a message with a content of "~help", DM the author a help message, and then react with '👌' to verify message sending:

use serenity::model::Permissions;

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content == "~help" {
            let url = match ctx.cache.current_user().await.invite_url(&ctx, Permissions::empty()).await {
                Ok(v) => v,
                Err(why) => {
                    println!("Error creating invite url: {:?}", why);

                    return;
                },
            };

            let help = format!(
                "Helpful info here. Invite me with this link: <{}>",
                url,
            );

            let dm = msg.author.direct_message(&ctx, |m| {
                m.content(&help)
            })
            .await;

            match dm {
                Ok(_) => {
                    let _ = msg.react(&ctx, '👌').await;
                },
                Err(why) => {
                    println!("Err sending help: {:?}", why);

                    let _ = msg.reply(&ctx, "There was an error DMing you help.").await;
                },
            };
        }
    }
}

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

Errors

Returns a ModelError::MessagingBot if the user being direct messaged is a bot user.

May also return an Error::Http if the message was illformed, or if the user cannot be sent a direct message.

Error::Json can also be returned if there is an error deserializing the API response.

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

This is an alias of Self::direct_message.

pub fn face(&self) -> String[src]

Retrieves the URL to the user’s avatar, falling back to the default avatar if needed.

This will call Self::avatar_url first, and if that returns None, it then falls back to Self::default_avatar_url.

pub async fn has_role(
    &self,
    cache_http: impl CacheHttp,
    guild: impl Into<GuildContainer>,
    role: impl Into<RoleId>
) -> Result<bool>
[src]

Check if a user has a Role. This will retrieve the Guild from the Cache if it is available, and then check if that guild has the given Role.

Three forms of data may be passed in to the guild parameter: either a PartialGuild, a GuildId, or a u64.

Examples

Check if a guild has a Role by Id:

// Assumes a 'guild_id' and `role_id` have already been bound
let _ = message.author.has_role(guild_id, role_id);

Errors

Returns an Error::Http if the given Guild is unavailable, if that Role does not exist in the given Guild, or if the given User is not in that Guild.

May also return an Error::Json if there is an error in deserializing the API response.

pub async fn refresh(&mut self, cache_http: impl CacheHttp) -> Result<()>[src]

Refreshes the information about the user.

Replaces the instance with the data retrieved over the REST API.

Errors

See UserId::to_user for what errors may be returned.

pub fn static_avatar_url(&self) -> Option<String>[src]

Returns a static formatted URL of the user’s icon, if one exists.

This will always produce a WEBP image URL.

pub fn tag(&self) -> String[src]

Returns the “tag” for the user.

The “tag” is defined as “username#discriminator”, such as “zeyla#5479”.

Examples

Make a command to tell the user what their tag is:

use serenity::utils::MessageBuilder;
use serenity::utils::ContentModifier::Bold;

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn message(&self, context: Context, msg: Message) {
        if msg.content == "!mytag" {
            let content = MessageBuilder::new()
                .push("Your tag is ")
                .push(Bold + msg.author.tag())
                .build();

            let _ = msg.channel_id.say(&context.http, &content).await;
        }
    }
}
let mut client =Client::builder("token").event_handler(Handler).await?;

client.start().await?;

pub async fn nick_in(
    &self,
    cache_http: impl CacheHttp,
    guild_id: impl Into<GuildId>
) -> Option<String>
[src]

Returns the user’s nickname in the given guild_id.

If none is used, it returns None.

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]

This is supported on crate feature collector only.

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

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]

This is supported on crate feature collector only.

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

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]

This is supported on crate feature collector only.

Await a single reaction by this user.

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

This is supported on crate feature collector only.

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

Trait Implementations

impl Clone for User[src]

fn clone(&self) -> User[src]

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl Debug for User[src]

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

Formats the value using the given formatter. Read more

impl Default for User[src]

fn default() -> Self[src]

Initializes a User with default values. Setting the following:

  • id to UserId(210)
  • avatar to Some("abc")
  • bot to true.
  • discriminator to 1432.
  • name to "test".
  • public_flags to None.

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

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
    __D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer. Read more

impl Display for User[src]

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

Formats a string which will mention the user.

impl From<&'_ User> for Mention[src]

fn from(value: &User) -> Self[src]

Performs the conversion.

impl<'a> From<&'a CurrentUser> for User[src]

fn from(user: &'a CurrentUser) -> Self[src]

Performs the conversion.

impl<'a> From<&'a User> for UserId[src]

fn from(user: &User) -> UserId[src]

Gets the Id of a User.

impl From<CurrentUser> for User[src]

fn from(user: CurrentUser) -> Self[src]

Performs the conversion.

impl From<User> for UserId[src]

fn from(user: User) -> UserId[src]

Gets the Id of a User.

impl Hash for User[src]

fn hash<H: Hasher>(&self, hasher: &mut H)[src]

Feeds this value into the given Hasher. Read more

fn hash_slice<H>(data: &[Self], state: &mut H) where
    H: Hasher
1.3.0[src]

Feeds a slice of this type into the given Hasher. Read more

impl Mentionable for User[src]

fn mention(&self) -> Mention[src]

Creates a Mention that will be able to notify or create a link to the item. Read more

impl PartialEq<User> for User[src]

fn eq(&self, other: &Self) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

#[must_use]
fn ne(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests for !=.

impl Serialize for User[src]

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where
    __S: Serializer
[src]

Serialize this value into the given Serde serializer. Read more

impl Eq for User[src]

Auto Trait Implementations

impl RefUnwindSafe for User

impl Send for User

impl Sync for User

impl Unpin for User

impl UnwindSafe for User

Blanket Implementations

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

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

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

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

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

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<Q, K> Equivalent<K> for Q where
    K: Borrow<Q> + ?Sized,
    Q: Eq + ?Sized
[src]

pub fn equivalent(&self, key: &K) -> bool[src]

Compare self to key and return true if they are equal.

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

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T> Instrument for T[src]

fn instrument(self, span: Span) -> Instrumented<Self>[src]

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

fn in_current_span(self) -> Instrumented<Self>[src]

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

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

pub fn into(self) -> U[src]

Performs the conversion.

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.

pub fn to_owned(&self) -> T[src]

Creates owned data from borrowed data, usually by cloning. Read more

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

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

pub default fn to_string(&self) -> String[src]

Converts the given value to a String. Read more

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.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]

Performs the conversion.

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.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.

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

pub fn vzip(self) -> V

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