1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
//! User information-related models.
use std::fmt;
#[cfg(feature = "model")]
use std::fmt::Write;
use bitflags::__impl_bitflags;
#[cfg(feature = "model")]
use futures::future::{BoxFuture, FutureExt};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "model")]
use serde_json::json;
use super::prelude::*;
use super::utils::deserialize_u16;
#[cfg(feature = "model")]
use crate::builder::{CreateBotAuthParameters, CreateMessage, EditProfile};
#[cfg(all(feature = "cache", feature = "model"))]
use crate::cache::Cache;
#[cfg(feature = "collector")]
use crate::client::bridge::gateway::ShardMessenger;
#[cfg(feature = "collector")]
use crate::collector::{
CollectReaction,
CollectReply,
MessageCollectorBuilder,
ReactionCollectorBuilder,
};
#[cfg(feature = "model")]
use crate::http::GuildPagination;
#[cfg(feature = "model")]
use crate::http::{CacheHttp, Http};
#[cfg(feature = "model")]
use crate::utils;
use crate::{internal::prelude::*, model::misc::Mentionable};
/// Information about the current user.
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CurrentUser {
pub id: UserId,
pub avatar: Option<String>,
#[serde(default)]
pub bot: bool,
#[serde(deserialize_with = "deserialize_u16")]
pub discriminator: u16,
pub email: Option<String>,
pub mfa_enabled: bool,
#[serde(rename = "username")]
pub name: String,
pub verified: Option<bool>,
pub public_flags: Option<UserPublicFlags>,
pub banner: Option<String>,
#[cfg(feature = "utils")]
pub accent_colour: Option<Colour>,
#[cfg(not(feature = "utils"))]
pub accent_colour: Option<u32>,
}
#[cfg(feature = "model")]
impl CurrentUser {
/// 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.
///
/// # Examples
///
/// Print out the current user's avatar url if one is set:
///
/// ```rust,no_run
/// # #[cfg(feature = "cache")]
/// # async fn run() {
/// # use serenity::cache::Cache;
/// # use tokio::sync::RwLock;
/// # use std::sync::Arc;
/// #
/// # let cache = Cache::default();
/// // assuming the cache has been unlocked
/// let user = cache.current_user().await;
///
/// match user.avatar_url() {
/// Some(url) => println!("{}'s avatar can be found at {}", user.name, url),
/// None => println!("{} does not have an avatar set.", user.name),
/// }
/// # }
/// ```
#[inline]
pub fn avatar_url(&self) -> Option<String> {
avatar_url(self.id, self.avatar.as_ref())
}
/// Returns the formatted URL to the user's default avatar URL.
///
/// This will produce a PNG URL.
#[inline]
pub fn default_avatar_url(&self) -> String {
default_avatar_url(self.discriminator)
}
/// Edits the current user's profile settings.
///
/// This mutates the current user in-place.
///
/// Refer to [`EditProfile`]'s documentation for its methods.
///
/// # Examples
///
/// Change the avatar:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::user::CurrentUser;
/// #
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http = Http::default();
/// # let mut user = CurrentUser::default();
/// let avatar = serenity::utils::read_image("./avatar.png")?;
///
/// user.edit(&http, |p| p.avatar(Some(&avatar))).await;
/// # Ok(())
/// # }
/// ```
///
/// [`EditProfile`]: crate::builder::EditProfile
///
/// # Errors
///
/// Returns an [`Error::Http`] if an invalid value is set.
/// May also return an [`Error::Json`] if there is an error in
/// deserializing the API response.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
pub async fn edit<F>(&mut self, http: impl AsRef<Http>, f: F) -> Result<()>
where
F: FnOnce(&mut EditProfile) -> &mut EditProfile,
{
let mut map = HashMap::new();
map.insert("username", Value::String(self.name.clone()));
if let Some(email) = self.email.as_ref() {
map.insert("email", Value::String(email.clone()));
}
let mut edit_profile = EditProfile(map);
f(&mut edit_profile);
let map = utils::hashmap_to_json_map(edit_profile.0);
*self = http.as_ref().edit_profile(&map).await?;
Ok(())
}
/// Retrieves the URL to the current 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`].
#[inline]
pub fn face(&self) -> String {
self.avatar_url().unwrap_or_else(|| self.default_avatar_url())
}
/// Gets a list of guilds that the current user is in.
///
/// # Examples
///
/// Print out the names of all guilds the current user is in:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::user::CurrentUser;
/// #
/// # async fn run() {
/// # let user = CurrentUser::default();
/// # let http = Http::default();
/// // assuming the user has been bound
///
/// if let Ok(guilds) = user.guilds(&http).await {
/// for (index, guild) in guilds.into_iter().enumerate() {
/// println!("{}: {}", index, guild.name);
/// }
/// }
/// # }
/// ```
///
/// # Errors
///
/// May return an [`Error::Http`] if the Discord API returns an error.
/// Also can return [`Error::Json`] if there is an error in deserializing
/// the data returned by the API.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
pub async fn guilds(&self, http: impl AsRef<Http>) -> Result<Vec<GuildInfo>> {
let mut guilds = Vec::new();
loop {
let mut pagination = http
.as_ref()
.get_guilds(
&GuildPagination::After(guilds.last().map_or(GuildId(1), |g: &GuildInfo| g.id)),
100,
)
.await?;
let len = pagination.len();
guilds.append(&mut pagination);
if len != 100 {
break;
}
}
Ok(guilds)
}
/// Returns the invite url for the bot with the given permissions.
///
/// This queries the REST API for the client id.
///
/// If the permissions passed are empty, the permissions part will be dropped.
///
/// Only the `bot` scope is used, if you wish to use more, such as slash commands, see
/// [`Self::invite_url_with_oauth2_scopes`]
///
/// # Examples
///
/// Get the invite url with no permissions set:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::user::CurrentUser;
/// #
/// # async fn run() {
/// # let user = CurrentUser::default();
/// # let http = Http::default();
/// use serenity::model::Permissions;
///
/// // assuming the user has been bound
/// let url = match user.invite_url(&http, Permissions::empty()).await {
/// Ok(v) => v,
/// Err(why) => {
/// println!("Error getting invite url: {:?}", why);
///
/// return;
/// },
/// };
///
/// assert_eq!(
/// url,
/// "https://discordapp.com/api/oauth2/authorize? \
/// client_id=249608697955745802&scope=bot"
/// );
/// # }
/// ```
///
/// Get the invite url with some basic permissions set:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::user::CurrentUser;
/// #
/// # async fn run() {
/// # let user = CurrentUser::default();
/// # let http = Http::default();
/// use serenity::model::Permissions;
///
/// // assuming the user has been bound
/// let permissions =
/// Permissions::READ_MESSAGES | Permissions::SEND_MESSAGES | Permissions::EMBED_LINKS;
/// let url = match user.invite_url(&http, permissions).await {
/// Ok(v) => v,
/// Err(why) => {
/// println!("Error getting invite url: {:?}", why);
///
/// return;
/// },
/// };
///
/// assert_eq!(
/// url,
/// "https://discordapp.
/// com/api/oauth2/authorize?client_id=249608697955745802&scope=bot&permissions=19456"
/// );
/// # }
/// ```
///
/// # Errors
///
/// Returns an
/// [`HttpError::UnsuccessfulRequest(Unauthorized)`][`HttpError::UnsuccessfulRequest`]
/// If the user is not authorized for this end point.
///
/// Should never return [`Error::Url`] as all the data is controlled over.
///
/// [`HttpError::UnsuccessfulRequest`]: crate::http::HttpError::UnsuccessfulRequest
pub async fn invite_url(
&self,
http: impl AsRef<Http>,
permissions: Permissions,
) -> Result<String> {
self.invite_url_with_oauth2_scopes(http, permissions, &[OAuth2Scope::Bot]).await
}
/// Generate an invite url, but with custom scopes.
///
/// # Examples
///
/// Get the invite url with no permissions set and slash commands support:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::user::CurrentUser;
/// #
/// # async fn run() {
/// # let user = CurrentUser::default();
/// # let http = Http::default();
/// use serenity::model::oauth2::OAuth2Scope;
/// use serenity::model::Permissions;
///
/// let scopes = vec![OAuth2Scope::Bot, OAuth2Scope::ApplicationsCommands];
///
/// // assuming the user has been bound
/// let url = match user.invite_url_with_oauth2_scopes(&http, Permissions::empty(), &scopes).await {
/// Ok(v) => v,
/// Err(why) => {
/// println!("Error getting invite url: {:?}", why);
///
/// return;
/// },
/// };
///
/// assert_eq!(
/// url,
/// "https://discordapp.com/api/oauth2/authorize? \
/// client_id=249608697955745802&scope=bot%20applications.commands"
/// );
/// # }
/// ```
/// # Errors
///
/// Returns an
/// [`HttpError::UnsuccessfulRequest(Unauthorized)`][`HttpError::UnsuccessfulRequest`]
/// If the user is not authorized for this end point.
///
/// Should never return [`Error::Url`] as all the data is controlled over.
///
/// [`HttpError::UnsuccessfulRequest`]: crate::http::HttpError::UnsuccessfulRequest
pub async fn invite_url_with_oauth2_scopes(
&self,
http: impl AsRef<Http>,
permissions: Permissions,
scopes: &[OAuth2Scope],
) -> Result<String> {
let mut builder = CreateBotAuthParameters::default();
builder.permissions(permissions);
builder.auto_client_id(http).await?;
builder.scopes(scopes);
Ok(builder.build())
}
/// Returns a static formatted URL of the user's icon, if one exists.
///
/// This will always produce a WEBP image URL.
///
/// # Examples
///
/// Print out the current user's static avatar url if one is set:
///
/// ```rust,no_run
/// # use serenity::model::user::CurrentUser;
/// #
/// # fn run() {
/// # let user = CurrentUser::default();
/// // assuming the user has been bound
///
/// match user.static_avatar_url() {
/// Some(url) => println!("{}'s static avatar can be found at {}", user.name, url),
/// None => println!("Could not get static avatar for {}.", user.name),
/// }
/// # }
/// ```
#[inline]
pub fn static_avatar_url(&self) -> Option<String> {
static_avatar_url(self.id, self.avatar.as_ref())
}
/// Returns the tag of the current user.
///
/// # Examples
///
/// Print out the current user's distinct identifier (e.g., Username#1234):
///
/// ```rust,no_run
/// # use serenity::model::user::CurrentUser;
/// #
/// # fn run() {
/// # let user = CurrentUser::default();
/// // assuming the user has been bound
///
/// println!("The current user's distinct identifier is {}", user.tag());
/// # }
/// ```
#[inline]
pub fn tag(&self) -> String {
tag(&self.name, self.discriminator)
}
}
/// An enum that represents a default avatar.
///
/// The default avatar is calculated via the result of `discriminator % 5`.
///
/// The has of the avatar can be retrieved via calling [`Self::name`] on the enum.
#[derive(Copy, Clone, Debug, Deserialize, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub enum DefaultAvatar {
/// The avatar when the result is `0`.
#[serde(rename = "6debd47ed13483642cf09e832ed0bc1b")]
Blurple,
/// The avatar when the result is `1`.
#[serde(rename = "322c936a8c8be1b803cd94861bdfa868")]
Grey,
/// The avatar when the result is `2`.
#[serde(rename = "dd4dbc0016779df1378e7812eabaa04d")]
Green,
/// The avatar when the result is `3`.
#[serde(rename = "0e291f67c9274a1abdddeb3fd919cbaa")]
Orange,
/// The avatar when the result is `4`.
#[serde(rename = "1cbd08c76f8af6dddce02c5138971129")]
Red,
}
impl DefaultAvatar {
/// Retrieves the String hash of the default avatar.
///
/// # Errors
///
/// May return a [`Error::Json`] if there is a serialization error.
///
/// [`Error::Json`]: crate::error::Error::Json
pub fn name(self) -> Result<String> {
serde_json::to_string(&self).map_err(From::from)
}
}
/// The representation of a user's status.
///
/// # Examples
///
/// - [`DoNotDisturb`];
/// - [`Invisible`].
///
/// [`DoNotDisturb`]: OnlineStatus::DoNotDisturb
/// [`Invisible`]: OnlineStatus::Invisible
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub enum OnlineStatus {
#[serde(rename = "dnd")]
DoNotDisturb,
#[serde(rename = "idle")]
Idle,
#[serde(rename = "invisible")]
Invisible,
#[serde(rename = "offline")]
Offline,
#[serde(rename = "online")]
Online,
}
impl OnlineStatus {
pub fn name(&self) -> &str {
match *self {
OnlineStatus::DoNotDisturb => "dnd",
OnlineStatus::Idle => "idle",
OnlineStatus::Invisible => "invisible",
OnlineStatus::Offline => "offline",
OnlineStatus::Online => "online",
}
}
}
impl Default for OnlineStatus {
fn default() -> OnlineStatus {
OnlineStatus::Online
}
}
/// Information about a user.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct User {
/// The unique Id of the user. Can be used to calculate the account's
/// creation date.
pub id: UserId,
/// Optional avatar hash.
pub avatar: Option<String>,
/// Indicator of whether the user is a bot.
#[serde(default)]
pub bot: bool,
/// The account's discriminator to differentiate the user from others with
/// the same [`Self::name`]. The name+discriminator pair is always unique.
#[serde(deserialize_with = "deserialize_u16")]
pub discriminator: u16,
/// The account's username. Changing username will trigger a discriminator
/// change if the username+discriminator pair becomes non-unique.
#[serde(rename = "username")]
pub name: String,
/// The public flags on a user's account
pub public_flags: Option<UserPublicFlags>,
/// Optional banner hash.
///
/// **Note**: This will only be present if the user is fetched via Rest API,
/// e.g. with [`Http::get_user`].
pub banner: Option<String>,
/// 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`].
#[cfg(feature = "utils")]
#[serde(rename = "accent_color")]
pub accent_colour: Option<Colour>,
#[cfg(not(feature = "utils"))]
#[serde(rename = "accent_color")]
pub accent_colour: Option<u32>,
}
/// User's public flags
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UserPublicFlags {
pub bits: u32,
}
__impl_bitflags! {
UserPublicFlags: u32 {
/// User's flag as discord employee
DISCORD_EMPLOYEE = 1 << 0;
/// User's flag as partnered server owner
PARTNERED_SERVER_OWNER = 1 << 1;
/// User's flag as hypesquad events
HYPESQUAD_EVENTS = 1 << 2;
/// User's flag as bug hunter level 1
BUG_HUNTER_LEVEL_1 = 1 << 3;
/// User's flag as house bravery
HOUSE_BRAVERY = 1 << 6;
/// User's flag as house brilliance
HOUSE_BRILLIANCE = 1 << 7;
/// User's flag as house balance
HOUSE_BALANCE = 1 << 8;
/// User's flag as early supporter
EARLY_SUPPORTER = 1 << 9;
/// User's flag as team user
TEAM_USER = 1 << 10;
/// User's flag as system
SYSTEM = 1 << 12;
/// User's flag as bug hunter level 2
BUG_HUNTER_LEVEL_2 = 1 << 14;
/// User's flag as verified bot
VERIFIED_BOT = 1 << 16;
/// User's flag as early verified bot developer
EARLY_VERIFIED_BOT_DEVELOPER = 1 << 17;
/// User's flag as discord certified moderator
DISCORD_CERTIFIED_MODERATOR = 1 << 18;
/// Bot's running with HTTP interactions
BOT_HTTP_INTERACTIONS = 1 << 19;
}
}
impl<'de> Deserialize<'de> for UserPublicFlags {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(UserPublicFlags::from_bits_truncate(deserializer.deserialize_u32(U32Visitor)?))
}
}
impl Serialize for UserPublicFlags {
fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.bits())
}
}
impl Default for User {
/// 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`].
fn default() -> Self {
User {
id: UserId(210),
avatar: Some("abc".to_string()),
bot: true,
discriminator: 1432,
name: "test".to_string(),
public_flags: None,
banner: None,
accent_colour: None,
}
}
}
use std::hash::{Hash, Hasher};
#[cfg(feature = "model")]
use chrono::{DateTime, Utc};
impl PartialEq for User {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for User {}
impl Hash for User {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.id.hash(hasher);
}
}
#[cfg(feature = "model")]
impl User {
/// 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.
#[inline]
pub fn avatar_url(&self) -> Option<String> {
avatar_url(self.id, self.avatar.as_ref())
}
/// 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`].
#[inline]
pub fn banner_url(&self) -> Option<String> {
banner_url(self.id, self.banner.as_ref())
}
/// Creates a direct message channel between the [current user] and the
/// user. This can also retrieve the channel if one already exists.
///
/// [current user]: CurrentUser
///
/// # Errors
///
/// See [`UserId::create_dm_channel`] for what errors may be returned.
///
/// [`UserId::create_dm_channel`]: crate::model::id::UserId::create_dm_channel
#[inline]
pub async fn create_dm_channel(&self, cache_http: impl CacheHttp) -> Result<PrivateChannel> {
if self.bot {
return Err(Error::Model(ModelError::MessagingBot));
}
self.id.create_dm_channel(cache_http).await
}
/// Retrieves the time that this user was created at.
#[inline]
pub fn created_at(&self) -> DateTime<Utc> {
self.id.created_at()
}
/// Returns the formatted URL to the user's default avatar URL.
///
/// This will produce a PNG URL.
#[inline]
pub fn default_avatar_url(&self) -> String {
default_avatar_url(self.discriminator)
}
/// 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:
///
/// ```rust,no_run
/// # #[cfg(feature="client")] {
/// # use serenity::prelude::*;
/// # use serenity::model::prelude::*;
/// #
/// use serenity::model::Permissions;
///
/// struct Handler;
///
/// #[serenity::async_trait]
/// impl EventHandler for Handler {
/// # #[cfg(feature = "cache")]
/// 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;
/// },
/// };
/// }
/// }
/// }
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let mut client = Client::builder("token").event_handler(Handler).await?;
/// # Ok(())
/// # }
/// # }
/// ```
///
/// # 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.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
pub async fn direct_message<F>(&self, cache_http: impl CacheHttp, f: F) -> Result<Message>
where
for<'a, 'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
{
self.create_dm_channel(&cache_http).await?.send_message(&cache_http.http(), f).await
}
/// This is an alias of [`Self::direct_message`].
#[allow(clippy::missing_errors_doc)]
#[inline]
pub async fn dm<F>(&self, cache_http: impl CacheHttp, f: F) -> Result<Message>
where
for<'a, 'b> F: FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
{
self.direct_message(cache_http, f).await
}
/// 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 fn face(&self) -> String {
self.avatar_url().unwrap_or_else(|| 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:
///
/// ```rust,ignore
/// // Assumes a 'guild_id' and `role_id` have already been bound
/// let _ = message.author.has_role(guild_id, role_id);
/// ```
///
/// [`Cache`]: crate::cache::Cache
///
/// # 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.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
#[inline]
pub async fn has_role(
&self,
cache_http: impl CacheHttp,
guild: impl Into<GuildContainer>,
role: impl Into<RoleId>,
) -> Result<bool> {
self._has_role(&cache_http, guild.into(), role.into()).await
}
fn _has_role<'a>(
&'a self,
cache_http: &'a impl CacheHttp,
guild: GuildContainer,
role: RoleId,
) -> BoxFuture<'a, Result<bool>> {
async move {
match guild {
GuildContainer::Guild(partial_guild) => {
self._has_role(cache_http, GuildContainer::Id(partial_guild.id), role).await
},
GuildContainer::Id(guild_id) => {
// Silences a warning when compiling without the `cache` feature.
#[allow(unused_mut)]
let mut has_role = None;
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
if let Some(member) = cache.member(guild_id, self.id).await {
has_role = Some(member.roles.contains(&role));
}
}
}
if let Some(has_role) = has_role {
Ok(has_role)
} else {
cache_http
.http()
.get_member(guild_id.0, self.id.0)
.await
.map(|m| m.roles.contains(&role))
}
},
}
}
.boxed()
}
/// 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.
///
/// [`UserId::to_user`]: crate::model::id::UserId::to_user
#[inline]
pub async fn refresh(&mut self, cache_http: impl CacheHttp) -> Result<()> {
*self = self.id.to_user(cache_http).await?;
Ok(())
}
/// Returns a static formatted URL of the user's icon, if one exists.
///
/// This will always produce a WEBP image URL.
#[inline]
pub fn static_avatar_url(&self) -> Option<String> {
static_avatar_url(self.id, self.avatar.as_ref())
}
/// 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:
///
/// ```rust,no_run
/// # #[cfg(feature = "client")]
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # use serenity::prelude::*;
/// # use serenity::model::prelude::*;
/// #
/// 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?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn tag(&self) -> String {
tag(&self.name, self.discriminator)
}
/// Returns the user's nickname in the given `guild_id`.
///
/// If none is used, it returns [`None`].
#[inline]
pub async fn nick_in(
&self,
cache_http: impl CacheHttp,
guild_id: impl Into<GuildId>,
) -> Option<String> {
let guild_id = guild_id.into();
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
if let Some(guild) = guild_id.to_guild_cached(cache).await {
if let Some(member) = guild.members.get(&self.id) {
return member.nick.clone();
}
}
}
}
guild_id.member(cache_http, &self.id).await.ok().and_then(|member| member.nick)
}
/// Returns a future that will await one message by this user.
#[cfg(feature = "collector")]
pub fn await_reply<'a>(
&self,
shard_messenger: &'a impl AsRef<ShardMessenger>,
) -> CollectReply<'a> {
CollectReply::new(shard_messenger).author_id(self.id.0)
}
/// Returns a stream builder which can be awaited to obtain a stream of messages sent by this user.
#[cfg(feature = "collector")]
pub fn await_replies<'a>(
&self,
shard_messenger: &'a impl AsRef<ShardMessenger>,
) -> MessageCollectorBuilder<'a> {
MessageCollectorBuilder::new(shard_messenger).author_id(self.id.0)
}
/// Await a single reaction by this user.
#[cfg(feature = "collector")]
pub fn await_reaction<'a>(
&self,
shard_messenger: &'a impl AsRef<ShardMessenger>,
) -> CollectReaction<'a> {
CollectReaction::new(shard_messenger).author_id(self.id.0)
}
/// Returns a stream builder which can be awaited to obtain a stream of reactions sent by this user.
#[cfg(feature = "collector")]
pub fn await_reactions<'a>(
&self,
shard_messenger: &'a impl AsRef<ShardMessenger>,
) -> ReactionCollectorBuilder<'a> {
ReactionCollectorBuilder::new(shard_messenger).author_id(self.id.0)
}
}
impl fmt::Display for User {
/// Formats a string which will mention the user.
// This is in the format of: `<@USER_ID>`
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.id.mention(), f)
}
}
#[cfg(feature = "model")]
impl UserId {
/// Creates a direct message channel between the [current user] and the
/// user. This can also retrieve the channel if one already exists.
///
/// [current user]: CurrentUser
///
/// # Errors
///
/// Returns [`Error::Http`] if a [`User`] with that [`UserId`] does not exist,
/// or is otherwise unavailable.
///
/// May also return an [`Error::Json`] if there is an error in deserializing
/// the channel data returned by the Discord API.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
pub async fn create_dm_channel(self, cache_http: impl CacheHttp) -> Result<PrivateChannel> {
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
for channel in cache.private_channels().await.values() {
if channel.recipient.id == self {
return Ok(channel.clone());
}
}
}
}
let map = json!({
"recipient_id": self.0,
});
cache_http.http().create_private_channel(&map).await
}
/// Attempts to find a [`User`] by its Id in the cache.
#[cfg(feature = "cache")]
#[inline]
pub async fn to_user_cached(self, cache: impl AsRef<Cache>) -> Option<User> {
cache.as_ref().user(self).await
}
/// First attempts to find a [`User`] by its Id in the cache,
/// upon failure requests it via the REST API.
///
/// **Note**: If the cache is not enabled,
/// REST API will be used only.
///
/// # Errors
///
/// May return an [`Error::Http`] if a [`User`] with that [`UserId`] does not exist,
/// or otherwise cannot be fetched.
///
/// May also return an [`Error::Json`] if there is an error in
/// deserializing the user.
///
/// [`Error::Http`]: crate::error::Error::Http
/// [`Error::Json`]: crate::error::Error::Json
#[inline]
pub async fn to_user(self, cache_http: impl CacheHttp) -> Result<User> {
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
if let Some(user) = cache.user(self).await {
return Ok(user);
}
}
}
cache_http.http().get_user(self.0).await
}
}
impl From<CurrentUser> for User {
fn from(user: CurrentUser) -> Self {
Self {
avatar: user.avatar,
bot: user.bot,
discriminator: user.discriminator,
id: user.id,
name: user.name,
public_flags: user.public_flags,
banner: user.banner,
accent_colour: user.accent_colour,
}
}
}
impl<'a> From<&'a CurrentUser> for User {
fn from(user: &'a CurrentUser) -> Self {
Self {
avatar: user.avatar.clone(),
bot: user.bot,
discriminator: user.discriminator,
id: user.id,
name: user.name.clone(),
public_flags: user.public_flags,
banner: user.banner.clone(),
accent_colour: user.accent_colour,
}
}
}
impl From<CurrentUser> for UserId {
/// Gets the Id of a [`CurrentUser`] struct.
fn from(current_user: CurrentUser) -> UserId {
current_user.id
}
}
impl<'a> From<&'a CurrentUser> for UserId {
/// Gets the Id of a [`CurrentUser`] struct.
fn from(current_user: &CurrentUser) -> UserId {
current_user.id
}
}
impl From<Member> for UserId {
/// Gets the Id of a [`Member`].
fn from(member: Member) -> UserId {
member.user.id
}
}
impl<'a> From<&'a Member> for UserId {
/// Gets the Id of a [`Member`].
fn from(member: &Member) -> UserId {
member.user.id
}
}
impl From<User> for UserId {
/// Gets the Id of a [`User`].
fn from(user: User) -> UserId {
user.id
}
}
impl<'a> From<&'a User> for UserId {
/// Gets the Id of a [`User`].
fn from(user: &User) -> UserId {
user.id
}
}
#[cfg(feature = "model")]
fn avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> {
hash.map(|hash| {
let ext = if hash.starts_with("a_") { "gif" } else { "webp" };
cdn!("/avatars/{}/{}.{}?size=1024", user_id.0, hash, ext)
})
}
#[cfg(feature = "model")]
fn default_avatar_url(discriminator: u16) -> String {
cdn!("/embed/avatars/{}.png", discriminator % 5u16)
}
#[cfg(feature = "model")]
fn static_avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> {
hash.map(|hash| cdn!("/avatars/{}/{}.webp?size=1024", user_id, hash))
}
#[cfg(feature = "model")]
fn banner_url(user_id: UserId, hash: Option<&String>) -> Option<String> {
hash.map(|hash| {
let ext = if hash.starts_with("a_") { "gif" } else { "webp" };
cdn!("/banners/{}/{}.{}?size=1024", user_id.0, hash, ext)
})
}
#[cfg(feature = "model")]
fn tag(name: &str, discriminator: u16) -> String {
// 32: max length of username
// 1: `#`
// 4: max length of discriminator
let mut tag = String::with_capacity(37);
tag.push_str(name);
tag.push('#');
#[allow(clippy::let_underscore_must_use)]
let _ = write!(tag, "{:04}", discriminator);
tag
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod test {
#[cfg(feature = "model")]
mod model {
use crate::model::user::User;
#[test]
fn test_core() {
let mut user = User::default();
assert!(user.avatar_url().unwrap().ends_with("/avatars/210/abc.webp?size=1024"));
assert!(user.static_avatar_url().unwrap().ends_with("/avatars/210/abc.webp?size=1024"));
user.avatar = Some("a_aaa".to_string());
assert!(user.avatar_url().unwrap().ends_with("/avatars/210/a_aaa.gif?size=1024"));
assert!(user
.static_avatar_url()
.unwrap()
.ends_with("/avatars/210/a_aaa.webp?size=1024"));
user.avatar = None;
assert!(user.avatar_url().is_none());
assert_eq!(user.tag(), "test#1432");
}
#[test]
fn default_avatars() {
let mut user = User {
discriminator: 0,
..Default::default()
};
assert!(user.default_avatar_url().ends_with("0.png"));
user.discriminator = 1;
assert!(user.default_avatar_url().ends_with("1.png"));
user.discriminator = 2;
assert!(user.default_avatar_url().ends_with("2.png"));
user.discriminator = 3;
assert!(user.default_avatar_url().ends_with("3.png"));
user.discriminator = 4;
assert!(user.default_avatar_url().ends_with("4.png"));
}
}
}