message.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains code related to the Message struct
  7. package discordgo
  8. import (
  9. "encoding/json"
  10. "io"
  11. "regexp"
  12. "strings"
  13. "time"
  14. )
  15. // MessageType is the type of Message
  16. // https://discord.com/developers/docs/resources/channel#message-object-message-types
  17. type MessageType int
  18. // Block contains the valid known MessageType values
  19. const (
  20. MessageTypeDefault MessageType = 0
  21. MessageTypeRecipientAdd MessageType = 1
  22. MessageTypeRecipientRemove MessageType = 2
  23. MessageTypeCall MessageType = 3
  24. MessageTypeChannelNameChange MessageType = 4
  25. MessageTypeChannelIconChange MessageType = 5
  26. MessageTypeChannelPinnedMessage MessageType = 6
  27. MessageTypeGuildMemberJoin MessageType = 7
  28. MessageTypeUserPremiumGuildSubscription MessageType = 8
  29. MessageTypeUserPremiumGuildSubscriptionTierOne MessageType = 9
  30. MessageTypeUserPremiumGuildSubscriptionTierTwo MessageType = 10
  31. MessageTypeUserPremiumGuildSubscriptionTierThree MessageType = 11
  32. MessageTypeChannelFollowAdd MessageType = 12
  33. MessageTypeGuildDiscoveryDisqualified MessageType = 14
  34. MessageTypeGuildDiscoveryRequalified MessageType = 15
  35. MessageTypeThreadCreated MessageType = 18
  36. MessageTypeReply MessageType = 19
  37. MessageTypeChatInputCommand MessageType = 20
  38. MessageTypeThreadStarterMessage MessageType = 21
  39. MessageTypeContextMenuCommand MessageType = 23
  40. )
  41. // A Message stores all data related to a specific Discord message.
  42. type Message struct {
  43. // The ID of the message.
  44. ID string `json:"id"`
  45. // The ID of the channel in which the message was sent.
  46. ChannelID string `json:"channel_id"`
  47. // The ID of the guild in which the message was sent.
  48. GuildID string `json:"guild_id,omitempty"`
  49. // The content of the message.
  50. Content string `json:"content"`
  51. // The time at which the messsage was sent.
  52. // CAUTION: this field may be removed in a
  53. // future API version; it is safer to calculate
  54. // the creation time via the ID.
  55. Timestamp time.Time `json:"timestamp"`
  56. // The time at which the last edit of the message
  57. // occurred, if it has been edited.
  58. EditedTimestamp *time.Time `json:"edited_timestamp"`
  59. // The roles mentioned in the message.
  60. MentionRoles []string `json:"mention_roles"`
  61. // Whether the message is text-to-speech.
  62. TTS bool `json:"tts"`
  63. // Whether the message mentions everyone.
  64. MentionEveryone bool `json:"mention_everyone"`
  65. // The author of the message. This is not guaranteed to be a
  66. // valid user (webhook-sent messages do not possess a full author).
  67. Author *User `json:"author"`
  68. // A list of attachments present in the message.
  69. Attachments []*MessageAttachment `json:"attachments"`
  70. // A list of components attached to the message.
  71. Components []MessageComponent `json:"-"`
  72. // A list of embeds present in the message.
  73. Embeds []*MessageEmbed `json:"embeds"`
  74. // A list of users mentioned in the message.
  75. Mentions []*User `json:"mentions"`
  76. // A list of reactions to the message.
  77. Reactions []*MessageReactions `json:"reactions"`
  78. // Whether the message is pinned or not.
  79. Pinned bool `json:"pinned"`
  80. // The type of the message.
  81. Type MessageType `json:"type"`
  82. // The webhook ID of the message, if it was generated by a webhook
  83. WebhookID string `json:"webhook_id"`
  84. // Member properties for this message's author,
  85. // contains only partial information
  86. Member *Member `json:"member"`
  87. // Channels specifically mentioned in this message
  88. // Not all channel mentions in a message will appear in mention_channels.
  89. // Only textual channels that are visible to everyone in a lurkable guild will ever be included.
  90. // Only crossposted messages (via Channel Following) currently include mention_channels at all.
  91. // If no mentions in the message meet these requirements, this field will not be sent.
  92. MentionChannels []*Channel `json:"mention_channels"`
  93. // Is sent with Rich Presence-related chat embeds
  94. Activity *MessageActivity `json:"activity"`
  95. // Is sent with Rich Presence-related chat embeds
  96. Application *MessageApplication `json:"application"`
  97. // MessageReference contains reference data sent with crossposted or reply messages.
  98. // This does not contain the reference *to* this message; this is for when *this* message references another.
  99. // To generate a reference to this message, use (*Message).Reference().
  100. MessageReference *MessageReference `json:"message_reference"`
  101. // The message associated with the message_reference
  102. // NOTE: This field is only returned for messages with a type of 19 (REPLY) or 21 (THREAD_STARTER_MESSAGE).
  103. // If the message is a reply but the referenced_message field is not present,
  104. // the backend did not attempt to fetch the message that was being replied to, so its state is unknown.
  105. // If the field exists but is null, the referenced message was deleted.
  106. ReferencedMessage *Message `json:"referenced_message"`
  107. // Is sent when the message is a response to an Interaction, without an existing message.
  108. // This means responses to message component interactions do not include this property,
  109. // instead including a MessageReference, as components exist on preexisting messages.
  110. Interaction *MessageInteraction `json:"interaction"`
  111. // The flags of the message, which describe extra features of a message.
  112. // This is a combination of bit masks; the presence of a certain permission can
  113. // be checked by performing a bitwise AND between this int and the flag.
  114. Flags MessageFlags `json:"flags"`
  115. // The thread that was started from this message, includes thread member object
  116. Thread *Channel `json:"thread,omitempty"`
  117. // An array of Sticker objects, if any were sent.
  118. StickerItems []*Sticker `json:"sticker_items"`
  119. }
  120. // UnmarshalJSON is a helper function to unmarshal the Message.
  121. func (m *Message) UnmarshalJSON(data []byte) error {
  122. type message Message
  123. var v struct {
  124. message
  125. RawComponents []unmarshalableMessageComponent `json:"components"`
  126. }
  127. err := json.Unmarshal(data, &v)
  128. if err != nil {
  129. return err
  130. }
  131. *m = Message(v.message)
  132. m.Components = make([]MessageComponent, len(v.RawComponents))
  133. for i, v := range v.RawComponents {
  134. m.Components[i] = v.MessageComponent
  135. }
  136. return err
  137. }
  138. // GetCustomEmojis pulls out all the custom (Non-unicode) emojis from a message and returns a Slice of the Emoji struct.
  139. func (m *Message) GetCustomEmojis() []*Emoji {
  140. var toReturn []*Emoji
  141. emojis := EmojiRegex.FindAllString(m.Content, -1)
  142. if len(emojis) < 1 {
  143. return toReturn
  144. }
  145. for _, em := range emojis {
  146. parts := strings.Split(em, ":")
  147. toReturn = append(toReturn, &Emoji{
  148. ID: parts[2][:len(parts[2])-1],
  149. Name: parts[1],
  150. Animated: strings.HasPrefix(em, "<a:"),
  151. })
  152. }
  153. return toReturn
  154. }
  155. // MessageFlags is the flags of "message" (see MessageFlags* consts)
  156. // https://discord.com/developers/docs/resources/channel#message-object-message-flags
  157. type MessageFlags int
  158. // Valid MessageFlags values
  159. const (
  160. // MessageFlagsCrossPosted This message has been published to subscribed channels (via Channel Following).
  161. MessageFlagsCrossPosted MessageFlags = 1 << 0
  162. // MessageFlagsIsCrossPosted this message originated from a message in another channel (via Channel Following).
  163. MessageFlagsIsCrossPosted MessageFlags = 1 << 1
  164. // MessageFlagsSupressEmbeds do not include any embeds when serializing this message.
  165. MessageFlagsSupressEmbeds MessageFlags = 1 << 2
  166. // MessageFlagsSourceMessageDeleted the source message for this crosspost has been deleted (via Channel Following).
  167. MessageFlagsSourceMessageDeleted MessageFlags = 1 << 3
  168. // MessageFlagsUrgent this message came from the urgent message system.
  169. MessageFlagsUrgent MessageFlags = 1 << 4
  170. // MessageFlagsHasThread this message has an associated thread, with the same id as the message.
  171. MessageFlagsHasThread MessageFlags = 1 << 5
  172. // MessageFlagsEphemeral this message is only visible to the user who invoked the Interaction.
  173. MessageFlagsEphemeral MessageFlags = 1 << 6
  174. // MessageFlagsLoading this message is an Interaction Response and the bot is "thinking".
  175. MessageFlagsLoading MessageFlags = 1 << 7
  176. // MessageFlagsFailedToMentionSomeRolesInThread this message failed to mention some roles and add their members to the thread.
  177. MessageFlagsFailedToMentionSomeRolesInThread MessageFlags = 1 << 8
  178. )
  179. // File stores info about files you e.g. send in messages.
  180. type File struct {
  181. Name string
  182. ContentType string
  183. Reader io.Reader
  184. }
  185. // MessageSend stores all parameters you can send with ChannelMessageSendComplex.
  186. type MessageSend struct {
  187. Content string `json:"content,omitempty"`
  188. Embeds []*MessageEmbed `json:"embeds"`
  189. TTS bool `json:"tts"`
  190. Components []MessageComponent `json:"components"`
  191. Files []*File `json:"-"`
  192. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  193. Reference *MessageReference `json:"message_reference,omitempty"`
  194. // TODO: Remove this when compatibility is not required.
  195. File *File `json:"-"`
  196. // TODO: Remove this when compatibility is not required.
  197. Embed *MessageEmbed `json:"-"`
  198. }
  199. // MessageEdit is used to chain parameters via ChannelMessageEditComplex, which
  200. // is also where you should get the instance from.
  201. type MessageEdit struct {
  202. Content *string `json:"content,omitempty"`
  203. Components []MessageComponent `json:"components"`
  204. Embeds []*MessageEmbed `json:"embeds"`
  205. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  206. ID string
  207. Channel string
  208. // TODO: Remove this when compatibility is not required.
  209. Embed *MessageEmbed `json:"-"`
  210. }
  211. // NewMessageEdit returns a MessageEdit struct, initialized
  212. // with the Channel and ID.
  213. func NewMessageEdit(channelID string, messageID string) *MessageEdit {
  214. return &MessageEdit{
  215. Channel: channelID,
  216. ID: messageID,
  217. }
  218. }
  219. // SetContent is the same as setting the variable Content,
  220. // except it doesn't take a pointer.
  221. func (m *MessageEdit) SetContent(str string) *MessageEdit {
  222. m.Content = &str
  223. return m
  224. }
  225. // SetEmbed is a convenience function for setting the embed,
  226. // so you can chain commands.
  227. func (m *MessageEdit) SetEmbed(embed *MessageEmbed) *MessageEdit {
  228. m.Embeds = []*MessageEmbed{embed}
  229. return m
  230. }
  231. // SetEmbeds is a convenience function for setting the embeds,
  232. // so you can chain commands.
  233. func (m *MessageEdit) SetEmbeds(embeds []*MessageEmbed) *MessageEdit {
  234. m.Embeds = embeds
  235. return m
  236. }
  237. // AllowedMentionType describes the types of mentions used
  238. // in the MessageAllowedMentions type.
  239. type AllowedMentionType string
  240. // The types of mentions used in MessageAllowedMentions.
  241. const (
  242. AllowedMentionTypeRoles AllowedMentionType = "roles"
  243. AllowedMentionTypeUsers AllowedMentionType = "users"
  244. AllowedMentionTypeEveryone AllowedMentionType = "everyone"
  245. )
  246. // MessageAllowedMentions allows the user to specify which mentions
  247. // Discord is allowed to parse in this message. This is useful when
  248. // sending user input as a message, as it prevents unwanted mentions.
  249. // If this type is used, all mentions must be explicitly whitelisted,
  250. // either by putting an AllowedMentionType in the Parse slice
  251. // (allowing all mentions of that type) or, in the case of roles and
  252. // users, explicitly allowing those mentions on an ID-by-ID basis.
  253. // For more information on this functionality, see:
  254. // https://discordapp.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mentions-reference
  255. type MessageAllowedMentions struct {
  256. // The mention types that are allowed to be parsed in this message.
  257. // Please note that this is purposely **not** marked as omitempty,
  258. // so if a zero-value MessageAllowedMentions object is provided no
  259. // mentions will be allowed.
  260. Parse []AllowedMentionType `json:"parse"`
  261. // A list of role IDs to allow. This cannot be used when specifying
  262. // AllowedMentionTypeRoles in the Parse slice.
  263. Roles []string `json:"roles,omitempty"`
  264. // A list of user IDs to allow. This cannot be used when specifying
  265. // AllowedMentionTypeUsers in the Parse slice.
  266. Users []string `json:"users,omitempty"`
  267. }
  268. // A MessageAttachment stores data for message attachments.
  269. type MessageAttachment struct {
  270. ID string `json:"id"`
  271. URL string `json:"url"`
  272. ProxyURL string `json:"proxy_url"`
  273. Filename string `json:"filename"`
  274. ContentType string `json:"content_type"`
  275. Width int `json:"width"`
  276. Height int `json:"height"`
  277. Size int `json:"size"`
  278. Ephemeral bool `json:"ephemeral"`
  279. }
  280. // MessageEmbedFooter is a part of a MessageEmbed struct.
  281. type MessageEmbedFooter struct {
  282. Text string `json:"text,omitempty"`
  283. IconURL string `json:"icon_url,omitempty"`
  284. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  285. }
  286. // MessageEmbedImage is a part of a MessageEmbed struct.
  287. type MessageEmbedImage struct {
  288. URL string `json:"url,omitempty"`
  289. ProxyURL string `json:"proxy_url,omitempty"`
  290. Width int `json:"width,omitempty"`
  291. Height int `json:"height,omitempty"`
  292. }
  293. // MessageEmbedThumbnail is a part of a MessageEmbed struct.
  294. type MessageEmbedThumbnail struct {
  295. URL string `json:"url,omitempty"`
  296. ProxyURL string `json:"proxy_url,omitempty"`
  297. Width int `json:"width,omitempty"`
  298. Height int `json:"height,omitempty"`
  299. }
  300. // MessageEmbedVideo is a part of a MessageEmbed struct.
  301. type MessageEmbedVideo struct {
  302. URL string `json:"url,omitempty"`
  303. Width int `json:"width,omitempty"`
  304. Height int `json:"height,omitempty"`
  305. }
  306. // MessageEmbedProvider is a part of a MessageEmbed struct.
  307. type MessageEmbedProvider struct {
  308. URL string `json:"url,omitempty"`
  309. Name string `json:"name,omitempty"`
  310. }
  311. // MessageEmbedAuthor is a part of a MessageEmbed struct.
  312. type MessageEmbedAuthor struct {
  313. URL string `json:"url,omitempty"`
  314. Name string `json:"name,omitempty"`
  315. IconURL string `json:"icon_url,omitempty"`
  316. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  317. }
  318. // MessageEmbedField is a part of a MessageEmbed struct.
  319. type MessageEmbedField struct {
  320. Name string `json:"name,omitempty"`
  321. Value string `json:"value,omitempty"`
  322. Inline bool `json:"inline,omitempty"`
  323. }
  324. // An MessageEmbed stores data for message embeds.
  325. type MessageEmbed struct {
  326. URL string `json:"url,omitempty"`
  327. Type EmbedType `json:"type,omitempty"`
  328. Title string `json:"title,omitempty"`
  329. Description string `json:"description,omitempty"`
  330. Timestamp string `json:"timestamp,omitempty"`
  331. Color int `json:"color,omitempty"`
  332. Footer *MessageEmbedFooter `json:"footer,omitempty"`
  333. Image *MessageEmbedImage `json:"image,omitempty"`
  334. Thumbnail *MessageEmbedThumbnail `json:"thumbnail,omitempty"`
  335. Video *MessageEmbedVideo `json:"video,omitempty"`
  336. Provider *MessageEmbedProvider `json:"provider,omitempty"`
  337. Author *MessageEmbedAuthor `json:"author,omitempty"`
  338. Fields []*MessageEmbedField `json:"fields,omitempty"`
  339. }
  340. // EmbedType is the type of embed
  341. // https://discord.com/developers/docs/resources/channel#embed-object-embed-types
  342. type EmbedType string
  343. // Block of valid EmbedTypes
  344. const (
  345. EmbedTypeRich EmbedType = "rich"
  346. EmbedTypeImage EmbedType = "image"
  347. EmbedTypeVideo EmbedType = "video"
  348. EmbedTypeGifv EmbedType = "gifv"
  349. EmbedTypeArticle EmbedType = "article"
  350. EmbedTypeLink EmbedType = "link"
  351. )
  352. // MessageReactions holds a reactions object for a message.
  353. type MessageReactions struct {
  354. Count int `json:"count"`
  355. Me bool `json:"me"`
  356. Emoji *Emoji `json:"emoji"`
  357. }
  358. // MessageActivity is sent with Rich Presence-related chat embeds
  359. type MessageActivity struct {
  360. Type MessageActivityType `json:"type"`
  361. PartyID string `json:"party_id"`
  362. }
  363. // MessageActivityType is the type of message activity
  364. type MessageActivityType int
  365. // Constants for the different types of Message Activity
  366. const (
  367. MessageActivityTypeJoin MessageActivityType = 1
  368. MessageActivityTypeSpectate MessageActivityType = 2
  369. MessageActivityTypeListen MessageActivityType = 3
  370. MessageActivityTypeJoinRequest MessageActivityType = 5
  371. )
  372. // MessageApplication is sent with Rich Presence-related chat embeds
  373. type MessageApplication struct {
  374. ID string `json:"id"`
  375. CoverImage string `json:"cover_image"`
  376. Description string `json:"description"`
  377. Icon string `json:"icon"`
  378. Name string `json:"name"`
  379. }
  380. // MessageReference contains reference data sent with crossposted messages
  381. type MessageReference struct {
  382. MessageID string `json:"message_id"`
  383. ChannelID string `json:"channel_id"`
  384. GuildID string `json:"guild_id,omitempty"`
  385. }
  386. // Reference returns MessageReference of given message
  387. func (m *Message) Reference() *MessageReference {
  388. return &MessageReference{
  389. GuildID: m.GuildID,
  390. ChannelID: m.ChannelID,
  391. MessageID: m.ID,
  392. }
  393. }
  394. // ContentWithMentionsReplaced will replace all @<id> mentions with the
  395. // username of the mention.
  396. func (m *Message) ContentWithMentionsReplaced() (content string) {
  397. content = m.Content
  398. for _, user := range m.Mentions {
  399. content = strings.NewReplacer(
  400. "<@"+user.ID+">", "@"+user.Username,
  401. "<@!"+user.ID+">", "@"+user.Username,
  402. ).Replace(content)
  403. }
  404. return
  405. }
  406. var patternChannels = regexp.MustCompile("<#[^>]*>")
  407. // ContentWithMoreMentionsReplaced will replace all @<id> mentions with the
  408. // username of the mention, but also role IDs and more.
  409. func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) {
  410. content = m.Content
  411. if !s.StateEnabled {
  412. content = m.ContentWithMentionsReplaced()
  413. return
  414. }
  415. channel, err := s.State.Channel(m.ChannelID)
  416. if err != nil {
  417. content = m.ContentWithMentionsReplaced()
  418. return
  419. }
  420. for _, user := range m.Mentions {
  421. nick := user.Username
  422. member, err := s.State.Member(channel.GuildID, user.ID)
  423. if err == nil && member.Nick != "" {
  424. nick = member.Nick
  425. }
  426. content = strings.NewReplacer(
  427. "<@"+user.ID+">", "@"+user.Username,
  428. "<@!"+user.ID+">", "@"+nick,
  429. ).Replace(content)
  430. }
  431. for _, roleID := range m.MentionRoles {
  432. role, err := s.State.Role(channel.GuildID, roleID)
  433. if err != nil || !role.Mentionable {
  434. continue
  435. }
  436. content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1)
  437. }
  438. content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string {
  439. channel, err := s.State.Channel(mention[2 : len(mention)-1])
  440. if err != nil || channel.Type == ChannelTypeGuildVoice {
  441. return mention
  442. }
  443. return "#" + channel.Name
  444. })
  445. return
  446. }
  447. // MessageInteraction contains information about the application command interaction which generated the message.
  448. type MessageInteraction struct {
  449. ID string `json:"id"`
  450. Type InteractionType `json:"type"`
  451. Name string `json:"name"`
  452. User *User `json:"user"`
  453. // Member is only present when the interaction is from a guild.
  454. Member *Member `json:"member"`
  455. }