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
//! Models relating to Discord channels. use std::fmt::Display; #[cfg(all(feature = "cache", feature = "model"))] use std::fmt::Write; #[cfg(feature = "model")] use std::result::Result as StdResult; #[cfg(feature = "model")] use bitflags::__impl_bitflags; use chrono::{DateTime, Utc}; #[cfg(feature = "model")] use serde::{ de::{Deserialize, Deserializer}, ser::{Serialize, Serializer}, }; use serde_json::Value; #[cfg(all(feature = "model", feature = "utils"))] use crate::builder::{CreateEmbed, EditMessage}; #[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, ReactionCollectorBuilder}; #[cfg(feature = "model")] use crate::http::{CacheHttp, Http}; #[cfg(feature = "unstable_discord_api")] use crate::model::interactions::MessageInteraction; use crate::model::prelude::*; #[cfg(feature = "model")] use crate::model::utils::U64Visitor; #[cfg(feature = "model")] use crate::{ constants, model::id::{ApplicationId, ChannelId, GuildId, MessageId}, }; /// A representation of a message over a guild's text channel, a group, or a /// private channel. #[derive(Clone, Debug, Deserialize, Serialize)] #[non_exhaustive] pub struct Message { /// The unique Id of the message. Can be used to calculate the creation date /// of the message. pub id: MessageId, /// An vector of the files attached to a message. pub attachments: Vec<Attachment>, /// The user that sent the message. pub author: User, /// The Id of the [`Channel`] that the message was sent to. pub channel_id: ChannelId, /// The content of the message. pub content: String, /// The timestamp of the last time the message was updated, if it was. pub edited_timestamp: Option<DateTime<Utc>>, /// Array of embeds sent with the message. pub embeds: Vec<Embed>, /// The Id of the [`Guild`] that the message was sent in. This value will /// only be present if this message was received over the gateway. pub guild_id: Option<GuildId>, /// Indicator of the type of message this is, i.e. whether it is a regular /// message or a system message. #[serde(rename = "type")] pub kind: MessageType, /// A partial amount of data about the user's member data, if this message /// was sent in a guild. pub member: Option<PartialMember>, /// Indicator of whether the message mentions everyone. pub mention_everyone: bool, /// Array of [`Role`]s' Ids mentioned in the message. pub mention_roles: Vec<RoleId>, /// Channels specifically mentioned in this message. #[serde(default = "Vec::new")] pub mention_channels: Vec<ChannelMention>, /// Array of users mentioned in the message. pub mentions: Vec<User>, /// Non-repeating number used for ensuring message order. #[serde(default)] pub nonce: Value, /// Indicator of whether the message is pinned. pub pinned: bool, /// Array of reactions performed on the message. #[serde(default)] pub reactions: Vec<MessageReaction>, /// Initial message creation timestamp, calculated from its Id. pub timestamp: DateTime<Utc>, /// Indicator of whether the command is to be played back via /// text-to-speech. /// /// In the client, this is done via the `/tts` slash command. pub tts: bool, /// The Id of the webhook that sent this message, if one did. pub webhook_id: Option<WebhookId>, /// Sent with Rich Presence-related chat embeds. pub activity: Option<MessageActivity>, /// Sent with Rich Presence-related chat embeds. pub application: Option<MessageApplication>, /// Reference data sent with crossposted messages. pub message_reference: Option<MessageReference>, /// Bit flags describing extra features of the message. pub flags: Option<MessageFlags>, /// Array of stickers sent with the message. #[serde(default)] pub stickers: Vec<Sticker>, /// The message that was replied to using this message. pub referenced_message: Option<Box<Message>>, // Boxed to avoid recusion /// Sent if the message is a response to an [`Interaction`]. /// /// [`Interaction`]: crate::model::interactions::Interaction #[cfg(feature = "unstable_discord_api")] #[cfg_attr(docsrs, doc(cfg(feature = "unstable_discord_api")))] pub interaction: Option<MessageInteraction>, } #[cfg(feature = "model")] impl Message { /// Retrieves the related channel located in the cache. /// /// Returns `None` if the channel is not in the cache. #[cfg(feature = "cache")] #[inline] pub async fn channel(&self, cache: impl AsRef<Cache>) -> Option<Channel> { cache.as_ref().channel(self.channel_id).await } /// A util function for determining whether this message was sent by someone else, or the /// bot. #[cfg(all(feature = "cache", feature = "utils"))] pub async fn is_own(&self, cache: impl AsRef<Cache>) -> bool { self.author.id == cache.as_ref().current_user().await.id } /// Deletes the message. /// /// **Note**: The logged in user must either be the author of the message or /// have the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` feature is enabled, then returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES pub async fn delete(&self, cache_http: impl CacheHttp) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.author.id != cache.current_user_id().await { if self.is_private() { return Err(Error::Model(ModelError::NotAuthor)); } else { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; } } } } self.channel_id.delete_message(&cache_http.http(), self.id).await } /// Deletes all of the [`Reaction`]s associated with the message. /// /// **Note**: Requires the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` feature is enabled, then returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES pub async fn delete_reactions(&self, cache_http: impl CacheHttp) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; } } cache_http.http().as_ref().delete_message_reactions(self.channel_id.0, self.id.0).await } /// Deletes all of the [`Reaction`]s of a given emoji associated with the message. /// /// **Note**: Requires the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` feature is enabled, then returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES pub async fn delete_reaction_emoji( &self, cache_http: impl CacheHttp, reaction_type: impl Into<ReactionType>, ) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; } } cache_http .http() .as_ref() .delete_message_reaction_emoji(self.channel_id.0, self.id.0, &reaction_type.into()) .await } /// Edits this message, replacing the original content with new content. /// /// 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. /// /// # Examples /// /// Edit a message with new content: /// /// ```rust,ignore /// // assuming a `message` has already been bound /// /// message.edit(&context, |m| m.content("new content")); /// ``` /// /// # Errors /// /// If the `cache` is enabled, returns a [`ModelError::InvalidUser`] if the /// current user is not the author. /// /// Returns a [`ModelError::MessageTooLong`] if the content of the message /// is over [`the limit`], containing the number of unicode code points /// over the limit. /// /// [`EditMessage`]: crate::builder::EditMessage /// [`the limit`]: crate::builder::EditMessage::content #[cfg(feature = "utils")] pub async fn edit<F>(&mut self, cache_http: impl CacheHttp, f: F) -> Result<()> where F: FnOnce(&mut EditMessage) -> &mut EditMessage, { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.author.id != cache.current_user_id().await { return Err(Error::Model(ModelError::InvalidUser)); } } } let mut builder = EditMessage::default(); if !self.content.is_empty() { builder.content(&self.content); } if let Some(embed) = self.embeds.get(0) { let embed = CreateEmbed::from(embed.clone()); builder.embed(|e| { *e = embed; e }); } f(&mut builder); let map = crate::utils::hashmap_to_json_map(builder.0); *self = cache_http .http() .edit_message(self.channel_id.0, self.id.0, &Value::Object(map)) .await?; Ok(()) } pub(crate) fn transform_content(&mut self) { match self.kind { MessageType::PinsAdd => { self.content = format!("{} pinned a message to this channel. See all the pins.", self.author); }, MessageType::MemberJoin => { let sec = self.timestamp.timestamp() as usize; let chosen = constants::JOIN_MESSAGES[sec % constants::JOIN_MESSAGES.len()]; self.content = if chosen.contains("$user") { chosen.replace("$user", &self.author.mention().to_string()) } else { chosen.to_string() }; }, _ => {}, } } /// Returns message content, but with user and role mentions replaced with /// names and everyone/here mentions cancelled. #[cfg(feature = "cache")] pub async fn content_safe(&self, cache: impl AsRef<Cache>) -> String { let mut result = self.content.clone(); // First replace all user mentions. for u in &self.mentions { let mut at_distinct = String::with_capacity(38); at_distinct.push('@'); at_distinct.push_str(&u.name); at_distinct.push('#'); #[allow(clippy::let_underscore_must_use)] let _ = write!(at_distinct, "{:04}", u.discriminator); let mut m = u.mention().to_string(); // Check whether we're replacing a nickname mention or a normal mention. // `UserId::mention` returns a normal mention. If it isn't present in the message, it's a nickname mention. if !result.contains(&m) { m.insert(2, '!'); } result = result.replace(&m, &at_distinct); } // Then replace all role mentions. for id in &self.mention_roles { let mention = id.mention().to_string(); if let Some(role) = id.to_role_cached(&cache).await { result = result.replace(&mention, &format!("@{}", role.name)); } else { result = result.replace(&mention, "@deleted-role"); } } // And finally replace everyone and here mentions. result.replace("@everyone", "@\u{200B}everyone").replace("@here", "@\u{200B}here") } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. /// /// The default `limit` is `50` - specify otherwise to receive a different /// maximum number of users. The maximum that may be retrieve at a time is /// `100`, if a greater number is provided then it is automatically reduced. /// /// The optional `after` attribute is to retrieve the users after a certain /// user. This is useful for pagination. /// /// **Note**: Requires the [Read Message History] permission. /// /// # Errors /// /// Returns [`Error::Http`] if the current user lacks permission. /// /// [Read Message History]: Permissions::READ_MESSAGE_HISTORY #[inline] pub async fn reaction_users( &self, http: impl AsRef<Http>, reaction_type: impl Into<ReactionType>, limit: Option<u8>, after: impl Into<Option<UserId>>, ) -> Result<Vec<User>> { self.channel_id.reaction_users(&http, self.id, reaction_type, limit, after).await } /// Returns the associated `Guild` for the message if one is in the cache. /// /// Returns `None` if the guild's Id could not be found via [`guild_id`] or /// if the Guild itself is not cached. /// /// Requires the `cache` feature be enabled. /// /// [`guild_id`]: Self::guild_id #[cfg(feature = "cache")] pub async fn guild(&self, cache: impl AsRef<Cache>) -> Option<Guild> { cache.as_ref().guild(self.guild_id?).await } /// Returns a field to the `Guild` for the message if one is in the cache. /// The field can be selected via the `field_accessor`. /// /// Returns `None` if the guild's ID could not be found via [`guild_id`] or /// if the Guild itself is not cached. /// /// Requires the `cache` feature be enabled. /// /// [`guild_id`]: Self::guild_id #[cfg(feature = "cache")] pub async fn guild_field<Ret, Fun>( &self, cache: impl AsRef<Cache>, field_accessor: Fun, ) -> Option<Ret> where Ret: Clone, Fun: FnOnce(&Guild) -> Ret, { cache.as_ref().guild_field(self.guild_id?, field_accessor).await } /// True if message was sent using direct messages. #[inline] pub fn is_private(&self) -> bool { self.guild_id.is_none() } /// Retrieves a clone of the author's Member instance, if this message was /// sent in a guild. /// /// If the instance cannot be found in the cache, or the `cache` feature is /// disabled, a HTTP request is performed to retrieve it from Discord's API. /// /// # Errors /// /// [`ModelError::ItemMissing`] is returned if [`guild_id`] is `None`. /// /// [`guild_id`]: Self::guild_id pub async fn member(&self, cache_http: impl CacheHttp) -> Result<Member> { let guild_id = match self.guild_id { Some(guild_id) => guild_id, None => return Err(Error::Model(ModelError::ItemMissing)), }; #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if let Some(member) = cache.member(guild_id, self.author.id).await { return Ok(member); } } } cache_http.http().get_member(guild_id.0, self.author.id.0).await } /// Checks the length of a string to ensure that it is within Discord's /// maximum message length limit. /// /// Returns `None` if the message is within the limit, otherwise returns /// `Some` with an inner value of how many unicode code points the message /// is over. pub fn overflow_length(content: &str) -> Option<usize> { // Check if the content is over the maximum number of unicode code // points. let count = content.chars().count(); if count > constants::MESSAGE_CODE_LIMIT { Some(count - constants::MESSAGE_CODE_LIMIT) } else { None } } /// Pins this message to its channel. /// /// **Note**: Requires the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES pub async fn pin(&self, cache_http: impl CacheHttp) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.guild_id.is_some() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; } } } self.channel_id.pin(cache_http.http(), self.id.0).await } /// React to the message with a custom [`Emoji`] or unicode character. /// /// **Note**: Requires the [Add Reactions] permission. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have the /// required [permissions]. /// /// [Add Reactions]: Permissions::ADD_REACTIONS /// [permissions]: super::permissions #[inline] pub async fn react( &self, cache_http: impl CacheHttp, reaction_type: impl Into<ReactionType>, ) -> Result<Reaction> { self._react(cache_http, &reaction_type.into()).await } async fn _react( &self, cache_http: impl CacheHttp, reaction_type: &ReactionType, ) -> Result<Reaction> { #[allow(unused_mut)] let mut user_id = None; #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.guild_id.is_some() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::ADD_REACTIONS, ) .await?; } user_id = Some(cache.current_user().await.id); } } cache_http.http().create_reaction(self.channel_id.0, self.id.0, reaction_type).await?; Ok(Reaction { channel_id: self.channel_id, emoji: reaction_type.clone(), message_id: self.id, user_id, guild_id: self.guild_id, }) } /// Uses Discord's inline reply to a user without pinging them. /// /// User mentions are generally around 20 or 21 characters long. /// /// **Note**: Requires the [Send Messages] permission. /// /// **Note**: Message contents must be under 2000 unicode code points. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// 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. /// /// [Send Messages]: Permissions::SEND_MESSAGES #[inline] pub async fn reply( &self, cache_http: impl CacheHttp, content: impl Display, ) -> Result<Message> { self._reply(cache_http, content, Some(false)).await } /// Uses Discord's inline reply to a user with a ping. /// /// **Note**: Requires the [Send Messages] permission. /// /// **Note**: Message contents must be under 2000 unicode code points. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// 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. /// /// [Send Messages]: Permissions::SEND_MESSAGES #[inline] pub async fn reply_ping( &self, cache_http: impl CacheHttp, content: impl Display, ) -> Result<Message> { self._reply(cache_http, content, Some(true)).await } /// Replies to the user, mentioning them prior to the content in the form /// of: `@<USER_ID> YOUR_CONTENT`. /// /// User mentions are generally around 20 or 21 characters long. /// /// **Note**: Requires the [Send Messages] permission. /// /// **Note**: Message contents must be under 2000 unicode code points. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// 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. /// /// [Send Messages]: Permissions::SEND_MESSAGES #[inline] pub async fn reply_mention( &self, cache_http: impl CacheHttp, content: impl Display, ) -> Result<Message> { self._reply(cache_http, format!("{} {}", self.author.mention(), content), None).await } /// `inlined` decides whether this reply is inlinded and whether it pings. async fn _reply( &self, cache_http: impl CacheHttp, content: impl Display, inlined: Option<bool>, ) -> Result<Message> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.guild_id.is_some() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::SEND_MESSAGES, ) .await?; } } } self.channel_id .send_message(cache_http.http(), |mut builder| { if let Some(ping_user) = inlined { builder = builder .reference_message(self) .allowed_mentions(|f| f.replied_user(ping_user)); } builder.content(content) }) .await } /// Delete all embeds in this message /// **Note**: The logged in user must either be the author of the message or /// have the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` feature is enabled, then returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// Otherwise returns [`Error::Http`] if the current user lacks permission. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES #[cfg(feature = "utils")] pub async fn suppress_embeds(&mut self, cache_http: impl CacheHttp) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; if self.author.id != cache.current_user_id().await { return Err(Error::Model(ModelError::NotAuthor)); } } } let mut suppress = EditMessage::default(); suppress.suppress_embeds(true); let map = crate::utils::hashmap_to_json_map(suppress.0); *self = cache_http .http() .edit_message(self.channel_id.0, self.id.0, &Value::Object(map)) .await?; Ok(()) } /// Checks whether the message mentions passed [`UserId`]. #[inline] pub fn mentions_user_id(&self, id: impl Into<UserId>) -> bool { let id = id.into(); self.mentions.iter().any(|mentioned_user| mentioned_user.id.0 == id.0) } /// Checks whether the message mentions passed [`User`]. #[inline] pub fn mentions_user(&self, user: &User) -> bool { self.mentions_user_id(user.id) } /// Checks whether the message mentions the current user. /// /// # Errors /// /// May return [`Error::Http`] if the `cache` feature is not enabled, /// or if the cache is otherwise unavailable. pub async fn mentions_me(&self, cache_http: impl CacheHttp) -> Result<bool> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { return Ok(self.mentions_user_id(cache.user.read().await.id)); } } let current_user = cache_http.http().get_current_user().await?; Ok(self.mentions_user_id(current_user.id)) } /// Unpins the message from its channel. /// /// **Note**: Requires the [Manage Messages] permission. /// /// # Errors /// /// If the `cache` is enabled, returns a /// [`ModelError::InvalidPermissions`] if the current user does not have /// the required permissions. /// /// [Manage Messages]: Permissions::MANAGE_MESSAGES pub async fn unpin(&self, cache_http: impl CacheHttp) -> Result<()> { #[cfg(feature = "cache")] { if let Some(cache) = cache_http.cache() { if self.guild_id.is_some() { utils::user_has_perms_cache( cache, self.channel_id, self.guild_id, Permissions::MANAGE_MESSAGES, ) .await?; } } } cache_http.http().unpin_message(self.channel_id.0, self.id.0).await } /// Tries to return author's nickname in the current channel's guild. /// /// Refer to [`User::nick_in()`] inside and `None` outside of a guild. #[inline] pub async fn author_nick(&self, cache_http: impl CacheHttp) -> Option<String> { self.author.nick_in(cache_http, self.guild_id?).await } /// Returns a link referencing this message. When clicked, users will jump to the message. /// The link will be valid for messages in either private channels or guilds. #[inline] pub fn link(&self) -> String { match self.guild_id { Some(guild_id) => format!( "https://discord.com/channels/{}/{}/{}", guild_id.0, self.channel_id.0, self.id.0 ), None => format!("https://discord.com/channels/@me/{}/{}", self.channel_id.0, self.id.0), } } /// Await a single reaction on this message. #[cfg(feature = "collector")] #[cfg_attr(docsrs, doc(cfg(feature = "collector")))] pub fn await_reaction<'a>( &self, shard_messenger: &'a impl AsRef<ShardMessenger>, ) -> CollectReaction<'a> { CollectReaction::new(shard_messenger).message_id(self.id.0) } /// Returns a stream builder which can be awaited to obtain a stream of reactions on this message. #[cfg(feature = "collector")] #[cfg_attr(docsrs, doc(cfg(feature = "collector")))] pub fn await_reactions<'a>( &self, shard_messenger: &'a impl AsRef<ShardMessenger>, ) -> ReactionCollectorBuilder<'a> { ReactionCollectorBuilder::new(shard_messenger).message_id(self.id.0) } /// Retrieves the message channel's category ID if the channel has one. #[cfg(feature = "cache")] pub async fn category_id(&self, cache: impl AsRef<Cache>) -> Option<ChannelId> { cache.as_ref().channel_category_id(self.channel_id).await } pub(crate) fn check_content_length(map: &JsonMap) -> Result<()> { if let Some(content) = map.get("content") { if let Value::String(ref content) = *content { if let Some(length_over) = Message::overflow_length(content) { return Err(Error::Model(ModelError::MessageTooLong(length_over))); } } } Ok(()) } pub(crate) fn check_embed_length(map: &JsonMap) -> Result<()> { let embed = match map.get("embed") { Some(&Value::Object(ref value)) => value, _ => return Ok(()), }; let mut total: usize = 0; if let Some(&Value::Object(ref author)) = embed.get("author") { if let Some(&Value::Object(ref name)) = author.get("name") { total += name.len(); } } if let Some(&Value::String(ref description)) = embed.get("description") { total += description.len(); } if let Some(&Value::Array(ref fields)) = embed.get("fields") { for field_as_value in fields { if let Value::Object(ref field) = *field_as_value { if let Some(&Value::String(ref field_name)) = field.get("name") { total += field_name.len(); } if let Some(&Value::String(ref field_value)) = field.get("value") { total += field_value.len(); } } } } if let Some(&Value::Object(ref footer)) = embed.get("footer") { if let Some(&Value::String(ref text)) = footer.get("text") { total += text.len(); } } if let Some(&Value::String(ref title)) = embed.get("title") { total += title.len(); } if total <= constants::EMBED_MAX_LENGTH { Ok(()) } else { let overflow = total - constants::EMBED_MAX_LENGTH; Err(Error::Model(ModelError::EmbedTooLarge(overflow))) } } } impl AsRef<MessageId> for Message { fn as_ref(&self) -> &MessageId { &self.id } } impl From<Message> for MessageId { /// Gets the Id of a `Message`. fn from(message: Message) -> MessageId { message.id } } impl<'a> From<&'a Message> for MessageId { /// Gets the Id of a `Message`. fn from(message: &Message) -> MessageId { message.id } } /// A representation of a reaction to a message. /// /// Multiple of the same [reaction type] are sent into one `MessageReaction`, /// with an associated [`count`]. /// /// [`count`]: Self::count /// [reaction type]: ReactionType #[derive(Clone, Debug, Deserialize, Serialize)] #[non_exhaustive] pub struct MessageReaction { /// The amount of the type of reaction that have been sent for the /// associated message. pub count: u64, /// Indicator of whether the current user has sent the type of reaction. pub me: bool, /// The type of reaction. #[serde(rename = "emoji")] pub reaction_type: ReactionType, } /// Differentiates between regular and different types of system messages. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] #[non_exhaustive] pub enum MessageType { /// A regular message. Regular = 0, /// An indicator that a recipient was added by the author. GroupRecipientAddition = 1, /// An indicator that a recipient was removed by the author. GroupRecipientRemoval = 2, /// An indicator that a call was started by the author. GroupCallCreation = 3, /// An indicator that the group name was modified by the author. GroupNameUpdate = 4, /// An indicator that the group icon was modified by the author. GroupIconUpdate = 5, /// An indicator that a message was pinned by the author. PinsAdd = 6, /// An indicator that a member joined the guild. MemberJoin = 7, /// An indicator that someone has boosted the guild. NitroBoost = 8, /// An indicator that the guild has reached nitro tier 1 NitroTier1 = 9, /// An indicator that the guild has reached nitro tier 2 NitroTier2 = 10, /// An indicator that the guild has reached nitro tier 3 NitroTier3 = 11, /// An indicator that the channel is now following an announcement channel ChannelFollowAdd = 12, /// An indicator that the guild is disqualified for Discovery Feature GuildDiscoveryDisqualified = 14, /// An indicator that the guild is requalified for Discovery Feature GuildDiscoveryRequalified = 15, /// A message reply. InlineReply = 19, /// A slash command ApplicationCommand = 20, } enum_number!(MessageType { Regular, GroupRecipientAddition, GroupRecipientRemoval, GroupCallCreation, GroupNameUpdate, GroupIconUpdate, PinsAdd, MemberJoin, NitroBoost, NitroTier1, NitroTier2, NitroTier3, ChannelFollowAdd, GuildDiscoveryDisqualified, GuildDiscoveryRequalified, InlineReply, ApplicationCommand, }); impl MessageType { pub fn num(self) -> u64 { use self::MessageType::*; match self { Regular => 0, GroupRecipientAddition => 1, GroupRecipientRemoval => 2, GroupCallCreation => 3, GroupNameUpdate => 4, GroupIconUpdate => 5, PinsAdd => 6, MemberJoin => 7, NitroBoost => 8, NitroTier1 => 9, NitroTier2 => 10, NitroTier3 => 11, ChannelFollowAdd => 12, GuildDiscoveryDisqualified => 14, GuildDiscoveryRequalified => 15, InlineReply => 19, ApplicationCommand => 20, } } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] #[non_exhaustive] pub enum MessageActivityKind { JOIN = 1, SPECTATE = 2, LISTEN = 3, #[allow(non_camel_case_types)] JOIN_REQUEST = 5, } enum_number!(MessageActivityKind { JOIN, SPECTATE, LISTEN, JOIN_REQUEST }); impl MessageActivityKind { pub fn num(self) -> u64 { use self::MessageActivityKind::*; match self { JOIN => 1, SPECTATE => 2, LISTEN => 3, JOIN_REQUEST => 5, } } } /// Rich Presence application information. #[derive(Clone, Debug, Deserialize, Serialize)] #[non_exhaustive] pub struct MessageApplication { /// ID of the application. pub id: ApplicationId, /// ID of the embed's image asset. pub cover_image: Option<String>, /// Application's description. pub description: String, /// ID of the application's icon. pub icon: Option<String>, /// Name of the application. pub name: String, } /// Rich Presence activity information. #[derive(Clone, Debug, Deserialize, Serialize)] #[non_exhaustive] pub struct MessageActivity { /// Kind of message activity. #[serde(rename = "type")] pub kind: MessageActivityKind, /// `party_id` from a Rich Presence event. pub party_id: Option<String>, } /// Reference data sent with crossposted messages. #[derive(Clone, Debug, Deserialize, Serialize)] #[non_exhaustive] pub struct MessageReference { /// ID of the originating message. pub message_id: Option<MessageId>, /// ID of the originating message's channel. pub channel_id: ChannelId, /// ID of the originating message's guild. pub guild_id: Option<GuildId>, } impl From<&Message> for MessageReference { fn from(m: &Message) -> Self { Self { message_id: Some(m.id), channel_id: m.channel_id, guild_id: m.guild_id, } } } impl From<(ChannelId, MessageId)> for MessageReference { fn from(pair: (ChannelId, MessageId)) -> Self { Self { message_id: Some(pair.1), channel_id: pair.0, guild_id: None, } } } /// Channel Mention Object #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ChannelMention { /// ID of the channel. pub id: ChannelId, /// ID of the guild containing the channel. pub guild_id: GuildId, /// The kind of channel #[serde(rename = "type")] pub kind: ChannelType, /// The name of the channel pub name: String, } /// Describes extra features of the message. #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] #[cfg_attr(not(feature = "model"), derive(Debug, Deserialize, Serialize))] pub struct MessageFlags { pub bits: u64, } #[cfg(feature = "model")] __impl_bitflags! { MessageFlags: u64 { /// This message has been published to subscribed channels (via Channel Following). CROSSPOSTED = 0b0000_0000_0000_0000_0000_0000_0000_0001; /// This message originated from a message in another channel (via Channel Following). IS_CROSSPOST = 0b0000_0000_0000_0000_0000_0000_0000_0010; /// Do not include any embeds when serializing this message. SUPPRESS_EMBEDS = 0b0000_0000_0000_0000_0000_0000_0000_0100; } } #[cfg(feature = "model")] impl<'de> Deserialize<'de> for MessageFlags { fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error> where D: Deserializer<'de>, { Ok(MessageFlags::from_bits_truncate(deserializer.deserialize_u64(U64Visitor)?)) } } #[cfg(feature = "model")] impl Serialize for MessageFlags { fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u64(self.bits()) } }