message.go 16 KB

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