message.go 17 KB

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