message.go 16 KB

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