message.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 messages
  95. MessageReference *MessageReference `json:"message_reference"`
  96. // The flags of the message, which describe extra features of a message.
  97. // This is a combination of bit masks; the presence of a certain permission can
  98. // be checked by performing a bitwise AND between this int and the flag.
  99. Flags MessageFlags `json:"flags"`
  100. }
  101. // UnmarshalJSON is a helper function to unmarshal the Message.
  102. func (m *Message) UnmarshalJSON(data []byte) error {
  103. type message Message
  104. var v struct {
  105. message
  106. RawComponents []unmarshalableMessageComponent `json:"components"`
  107. }
  108. err := json.Unmarshal(data, &v)
  109. if err != nil {
  110. return err
  111. }
  112. *m = Message(v.message)
  113. m.Components = make([]MessageComponent, len(v.RawComponents))
  114. for i, v := range v.RawComponents {
  115. m.Components[i] = v.MessageComponent
  116. }
  117. return err
  118. }
  119. // GetCustomEmojis pulls out all the custom (Non-unicode) emojis from a message and returns a Slice of the Emoji struct.
  120. func (m *Message) GetCustomEmojis() []*Emoji {
  121. var toReturn []*Emoji
  122. emojis := EmojiRegex.FindAllString(m.Content, -1)
  123. if len(emojis) < 1 {
  124. return toReturn
  125. }
  126. for _, em := range emojis {
  127. parts := strings.Split(em, ":")
  128. toReturn = append(toReturn, &Emoji{
  129. ID: parts[2][:len(parts[2])-1],
  130. Name: parts[1],
  131. Animated: strings.HasPrefix(em, "<a:"),
  132. })
  133. }
  134. return toReturn
  135. }
  136. // MessageFlags is the flags of "message" (see MessageFlags* consts)
  137. // https://discord.com/developers/docs/resources/channel#message-object-message-flags
  138. type MessageFlags int
  139. // Valid MessageFlags values
  140. const (
  141. MessageFlagsCrossPosted MessageFlags = 1 << 0
  142. MessageFlagsIsCrossPosted MessageFlags = 1 << 1
  143. MessageFlagsSupressEmbeds MessageFlags = 1 << 2
  144. MessageFlagsSourceMessageDeleted MessageFlags = 1 << 3
  145. MessageFlagsUrgent MessageFlags = 1 << 4
  146. )
  147. // File stores info about files you e.g. send in messages.
  148. type File struct {
  149. Name string
  150. ContentType string
  151. Reader io.Reader
  152. }
  153. // MessageSend stores all parameters you can send with ChannelMessageSendComplex.
  154. type MessageSend struct {
  155. Content string `json:"content,omitempty"`
  156. Embed *MessageEmbed `json:"embed,omitempty"`
  157. TTS bool `json:"tts"`
  158. Components []MessageComponent `json:"components"`
  159. Files []*File `json:"-"`
  160. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  161. Reference *MessageReference `json:"message_reference,omitempty"`
  162. // TODO: Remove this when compatibility is not required.
  163. File *File `json:"-"`
  164. }
  165. // MessageEdit is used to chain parameters via ChannelMessageEditComplex, which
  166. // is also where you should get the instance from.
  167. type MessageEdit struct {
  168. Content *string `json:"content,omitempty"`
  169. Components []MessageComponent `json:"components"`
  170. Embed *MessageEmbed `json:"embed,omitempty"`
  171. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  172. ID string
  173. Channel string
  174. }
  175. // NewMessageEdit returns a MessageEdit struct, initialized
  176. // with the Channel and ID.
  177. func NewMessageEdit(channelID string, messageID string) *MessageEdit {
  178. return &MessageEdit{
  179. Channel: channelID,
  180. ID: messageID,
  181. }
  182. }
  183. // SetContent is the same as setting the variable Content,
  184. // except it doesn't take a pointer.
  185. func (m *MessageEdit) SetContent(str string) *MessageEdit {
  186. m.Content = &str
  187. return m
  188. }
  189. // SetEmbed is a convenience function for setting the embed,
  190. // so you can chain commands.
  191. func (m *MessageEdit) SetEmbed(embed *MessageEmbed) *MessageEdit {
  192. m.Embed = embed
  193. return m
  194. }
  195. // AllowedMentionType describes the types of mentions used
  196. // in the MessageAllowedMentions type.
  197. type AllowedMentionType string
  198. // The types of mentions used in MessageAllowedMentions.
  199. const (
  200. AllowedMentionTypeRoles AllowedMentionType = "roles"
  201. AllowedMentionTypeUsers AllowedMentionType = "users"
  202. AllowedMentionTypeEveryone AllowedMentionType = "everyone"
  203. )
  204. // MessageAllowedMentions allows the user to specify which mentions
  205. // Discord is allowed to parse in this message. This is useful when
  206. // sending user input as a message, as it prevents unwanted mentions.
  207. // If this type is used, all mentions must be explicitly whitelisted,
  208. // either by putting an AllowedMentionType in the Parse slice
  209. // (allowing all mentions of that type) or, in the case of roles and
  210. // users, explicitly allowing those mentions on an ID-by-ID basis.
  211. // For more information on this functionality, see:
  212. // https://discordapp.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mentions-reference
  213. type MessageAllowedMentions struct {
  214. // The mention types that are allowed to be parsed in this message.
  215. // Please note that this is purposely **not** marked as omitempty,
  216. // so if a zero-value MessageAllowedMentions object is provided no
  217. // mentions will be allowed.
  218. Parse []AllowedMentionType `json:"parse"`
  219. // A list of role IDs to allow. This cannot be used when specifying
  220. // AllowedMentionTypeRoles in the Parse slice.
  221. Roles []string `json:"roles,omitempty"`
  222. // A list of user IDs to allow. This cannot be used when specifying
  223. // AllowedMentionTypeUsers in the Parse slice.
  224. Users []string `json:"users,omitempty"`
  225. }
  226. // A MessageAttachment stores data for message attachments.
  227. type MessageAttachment struct {
  228. ID string `json:"id"`
  229. URL string `json:"url"`
  230. ProxyURL string `json:"proxy_url"`
  231. Filename string `json:"filename"`
  232. Width int `json:"width"`
  233. Height int `json:"height"`
  234. Size int `json:"size"`
  235. }
  236. // MessageEmbedFooter is a part of a MessageEmbed struct.
  237. type MessageEmbedFooter struct {
  238. Text string `json:"text,omitempty"`
  239. IconURL string `json:"icon_url,omitempty"`
  240. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  241. }
  242. // MessageEmbedImage is a part of a MessageEmbed struct.
  243. type MessageEmbedImage struct {
  244. URL string `json:"url,omitempty"`
  245. ProxyURL string `json:"proxy_url,omitempty"`
  246. Width int `json:"width,omitempty"`
  247. Height int `json:"height,omitempty"`
  248. }
  249. // MessageEmbedThumbnail is a part of a MessageEmbed struct.
  250. type MessageEmbedThumbnail struct {
  251. URL string `json:"url,omitempty"`
  252. ProxyURL string `json:"proxy_url,omitempty"`
  253. Width int `json:"width,omitempty"`
  254. Height int `json:"height,omitempty"`
  255. }
  256. // MessageEmbedVideo is a part of a MessageEmbed struct.
  257. type MessageEmbedVideo struct {
  258. URL string `json:"url,omitempty"`
  259. Width int `json:"width,omitempty"`
  260. Height int `json:"height,omitempty"`
  261. }
  262. // MessageEmbedProvider is a part of a MessageEmbed struct.
  263. type MessageEmbedProvider struct {
  264. URL string `json:"url,omitempty"`
  265. Name string `json:"name,omitempty"`
  266. }
  267. // MessageEmbedAuthor is a part of a MessageEmbed struct.
  268. type MessageEmbedAuthor struct {
  269. URL string `json:"url,omitempty"`
  270. Name string `json:"name,omitempty"`
  271. IconURL string `json:"icon_url,omitempty"`
  272. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  273. }
  274. // MessageEmbedField is a part of a MessageEmbed struct.
  275. type MessageEmbedField struct {
  276. Name string `json:"name,omitempty"`
  277. Value string `json:"value,omitempty"`
  278. Inline bool `json:"inline,omitempty"`
  279. }
  280. // An MessageEmbed stores data for message embeds.
  281. type MessageEmbed struct {
  282. URL string `json:"url,omitempty"`
  283. Type EmbedType `json:"type,omitempty"`
  284. Title string `json:"title,omitempty"`
  285. Description string `json:"description,omitempty"`
  286. Timestamp string `json:"timestamp,omitempty"`
  287. Color int `json:"color,omitempty"`
  288. Footer *MessageEmbedFooter `json:"footer,omitempty"`
  289. Image *MessageEmbedImage `json:"image,omitempty"`
  290. Thumbnail *MessageEmbedThumbnail `json:"thumbnail,omitempty"`
  291. Video *MessageEmbedVideo `json:"video,omitempty"`
  292. Provider *MessageEmbedProvider `json:"provider,omitempty"`
  293. Author *MessageEmbedAuthor `json:"author,omitempty"`
  294. Fields []*MessageEmbedField `json:"fields,omitempty"`
  295. }
  296. // EmbedType is the type of embed
  297. // https://discord.com/developers/docs/resources/channel#embed-object-embed-types
  298. type EmbedType string
  299. // Block of valid EmbedTypes
  300. const (
  301. EmbedTypeRich EmbedType = "rich"
  302. EmbedTypeImage EmbedType = "image"
  303. EmbedTypeVideo EmbedType = "video"
  304. EmbedTypeGifv EmbedType = "gifv"
  305. EmbedTypeArticle EmbedType = "article"
  306. EmbedTypeLink EmbedType = "link"
  307. )
  308. // MessageReactions holds a reactions object for a message.
  309. type MessageReactions struct {
  310. Count int `json:"count"`
  311. Me bool `json:"me"`
  312. Emoji *Emoji `json:"emoji"`
  313. }
  314. // MessageActivity is sent with Rich Presence-related chat embeds
  315. type MessageActivity struct {
  316. Type MessageActivityType `json:"type"`
  317. PartyID string `json:"party_id"`
  318. }
  319. // MessageActivityType is the type of message activity
  320. type MessageActivityType int
  321. // Constants for the different types of Message Activity
  322. const (
  323. MessageActivityTypeJoin MessageActivityType = 1
  324. MessageActivityTypeSpectate MessageActivityType = 2
  325. MessageActivityTypeListen MessageActivityType = 3
  326. MessageActivityTypeJoinRequest MessageActivityType = 5
  327. )
  328. // MessageApplication is sent with Rich Presence-related chat embeds
  329. type MessageApplication struct {
  330. ID string `json:"id"`
  331. CoverImage string `json:"cover_image"`
  332. Description string `json:"description"`
  333. Icon string `json:"icon"`
  334. Name string `json:"name"`
  335. }
  336. // MessageReference contains reference data sent with crossposted messages
  337. type MessageReference struct {
  338. MessageID string `json:"message_id"`
  339. ChannelID string `json:"channel_id"`
  340. GuildID string `json:"guild_id,omitempty"`
  341. }
  342. // Reference returns MessageReference of given message
  343. func (m *Message) Reference() *MessageReference {
  344. return &MessageReference{
  345. GuildID: m.GuildID,
  346. ChannelID: m.ChannelID,
  347. MessageID: m.ID,
  348. }
  349. }
  350. // ContentWithMentionsReplaced will replace all @<id> mentions with the
  351. // username of the mention.
  352. func (m *Message) ContentWithMentionsReplaced() (content string) {
  353. content = m.Content
  354. for _, user := range m.Mentions {
  355. content = strings.NewReplacer(
  356. "<@"+user.ID+">", "@"+user.Username,
  357. "<@!"+user.ID+">", "@"+user.Username,
  358. ).Replace(content)
  359. }
  360. return
  361. }
  362. var patternChannels = regexp.MustCompile("<#[^>]*>")
  363. // ContentWithMoreMentionsReplaced will replace all @<id> mentions with the
  364. // username of the mention, but also role IDs and more.
  365. func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) {
  366. content = m.Content
  367. if !s.StateEnabled {
  368. content = m.ContentWithMentionsReplaced()
  369. return
  370. }
  371. channel, err := s.State.Channel(m.ChannelID)
  372. if err != nil {
  373. content = m.ContentWithMentionsReplaced()
  374. return
  375. }
  376. for _, user := range m.Mentions {
  377. nick := user.Username
  378. member, err := s.State.Member(channel.GuildID, user.ID)
  379. if err == nil && member.Nick != "" {
  380. nick = member.Nick
  381. }
  382. content = strings.NewReplacer(
  383. "<@"+user.ID+">", "@"+user.Username,
  384. "<@!"+user.ID+">", "@"+nick,
  385. ).Replace(content)
  386. }
  387. for _, roleID := range m.MentionRoles {
  388. role, err := s.State.Role(channel.GuildID, roleID)
  389. if err != nil || !role.Mentionable {
  390. continue
  391. }
  392. content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1)
  393. }
  394. content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string {
  395. channel, err := s.State.Channel(mention[2 : len(mention)-1])
  396. if err != nil || channel.Type == ChannelTypeGuildVoice {
  397. return mention
  398. }
  399. return "#" + channel.Name
  400. })
  401. return
  402. }