message.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. // The flags of the message, which describe extra features of a message.
  108. // This is a combination of bit masks; the presence of a certain permission can
  109. // be checked by performing a bitwise AND between this int and the flag.
  110. Flags MessageFlags `json:"flags"`
  111. // The thread that was started from this message, includes thread member object
  112. Thread *Channel `json:"thread,omitempty"`
  113. // An array of Sticker objects, if any were sent.
  114. StickerItems []*Sticker `json:"sticker_items"`
  115. }
  116. // UnmarshalJSON is a helper function to unmarshal the Message.
  117. func (m *Message) UnmarshalJSON(data []byte) error {
  118. type message Message
  119. var v struct {
  120. message
  121. RawComponents []unmarshalableMessageComponent `json:"components"`
  122. }
  123. err := json.Unmarshal(data, &v)
  124. if err != nil {
  125. return err
  126. }
  127. *m = Message(v.message)
  128. m.Components = make([]MessageComponent, len(v.RawComponents))
  129. for i, v := range v.RawComponents {
  130. m.Components[i] = v.MessageComponent
  131. }
  132. return err
  133. }
  134. // GetCustomEmojis pulls out all the custom (Non-unicode) emojis from a message and returns a Slice of the Emoji struct.
  135. func (m *Message) GetCustomEmojis() []*Emoji {
  136. var toReturn []*Emoji
  137. emojis := EmojiRegex.FindAllString(m.Content, -1)
  138. if len(emojis) < 1 {
  139. return toReturn
  140. }
  141. for _, em := range emojis {
  142. parts := strings.Split(em, ":")
  143. toReturn = append(toReturn, &Emoji{
  144. ID: parts[2][:len(parts[2])-1],
  145. Name: parts[1],
  146. Animated: strings.HasPrefix(em, "<a:"),
  147. })
  148. }
  149. return toReturn
  150. }
  151. // MessageFlags is the flags of "message" (see MessageFlags* consts)
  152. // https://discord.com/developers/docs/resources/channel#message-object-message-flags
  153. type MessageFlags int
  154. // Valid MessageFlags values
  155. const (
  156. // MessageFlagsCrossPosted This message has been published to subscribed channels (via Channel Following).
  157. MessageFlagsCrossPosted MessageFlags = 1 << 0
  158. // MessageFlagsIsCrossPosted this message originated from a message in another channel (via Channel Following).
  159. MessageFlagsIsCrossPosted MessageFlags = 1 << 1
  160. // MessageFlagsSupressEmbeds do not include any embeds when serializing this message.
  161. MessageFlagsSupressEmbeds MessageFlags = 1 << 2
  162. // MessageFlagsSourceMessageDeleted the source message for this crosspost has been deleted (via Channel Following).
  163. MessageFlagsSourceMessageDeleted MessageFlags = 1 << 3
  164. // MessageFlagsUrgent this message came from the urgent message system.
  165. MessageFlagsUrgent MessageFlags = 1 << 4
  166. // MessageFlagsHasThread this message has an associated thread, with the same id as the message.
  167. MessageFlagsHasThread MessageFlags = 1 << 5
  168. // MessageFlagsEphemeral this message is only visible to the user who invoked the Interaction.
  169. MessageFlagsEphemeral MessageFlags = 1 << 6
  170. // MessageFlagsLoading this message is an Interaction Response and the bot is "thinking".
  171. MessageFlagsLoading MessageFlags = 1 << 7
  172. // MessageFlagsFailedToMentionSomeRolesInThread this message failed to mention some roles and add their members to the thread.
  173. MessageFlagsFailedToMentionSomeRolesInThread MessageFlags = 1 << 8
  174. )
  175. // File stores info about files you e.g. send in messages.
  176. type File struct {
  177. Name string
  178. ContentType string
  179. Reader io.Reader
  180. }
  181. // StickerFormat is the file format of the Sticker.
  182. type StickerFormat int
  183. // Defines all known Sticker types.
  184. const (
  185. StickerFormatTypePNG StickerFormat = 1
  186. StickerFormatTypeAPNG StickerFormat = 2
  187. StickerFormatTypeLottie StickerFormat = 3
  188. )
  189. // StickerType is the type of sticker.
  190. type StickerType int
  191. // Defines Sticker types.
  192. const (
  193. StickerTypeStandard StickerType = 1
  194. StickerTypeGuild StickerType = 2
  195. )
  196. // Sticker represents a sticker object that can be sent in a Message.
  197. type Sticker struct {
  198. ID string `json:"id"`
  199. PackID string `json:"pack_id"`
  200. Name string `json:"name"`
  201. Description string `json:"description"`
  202. Tags string `json:"tags"`
  203. Type StickerType `json:"type"`
  204. FormatType StickerFormat `json:"format_type"`
  205. Available bool `json:"available"`
  206. GuildID string `json:"guild_id"`
  207. User *User `json:"user"`
  208. SortValue int `json:"sort_value"`
  209. }
  210. // StickerPack represents a pack of standard stickers.
  211. type StickerPack struct {
  212. ID string `json:"id"`
  213. Stickers []Sticker `json:"stickers"`
  214. Name string `json:"name"`
  215. SKUID string `json:"sku_id"`
  216. CoverStickerID string `json:"cover_sticker_id"`
  217. Description string `json:"description"`
  218. BannerAssetID string `json:"banner_asset_id"`
  219. }
  220. // MessageSend stores all parameters you can send with ChannelMessageSendComplex.
  221. type MessageSend struct {
  222. Content string `json:"content,omitempty"`
  223. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  224. TTS bool `json:"tts"`
  225. Components []MessageComponent `json:"components"`
  226. Files []*File `json:"-"`
  227. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  228. Reference *MessageReference `json:"message_reference,omitempty"`
  229. // TODO: Remove this when compatibility is not required.
  230. File *File `json:"-"`
  231. // TODO: Remove this when compatibility is not required.
  232. Embed *MessageEmbed `json:"-"`
  233. }
  234. // MessageEdit is used to chain parameters via ChannelMessageEditComplex, which
  235. // is also where you should get the instance from.
  236. type MessageEdit struct {
  237. Content *string `json:"content,omitempty"`
  238. Components []MessageComponent `json:"components"`
  239. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  240. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  241. ID string
  242. Channel string
  243. // TODO: Remove this when compatibility is not required.
  244. Embed *MessageEmbed `json:"-"`
  245. }
  246. // NewMessageEdit returns a MessageEdit struct, initialized
  247. // with the Channel and ID.
  248. func NewMessageEdit(channelID string, messageID string) *MessageEdit {
  249. return &MessageEdit{
  250. Channel: channelID,
  251. ID: messageID,
  252. }
  253. }
  254. // SetContent is the same as setting the variable Content,
  255. // except it doesn't take a pointer.
  256. func (m *MessageEdit) SetContent(str string) *MessageEdit {
  257. m.Content = &str
  258. return m
  259. }
  260. // SetEmbed is a convenience function for setting the embed,
  261. // so you can chain commands.
  262. func (m *MessageEdit) SetEmbed(embed *MessageEmbed) *MessageEdit {
  263. m.Embeds = []*MessageEmbed{embed}
  264. return m
  265. }
  266. // SetEmbeds is a convenience function for setting the embeds,
  267. // so you can chain commands.
  268. func (m *MessageEdit) SetEmbeds(embeds []*MessageEmbed) *MessageEdit {
  269. m.Embeds = embeds
  270. return m
  271. }
  272. // AllowedMentionType describes the types of mentions used
  273. // in the MessageAllowedMentions type.
  274. type AllowedMentionType string
  275. // The types of mentions used in MessageAllowedMentions.
  276. const (
  277. AllowedMentionTypeRoles AllowedMentionType = "roles"
  278. AllowedMentionTypeUsers AllowedMentionType = "users"
  279. AllowedMentionTypeEveryone AllowedMentionType = "everyone"
  280. )
  281. // MessageAllowedMentions allows the user to specify which mentions
  282. // Discord is allowed to parse in this message. This is useful when
  283. // sending user input as a message, as it prevents unwanted mentions.
  284. // If this type is used, all mentions must be explicitly whitelisted,
  285. // either by putting an AllowedMentionType in the Parse slice
  286. // (allowing all mentions of that type) or, in the case of roles and
  287. // users, explicitly allowing those mentions on an ID-by-ID basis.
  288. // For more information on this functionality, see:
  289. // https://discordapp.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mentions-reference
  290. type MessageAllowedMentions struct {
  291. // The mention types that are allowed to be parsed in this message.
  292. // Please note that this is purposely **not** marked as omitempty,
  293. // so if a zero-value MessageAllowedMentions object is provided no
  294. // mentions will be allowed.
  295. Parse []AllowedMentionType `json:"parse"`
  296. // A list of role IDs to allow. This cannot be used when specifying
  297. // AllowedMentionTypeRoles in the Parse slice.
  298. Roles []string `json:"roles,omitempty"`
  299. // A list of user IDs to allow. This cannot be used when specifying
  300. // AllowedMentionTypeUsers in the Parse slice.
  301. Users []string `json:"users,omitempty"`
  302. }
  303. // A MessageAttachment stores data for message attachments.
  304. type MessageAttachment struct {
  305. ID string `json:"id"`
  306. URL string `json:"url"`
  307. ProxyURL string `json:"proxy_url"`
  308. Filename string `json:"filename"`
  309. Width int `json:"width"`
  310. Height int `json:"height"`
  311. Size int `json:"size"`
  312. Ephemeral bool `json:"ephemeral"`
  313. }
  314. // MessageEmbedFooter is a part of a MessageEmbed struct.
  315. type MessageEmbedFooter struct {
  316. Text string `json:"text,omitempty"`
  317. IconURL string `json:"icon_url,omitempty"`
  318. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  319. }
  320. // MessageEmbedImage is a part of a MessageEmbed struct.
  321. type MessageEmbedImage struct {
  322. URL string `json:"url,omitempty"`
  323. ProxyURL string `json:"proxy_url,omitempty"`
  324. Width int `json:"width,omitempty"`
  325. Height int `json:"height,omitempty"`
  326. }
  327. // MessageEmbedThumbnail is a part of a MessageEmbed struct.
  328. type MessageEmbedThumbnail struct {
  329. URL string `json:"url,omitempty"`
  330. ProxyURL string `json:"proxy_url,omitempty"`
  331. Width int `json:"width,omitempty"`
  332. Height int `json:"height,omitempty"`
  333. }
  334. // MessageEmbedVideo is a part of a MessageEmbed struct.
  335. type MessageEmbedVideo struct {
  336. URL string `json:"url,omitempty"`
  337. Width int `json:"width,omitempty"`
  338. Height int `json:"height,omitempty"`
  339. }
  340. // MessageEmbedProvider is a part of a MessageEmbed struct.
  341. type MessageEmbedProvider struct {
  342. URL string `json:"url,omitempty"`
  343. Name string `json:"name,omitempty"`
  344. }
  345. // MessageEmbedAuthor is a part of a MessageEmbed struct.
  346. type MessageEmbedAuthor struct {
  347. URL string `json:"url,omitempty"`
  348. Name string `json:"name,omitempty"`
  349. IconURL string `json:"icon_url,omitempty"`
  350. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  351. }
  352. // MessageEmbedField is a part of a MessageEmbed struct.
  353. type MessageEmbedField struct {
  354. Name string `json:"name,omitempty"`
  355. Value string `json:"value,omitempty"`
  356. Inline bool `json:"inline,omitempty"`
  357. }
  358. // An MessageEmbed stores data for message embeds.
  359. type MessageEmbed struct {
  360. URL string `json:"url,omitempty"`
  361. Type EmbedType `json:"type,omitempty"`
  362. Title string `json:"title,omitempty"`
  363. Description string `json:"description,omitempty"`
  364. Timestamp string `json:"timestamp,omitempty"`
  365. Color int `json:"color,omitempty"`
  366. Footer *MessageEmbedFooter `json:"footer,omitempty"`
  367. Image *MessageEmbedImage `json:"image,omitempty"`
  368. Thumbnail *MessageEmbedThumbnail `json:"thumbnail,omitempty"`
  369. Video *MessageEmbedVideo `json:"video,omitempty"`
  370. Provider *MessageEmbedProvider `json:"provider,omitempty"`
  371. Author *MessageEmbedAuthor `json:"author,omitempty"`
  372. Fields []*MessageEmbedField `json:"fields,omitempty"`
  373. }
  374. // EmbedType is the type of embed
  375. // https://discord.com/developers/docs/resources/channel#embed-object-embed-types
  376. type EmbedType string
  377. // Block of valid EmbedTypes
  378. const (
  379. EmbedTypeRich EmbedType = "rich"
  380. EmbedTypeImage EmbedType = "image"
  381. EmbedTypeVideo EmbedType = "video"
  382. EmbedTypeGifv EmbedType = "gifv"
  383. EmbedTypeArticle EmbedType = "article"
  384. EmbedTypeLink EmbedType = "link"
  385. )
  386. // MessageReactions holds a reactions object for a message.
  387. type MessageReactions struct {
  388. Count int `json:"count"`
  389. Me bool `json:"me"`
  390. Emoji *Emoji `json:"emoji"`
  391. }
  392. // MessageActivity is sent with Rich Presence-related chat embeds
  393. type MessageActivity struct {
  394. Type MessageActivityType `json:"type"`
  395. PartyID string `json:"party_id"`
  396. }
  397. // MessageActivityType is the type of message activity
  398. type MessageActivityType int
  399. // Constants for the different types of Message Activity
  400. const (
  401. MessageActivityTypeJoin MessageActivityType = 1
  402. MessageActivityTypeSpectate MessageActivityType = 2
  403. MessageActivityTypeListen MessageActivityType = 3
  404. MessageActivityTypeJoinRequest MessageActivityType = 5
  405. )
  406. // MessageApplication is sent with Rich Presence-related chat embeds
  407. type MessageApplication struct {
  408. ID string `json:"id"`
  409. CoverImage string `json:"cover_image"`
  410. Description string `json:"description"`
  411. Icon string `json:"icon"`
  412. Name string `json:"name"`
  413. }
  414. // MessageReference contains reference data sent with crossposted messages
  415. type MessageReference struct {
  416. MessageID string `json:"message_id"`
  417. ChannelID string `json:"channel_id"`
  418. GuildID string `json:"guild_id,omitempty"`
  419. }
  420. // Reference returns MessageReference of given message
  421. func (m *Message) Reference() *MessageReference {
  422. return &MessageReference{
  423. GuildID: m.GuildID,
  424. ChannelID: m.ChannelID,
  425. MessageID: m.ID,
  426. }
  427. }
  428. // ContentWithMentionsReplaced will replace all @<id> mentions with the
  429. // username of the mention.
  430. func (m *Message) ContentWithMentionsReplaced() (content string) {
  431. content = m.Content
  432. for _, user := range m.Mentions {
  433. content = strings.NewReplacer(
  434. "<@"+user.ID+">", "@"+user.Username,
  435. "<@!"+user.ID+">", "@"+user.Username,
  436. ).Replace(content)
  437. }
  438. return
  439. }
  440. var patternChannels = regexp.MustCompile("<#[^>]*>")
  441. // ContentWithMoreMentionsReplaced will replace all @<id> mentions with the
  442. // username of the mention, but also role IDs and more.
  443. func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) {
  444. content = m.Content
  445. if !s.StateEnabled {
  446. content = m.ContentWithMentionsReplaced()
  447. return
  448. }
  449. channel, err := s.State.Channel(m.ChannelID)
  450. if err != nil {
  451. content = m.ContentWithMentionsReplaced()
  452. return
  453. }
  454. for _, user := range m.Mentions {
  455. nick := user.Username
  456. member, err := s.State.Member(channel.GuildID, user.ID)
  457. if err == nil && member.Nick != "" {
  458. nick = member.Nick
  459. }
  460. content = strings.NewReplacer(
  461. "<@"+user.ID+">", "@"+user.Username,
  462. "<@!"+user.ID+">", "@"+nick,
  463. ).Replace(content)
  464. }
  465. for _, roleID := range m.MentionRoles {
  466. role, err := s.State.Role(channel.GuildID, roleID)
  467. if err != nil || !role.Mentionable {
  468. continue
  469. }
  470. content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1)
  471. }
  472. content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string {
  473. channel, err := s.State.Channel(mention[2 : len(mention)-1])
  474. if err != nil || channel.Type == ChannelTypeGuildVoice {
  475. return mention
  476. }
  477. return "#" + channel.Name
  478. })
  479. return
  480. }