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>, pub banner: Option<String>, pub accent_colour: Option<Colour>, }
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

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

avatar: Option<String>

Optional avatar hash.

bot: bool

Indicator of whether the user is a bot.

discriminator: u16

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

name: String

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

public_flags: Option<UserPublicFlags>

The public flags on a user’s account

banner: Option<String>

Optional banner hash.

Note: This will only be present if the user is fetched via Rest API, e.g. with Http::get_user.

accent_colour: Option<Colour>

The user’s banner colour encoded as an integer representation of hexadecimal colour code

Note: This will only be present if the user is fetched via Rest API, e.g. with Http::get_user.

Implementations

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.

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

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

Note: This will only be present if the user is fetched via Rest API, e.g. with Http::get_user.

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.

Retrieves the time that this user was created at.

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

This will produce a PNG URL.

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.

This is an alias of Self::direct_message.

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.

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.

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.

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

This will always produce a WEBP image URL.

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::ContentModifier::Bold;
use serenity::utils::MessageBuilder;

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?;

Returns the user’s nickname in the given guild_id.

If none is used, it returns None.

Trait Implementations

Look up a user by a string case-insensitively.

Requires the cache feature to be enabled. If a user is not in cache, they will not be found!

The lookup strategy is as follows (in order):

  1. Lookup by ID.
  2. Lookup by mention.
  3. Lookup by name#discrim.
  4. Lookup by name

The associated error which can be returned from parsing.

Parses a string s as a command parameter of this type.

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

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.

Deserialize this value from the given Serde deserializer. Read more

Formats a string which will mention the user.

Performs the conversion.

Performs the conversion.

Gets the Id of a User.

Performs the conversion.

Gets the Id of a User.

Feeds this value into the given Hasher. Read more

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

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

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

This method tests for !=.

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

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

Performs the conversion.

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

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

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

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

Performs the conversion.

Should always be Self

The resulting type after obtaining ownership.

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

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

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

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more