#[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
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
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>
utils
only.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
sourceimpl User
impl User
sourcepub fn avatar_url(&self) -> Option<String>
Available on crate feature model
only.
pub fn avatar_url(&self) -> Option<String>
model
only.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.
Available on crate feature model
only.
model
only.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
.
sourcepub async fn create_dm_channel(
&self,
cache_http: impl CacheHttp
) -> Result<PrivateChannel>
Available on crate feature model
only.
pub async fn create_dm_channel(
&self,
cache_http: impl CacheHttp
) -> Result<PrivateChannel>
model
only.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.
sourcepub fn created_at(&self) -> Timestamp
Available on crate feature model
only.
pub fn created_at(&self) -> Timestamp
model
only.Retrieves the time that this user was created at.
sourcepub fn default_avatar_url(&self) -> String
Available on crate feature model
only.
pub fn default_avatar_url(&self) -> String
model
only.Returns the formatted URL to the user’s default avatar URL.
This will produce a PNG URL.
sourcepub async fn direct_message<'a, F>(
&self,
cache_http: impl CacheHttp,
f: F
) -> Result<Message> where
for<'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
Available on crate feature model
only.
pub async fn direct_message<'a, F>(
&self,
cache_http: impl CacheHttp,
f: F
) -> Result<Message> where
for<'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
model
only.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().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", GatewayIntents::default()).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.
sourcepub async fn dm<'a, F>(&self, cache_http: impl CacheHttp, f: F) -> Result<Message> where
for<'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
Available on crate feature model
only.
pub async fn dm<'a, F>(&self, cache_http: impl CacheHttp, f: F) -> Result<Message> where
for<'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
model
only.This is an alias of Self::direct_message
.
sourcepub fn face(&self) -> String
Available on crate feature model
only.
pub fn face(&self) -> String
model
only.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
.
sourcepub async fn has_role(
&self,
cache_http: impl CacheHttp,
guild: impl Into<GuildContainer>,
role: impl Into<RoleId>
) -> Result<bool>
Available on crate feature model
only.
pub async fn has_role(
&self,
cache_http: impl CacheHttp,
guild: impl Into<GuildContainer>,
role: impl Into<RoleId>
) -> Result<bool>
model
only.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.
sourcepub async fn refresh(&mut self, cache_http: impl CacheHttp) -> Result<()>
Available on crate feature model
only.
pub async fn refresh(&mut self, cache_http: impl CacheHttp) -> Result<()>
model
only.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.
sourcepub fn static_avatar_url(&self) -> Option<String>
Available on crate feature model
only.
pub fn static_avatar_url(&self) -> Option<String>
model
only.Returns a static formatted URL of the user’s icon, if one exists.
This will always produce a WEBP image URL.
sourcepub fn tag(&self) -> String
Available on crate feature model
only.
pub fn tag(&self) -> String
model
only.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", GatewayIntents::default()).event_handler(Handler).await?;
client.start().await?;
sourcepub async fn nick_in(
&self,
cache_http: impl CacheHttp,
guild_id: impl Into<GuildId>
) -> Option<String>
Available on crate feature model
only.
pub async fn nick_in(
&self,
cache_http: impl CacheHttp,
guild_id: impl Into<GuildId>
) -> Option<String>
model
only.Returns the user’s nickname in the given guild_id
.
If none is used, it returns None
.
sourcepub fn await_reply(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> CollectReplyⓘNotable traits for CollectReplyimpl Future for CollectReply type Output = Option<Arc<Message>>;
Available on crate features model
and collector
only.
pub fn await_reply(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> CollectReplyⓘNotable traits for CollectReplyimpl Future for CollectReply type Output = Option<Arc<Message>>;
model
and collector
only.Returns a future that will await one message by this user.
sourcepub fn await_replies(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> MessageCollectorBuilder
Available on crate features model
and collector
only.
pub fn await_replies(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> MessageCollectorBuilder
model
and collector
only.Returns a stream builder which can be awaited to obtain a stream of messages sent by this user.
sourcepub fn await_reaction(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> CollectReactionⓘNotable traits for CollectReactionimpl Future for CollectReaction type Output = Option<Arc<ReactionAction>>;
Available on crate features model
and collector
only.
pub fn await_reaction(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> CollectReactionⓘNotable traits for CollectReactionimpl Future for CollectReaction type Output = Option<Arc<ReactionAction>>;
model
and collector
only.Await a single reaction by this user.
sourcepub fn await_reactions(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> ReactionCollectorBuilder
Available on crate features model
and collector
only.
pub fn await_reactions(
&self,
shard_messenger: impl AsRef<ShardMessenger>
) -> ReactionCollectorBuilder
model
and collector
only.Returns a stream builder which can be awaited to obtain a stream of reactions sent by this user.
Trait Implementations
sourceimpl ArgumentConvert for User
impl ArgumentConvert for User
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):
- Lookup by ID.
- Lookup by mention.
- Lookup by name#discrim.
- Lookup by name
type Err = UserParseError
type Err = UserParseError
utils
and client
only.The associated error which can be returned from parsing.
sourcefn convert<'life0, 'life1, 'async_trait>(
ctx: &'life0 Context,
guild_id: Option<GuildId>,
channel_id: Option<ChannelId>,
s: &'life1 str
) -> Pin<Box<dyn Future<Output = Result<Self, Self::Err>> + Send + 'async_trait>> where
'life0: 'async_trait,
'life1: 'async_trait,
Self: 'async_trait,
fn convert<'life0, 'life1, 'async_trait>(
ctx: &'life0 Context,
guild_id: Option<GuildId>,
channel_id: Option<ChannelId>,
s: &'life1 str
) -> Pin<Box<dyn Future<Output = Result<Self, Self::Err>> + Send + 'async_trait>> where
'life0: 'async_trait,
'life1: 'async_trait,
Self: 'async_trait,
utils
and client
only.Parses a string s
as a command parameter of this type.
sourceimpl<'de> Deserialize<'de> for User
impl<'de> Deserialize<'de> for User
sourcefn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl<'a> From<&'a CurrentUser> for User
impl<'a> From<&'a CurrentUser> for User
sourcefn from(user: &'a CurrentUser) -> Self
fn from(user: &'a CurrentUser) -> Self
Converts to this type from the input type.
sourceimpl From<CurrentUser> for User
impl From<CurrentUser> for User
sourcefn from(user: CurrentUser) -> Self
fn from(user: CurrentUser) -> Self
Converts to this type from the input type.
sourceimpl Mentionable for User
impl Mentionable for User
impl Eq for User
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
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
sourcefn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to key
and return true
if they are equal.
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more