message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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.
  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. Embeds []*MessageEmbed `json:"embeds,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. // TODO: Remove this when compatibility is not required.
  167. Embed *MessageEmbed `json:"-"`
  168. }
  169. // MessageEdit is used to chain parameters via ChannelMessageEditComplex, which
  170. // is also where you should get the instance from.
  171. type MessageEdit struct {
  172. Content *string `json:"content,omitempty"`
  173. Components []MessageComponent `json:"components"`
  174. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  175. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  176. ID string
  177. Channel string
  178. // TODO: Remove this when compatibility is not required.
  179. Embed *MessageEmbed `json:"-"`
  180. }
  181. // NewMessageEdit returns a MessageEdit struct, initialized
  182. // with the Channel and ID.
  183. func NewMessageEdit(channelID string, messageID string) *MessageEdit {
  184. return &MessageEdit{
  185. Channel: channelID,
  186. ID: messageID,
  187. }
  188. }
  189. // SetContent is the same as setting the variable Content,
  190. // except it doesn't take a pointer.
  191. func (m *MessageEdit) SetContent(str string) *MessageEdit {
  192. m.Content = &str
  193. return m
  194. }
  195. // SetEmbed is a convenience function for setting the embed,
  196. // so you can chain commands.
  197. func (m *MessageEdit) SetEmbed(embed *MessageEmbed) *MessageEdit {
  198. m.Embeds = []*MessageEmbed{embed}
  199. return m
  200. }
  201. // SetEmbeds is a convenience function for setting the embeds,
  202. // so you can chain commands.
  203. func (m *MessageEdit) SetEmbeds(embeds []*MessageEmbed) *MessageEdit {
  204. m.Embeds = embeds
  205. return m
  206. }
  207. // AllowedMentionType describes the types of mentions used
  208. // in the MessageAllowedMentions type.
  209. type AllowedMentionType string
  210. // The types of mentions used in MessageAllowedMentions.
  211. const (
  212. AllowedMentionTypeRoles AllowedMentionType = "roles"
  213. AllowedMentionTypeUsers AllowedMentionType = "users"
  214. AllowedMentionTypeEveryone AllowedMentionType = "everyone"
  215. )
  216. // MessageAllowedMentions allows the user to specify which mentions
  217. // Discord is allowed to parse in this message. This is useful when
  218. // sending user input as a message, as it prevents unwanted mentions.
  219. // If this type is used, all mentions must be explicitly whitelisted,
  220. // either by putting an AllowedMentionType in the Parse slice
  221. // (allowing all mentions of that type) or, in the case of roles and
  222. // users, explicitly allowing those mentions on an ID-by-ID basis.
  223. // For more information on this functionality, see:
  224. // https://discordapp.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mentions-reference
  225. type MessageAllowedMentions struct {
  226. // The mention types that are allowed to be parsed in this message.
  227. // Please note that this is purposely **not** marked as omitempty,
  228. // so if a zero-value MessageAllowedMentions object is provided no
  229. // mentions will be allowed.
  230. Parse []AllowedMentionType `json:"parse"`
  231. // A list of role IDs to allow. This cannot be used when specifying
  232. // AllowedMentionTypeRoles in the Parse slice.
  233. Roles []string `json:"roles,omitempty"`
  234. // A list of user IDs to allow. This cannot be used when specifying
  235. // AllowedMentionTypeUsers in the Parse slice.
  236. Users []string `json:"users,omitempty"`
  237. }
  238. // A MessageAttachment stores data for message attachments.
  239. type MessageAttachment struct {
  240. ID string `json:"id"`
  241. URL string `json:"url"`
  242. ProxyURL string `json:"proxy_url"`
  243. Filename string `json:"filename"`
  244. Width int `json:"width"`
  245. Height int `json:"height"`
  246. Size int `json:"size"`
  247. Ephemeral bool `json:"ephemeral"`
  248. }
  249. // MessageEmbedFooter is a part of a MessageEmbed struct.
  250. type MessageEmbedFooter struct {
  251. Text string `json:"text,omitempty"`
  252. IconURL string `json:"icon_url,omitempty"`
  253. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  254. }
  255. // MessageEmbedImage is a part of a MessageEmbed struct.
  256. type MessageEmbedImage struct {
  257. URL string `json:"url,omitempty"`
  258. ProxyURL string `json:"proxy_url,omitempty"`
  259. Width int `json:"width,omitempty"`
  260. Height int `json:"height,omitempty"`
  261. }
  262. // MessageEmbedThumbnail is a part of a MessageEmbed struct.
  263. type MessageEmbedThumbnail struct {
  264. URL string `json:"url,omitempty"`
  265. ProxyURL string `json:"proxy_url,omitempty"`
  266. Width int `json:"width,omitempty"`
  267. Height int `json:"height,omitempty"`
  268. }
  269. // MessageEmbedVideo is a part of a MessageEmbed struct.
  270. type MessageEmbedVideo struct {
  271. URL string `json:"url,omitempty"`
  272. Width int `json:"width,omitempty"`
  273. Height int `json:"height,omitempty"`
  274. }
  275. // MessageEmbedProvider is a part of a MessageEmbed struct.
  276. type MessageEmbedProvider struct {
  277. URL string `json:"url,omitempty"`
  278. Name string `json:"name,omitempty"`
  279. }
  280. // MessageEmbedAuthor is a part of a MessageEmbed struct.
  281. type MessageEmbedAuthor struct {
  282. URL string `json:"url,omitempty"`
  283. Name string `json:"name,omitempty"`
  284. IconURL string `json:"icon_url,omitempty"`
  285. ProxyIconURL string `json:"proxy_icon_url,omitempty"`
  286. }
  287. // MessageEmbedField is a part of a MessageEmbed struct.
  288. type MessageEmbedField struct {
  289. Name string `json:"name,omitempty"`
  290. Value string `json:"value,omitempty"`
  291. Inline bool `json:"inline,omitempty"`
  292. }
  293. // An MessageEmbed stores data for message embeds.
  294. type MessageEmbed struct {
  295. URL string `json:"url,omitempty"`
  296. Type EmbedType `json:"type,omitempty"`
  297. Title string `json:"title,omitempty"`
  298. Description string `json:"description,omitempty"`
  299. Timestamp string `json:"timestamp,omitempty"`
  300. Color int `json:"color,omitempty"`
  301. Footer *MessageEmbedFooter `json:"footer,omitempty"`
  302. Image *MessageEmbedImage `json:"image,omitempty"`
  303. Thumbnail *MessageEmbedThumbnail `json:"thumbnail,omitempty"`
  304. Video *MessageEmbedVideo `json:"video,omitempty"`
  305. Provider *MessageEmbedProvider `json:"provider,omitempty"`
  306. Author *MessageEmbedAuthor `json:"author,omitempty"`
  307. Fields []*MessageEmbedField `json:"fields,omitempty"`
  308. }
  309. // EmbedType is the type of embed
  310. // https://discord.com/developers/docs/resources/channel#embed-object-embed-types
  311. type EmbedType string
  312. // Block of valid EmbedTypes
  313. const (
  314. EmbedTypeRich EmbedType = "rich"
  315. EmbedTypeImage EmbedType = "image"
  316. EmbedTypeVideo EmbedType = "video"
  317. EmbedTypeGifv EmbedType = "gifv"
  318. EmbedTypeArticle EmbedType = "article"
  319. EmbedTypeLink EmbedType = "link"
  320. )
  321. // MessageReactions holds a reactions object for a message.
  322. type MessageReactions struct {
  323. Count int `json:"count"`
  324. Me bool `json:"me"`
  325. Emoji *Emoji `json:"emoji"`
  326. }
  327. // MessageActivity is sent with Rich Presence-related chat embeds
  328. type MessageActivity struct {
  329. Type MessageActivityType `json:"type"`
  330. PartyID string `json:"party_id"`
  331. }
  332. // MessageActivityType is the type of message activity
  333. type MessageActivityType int
  334. // Constants for the different types of Message Activity
  335. const (
  336. MessageActivityTypeJoin MessageActivityType = 1
  337. MessageActivityTypeSpectate MessageActivityType = 2
  338. MessageActivityTypeListen MessageActivityType = 3
  339. MessageActivityTypeJoinRequest MessageActivityType = 5
  340. )
  341. // MessageApplication is sent with Rich Presence-related chat embeds
  342. type MessageApplication struct {
  343. ID string `json:"id"`
  344. CoverImage string `json:"cover_image"`
  345. Description string `json:"description"`
  346. Icon string `json:"icon"`
  347. Name string `json:"name"`
  348. }
  349. // MessageReference contains reference data sent with crossposted messages
  350. type MessageReference struct {
  351. MessageID string `json:"message_id"`
  352. ChannelID string `json:"channel_id"`
  353. GuildID string `json:"guild_id,omitempty"`
  354. }
  355. // Reference returns MessageReference of given message
  356. func (m *Message) Reference() *MessageReference {
  357. return &MessageReference{
  358. GuildID: m.GuildID,
  359. ChannelID: m.ChannelID,
  360. MessageID: m.ID,
  361. }
  362. }
  363. // ContentWithMentionsReplaced will replace all @<id> mentions with the
  364. // username of the mention.
  365. func (m *Message) ContentWithMentionsReplaced() (content string) {
  366. content = m.Content
  367. for _, user := range m.Mentions {
  368. content = strings.NewReplacer(
  369. "<@"+user.ID+">", "@"+user.Username,
  370. "<@!"+user.ID+">", "@"+user.Username,
  371. ).Replace(content)
  372. }
  373. return
  374. }
  375. var patternChannels = regexp.MustCompile("<#[^>]*>")
  376. // ContentWithMoreMentionsReplaced will replace all @<id> mentions with the
  377. // username of the mention, but also role IDs and more.
  378. func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) {
  379. content = m.Content
  380. if !s.StateEnabled {
  381. content = m.ContentWithMentionsReplaced()
  382. return
  383. }
  384. channel, err := s.State.Channel(m.ChannelID)
  385. if err != nil {
  386. content = m.ContentWithMentionsReplaced()
  387. return
  388. }
  389. for _, user := range m.Mentions {
  390. nick := user.Username
  391. member, err := s.State.Member(channel.GuildID, user.ID)
  392. if err == nil && member.Nick != "" {
  393. nick = member.Nick
  394. }
  395. content = strings.NewReplacer(
  396. "<@"+user.ID+">", "@"+user.Username,
  397. "<@!"+user.ID+">", "@"+nick,
  398. ).Replace(content)
  399. }
  400. for _, roleID := range m.MentionRoles {
  401. role, err := s.State.Role(channel.GuildID, roleID)
  402. if err != nil || !role.Mentionable {
  403. continue
  404. }
  405. content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1)
  406. }
  407. content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string {
  408. channel, err := s.State.Channel(mention[2 : len(mention)-1])
  409. if err != nil || channel.Type == ChannelTypeGuildVoice {
  410. return mention
  411. }
  412. return "#" + channel.Name
  413. })
  414. return
  415. }