message.go 15 KB

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