interactions.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package discordgo
  2. import (
  3. "bytes"
  4. "crypto/ed25519"
  5. "encoding/hex"
  6. "encoding/json"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "time"
  11. )
  12. // InteractionDeadline is the time allowed to respond to an interaction.
  13. const InteractionDeadline = time.Second * 3
  14. // ApplicationCommand represents an application's slash command.
  15. type ApplicationCommand struct {
  16. ID string `json:"id,omitempty"`
  17. ApplicationID string `json:"application_id,omitempty"`
  18. Name string `json:"name"`
  19. Description string `json:"description,omitempty"`
  20. Version string `json:"version,omitempty"`
  21. Options []*ApplicationCommandOption `json:"options"`
  22. }
  23. // ApplicationCommandOptionType indicates the type of a slash command's option.
  24. type ApplicationCommandOptionType uint8
  25. // Application command option types.
  26. const (
  27. ApplicationCommandOptionSubCommand ApplicationCommandOptionType = 1
  28. ApplicationCommandOptionSubCommandGroup ApplicationCommandOptionType = 2
  29. ApplicationCommandOptionString ApplicationCommandOptionType = 3
  30. ApplicationCommandOptionInteger ApplicationCommandOptionType = 4
  31. ApplicationCommandOptionBoolean ApplicationCommandOptionType = 5
  32. ApplicationCommandOptionUser ApplicationCommandOptionType = 6
  33. ApplicationCommandOptionChannel ApplicationCommandOptionType = 7
  34. ApplicationCommandOptionRole ApplicationCommandOptionType = 8
  35. ApplicationCommandOptionMentionable ApplicationCommandOptionType = 9
  36. )
  37. // ApplicationCommandOption represents an option/subcommand/subcommands group.
  38. type ApplicationCommandOption struct {
  39. Type ApplicationCommandOptionType `json:"type"`
  40. Name string `json:"name"`
  41. Description string `json:"description,omitempty"`
  42. // NOTE: This feature was on the API, but at some point developers decided to remove it.
  43. // So I commented it, until it will be officially on the docs.
  44. // Default bool `json:"default"`
  45. Required bool `json:"required"`
  46. Choices []*ApplicationCommandOptionChoice `json:"choices"`
  47. Options []*ApplicationCommandOption `json:"options"`
  48. }
  49. // ApplicationCommandOptionChoice represents a slash command option choice.
  50. type ApplicationCommandOptionChoice struct {
  51. Name string `json:"name"`
  52. Value interface{} `json:"value"`
  53. }
  54. // InteractionType indicates the type of an interaction event.
  55. type InteractionType uint8
  56. // Interaction types
  57. const (
  58. InteractionPing InteractionType = 1
  59. InteractionApplicationCommand InteractionType = 2
  60. InteractionMessageComponent InteractionType = 3
  61. )
  62. // Interaction represents data of an interaction.
  63. type Interaction struct {
  64. ID string `json:"id"`
  65. Type InteractionType `json:"type"`
  66. Data InteractionData `json:"-"`
  67. GuildID string `json:"guild_id"`
  68. ChannelID string `json:"channel_id"`
  69. // The message on which interaction was used.
  70. // NOTE: this field is only filled when a button click triggered the interaction. Otherwise it will be nil.
  71. Message *Message `json:"message"`
  72. // The member who invoked this interaction.
  73. // NOTE: this field is only filled when the slash command was invoked in a guild;
  74. // if it was invoked in a DM, the `User` field will be filled instead.
  75. // Make sure to check for `nil` before using this field.
  76. Member *Member `json:"member"`
  77. // The user who invoked this interaction.
  78. // NOTE: this field is only filled when the slash command was invoked in a DM;
  79. // if it was invoked in a guild, the `Member` field will be filled instead.
  80. // Make sure to check for `nil` before using this field.
  81. User *User `json:"user"`
  82. Token string `json:"token"`
  83. Version int `json:"version"`
  84. }
  85. type interaction Interaction
  86. type rawInteraction struct {
  87. interaction
  88. Data json.RawMessage `json:"data"`
  89. }
  90. // UnmarshalJSON is a method for unmarshalling JSON object to Interaction.
  91. func (i *Interaction) UnmarshalJSON(raw []byte) error {
  92. var tmp rawInteraction
  93. err := json.Unmarshal(raw, &tmp)
  94. if err != nil {
  95. return err
  96. }
  97. *i = Interaction(tmp.interaction)
  98. switch tmp.Type {
  99. case InteractionApplicationCommand:
  100. v := ApplicationCommandInteractionData{}
  101. err = json.Unmarshal(tmp.Data, &v)
  102. if err != nil {
  103. return err
  104. }
  105. i.Data = v
  106. case InteractionMessageComponent:
  107. v := MessageComponentInteractionData{}
  108. err = json.Unmarshal(tmp.Data, &v)
  109. if err != nil {
  110. return err
  111. }
  112. i.Data = v
  113. }
  114. return nil
  115. }
  116. // MessageComponentData is helper function to assert the inner InteractionData to MessageComponentInteractionData.
  117. // Make sure to check that the Type of the interaction is InteractionMessageComponent before calling.
  118. func (i Interaction) MessageComponentData() (data MessageComponentInteractionData) {
  119. return i.Data.(MessageComponentInteractionData)
  120. }
  121. // ApplicationCommandData is helper function to assert the inner InteractionData to ApplicationCommandInteractionData.
  122. // Make sure to check that the Type of the interaction is InteractionApplicationCommand before calling.
  123. func (i Interaction) ApplicationCommandData() (data ApplicationCommandInteractionData) {
  124. return i.Data.(ApplicationCommandInteractionData)
  125. }
  126. // InteractionData is a common interface for all types of interaction data.
  127. type InteractionData interface {
  128. Type() InteractionType
  129. }
  130. // ApplicationCommandInteractionData contains the data of application command interaction.
  131. type ApplicationCommandInteractionData struct {
  132. ID string `json:"id"`
  133. Name string `json:"name"`
  134. Resolved *ApplicationCommandInteractionDataResolved `json:"resolved"`
  135. Options []*ApplicationCommandInteractionDataOption `json:"options"`
  136. }
  137. // ApplicationCommandInteractionDataResolved contains resolved data for command arguments.
  138. // Partial Member objects are missing user, deaf and mute fields.
  139. // Partial Channel objects only have id, name, type and permissions fields.
  140. type ApplicationCommandInteractionDataResolved struct {
  141. Users map[string]*User `json:"users"`
  142. Members map[string]*Member `json:"members"`
  143. Roles map[string]*Role `json:"roles"`
  144. Channels map[string]*Channel `json:"channels"`
  145. }
  146. // Type returns the type of interaction data.
  147. func (ApplicationCommandInteractionData) Type() InteractionType {
  148. return InteractionApplicationCommand
  149. }
  150. // MessageComponentInteractionData contains the data of message component interaction.
  151. type MessageComponentInteractionData struct {
  152. CustomID string `json:"custom_id"`
  153. ComponentType ComponentType `json:"component_type"`
  154. }
  155. // Type returns the type of interaction data.
  156. func (MessageComponentInteractionData) Type() InteractionType {
  157. return InteractionMessageComponent
  158. }
  159. // ApplicationCommandInteractionDataOption represents an option of a slash command.
  160. type ApplicationCommandInteractionDataOption struct {
  161. Name string `json:"name"`
  162. // NOTE: Contains the value specified by InteractionType.
  163. Value interface{} `json:"value,omitempty"`
  164. Options []*ApplicationCommandInteractionDataOption `json:"options,omitempty"`
  165. }
  166. // IntValue is a utility function for casting option value to integer
  167. func (o ApplicationCommandInteractionDataOption) IntValue() int64 {
  168. if v, ok := o.Value.(float64); ok {
  169. return int64(v)
  170. }
  171. return 0
  172. }
  173. // UintValue is a utility function for casting option value to unsigned integer
  174. func (o ApplicationCommandInteractionDataOption) UintValue() uint64 {
  175. if v, ok := o.Value.(float64); ok {
  176. return uint64(v)
  177. }
  178. return 0
  179. }
  180. // FloatValue is a utility function for casting option value to float
  181. func (o ApplicationCommandInteractionDataOption) FloatValue() float64 {
  182. if v, ok := o.Value.(float64); ok {
  183. return v
  184. }
  185. return 0.0
  186. }
  187. // StringValue is a utility function for casting option value to string
  188. func (o ApplicationCommandInteractionDataOption) StringValue() string {
  189. if v, ok := o.Value.(string); ok {
  190. return v
  191. }
  192. return ""
  193. }
  194. // BoolValue is a utility function for casting option value to bool
  195. func (o ApplicationCommandInteractionDataOption) BoolValue() bool {
  196. if v, ok := o.Value.(bool); ok {
  197. return v
  198. }
  199. return false
  200. }
  201. // ChannelValue is a utility function for casting option value to channel object.
  202. // s : Session object, if not nil, function additionally fetches all channel's data
  203. func (o ApplicationCommandInteractionDataOption) ChannelValue(s *Session) *Channel {
  204. chanID := o.StringValue()
  205. if chanID == "" {
  206. return nil
  207. }
  208. if s == nil {
  209. return &Channel{ID: chanID}
  210. }
  211. ch, err := s.State.Channel(chanID)
  212. if err != nil {
  213. ch, err = s.Channel(chanID)
  214. if err != nil {
  215. return &Channel{ID: chanID}
  216. }
  217. }
  218. return ch
  219. }
  220. // RoleValue is a utility function for casting option value to role object.
  221. // s : Session object, if not nil, function additionally fetches all role's data
  222. func (o ApplicationCommandInteractionDataOption) RoleValue(s *Session, gID string) *Role {
  223. roleID := o.StringValue()
  224. if roleID == "" {
  225. return nil
  226. }
  227. if s == nil || gID == "" {
  228. return &Role{ID: roleID}
  229. }
  230. r, err := s.State.Role(roleID, gID)
  231. if err != nil {
  232. roles, err := s.GuildRoles(gID)
  233. if err == nil {
  234. for _, r = range roles {
  235. if r.ID == roleID {
  236. return r
  237. }
  238. }
  239. }
  240. return &Role{ID: roleID}
  241. }
  242. return r
  243. }
  244. // UserValue is a utility function for casting option value to user object.
  245. // s : Session object, if not nil, function additionally fetches all user's data
  246. func (o ApplicationCommandInteractionDataOption) UserValue(s *Session) *User {
  247. userID := o.StringValue()
  248. if userID == "" {
  249. return nil
  250. }
  251. if s == nil {
  252. return &User{ID: userID}
  253. }
  254. u, err := s.User(userID)
  255. if err != nil {
  256. return &User{ID: userID}
  257. }
  258. return u
  259. }
  260. // InteractionResponseType is type of interaction response.
  261. type InteractionResponseType uint8
  262. // Interaction response types.
  263. const (
  264. // InteractionResponsePong is for ACK ping event.
  265. InteractionResponsePong InteractionResponseType = 1
  266. // InteractionResponseChannelMessageWithSource is for responding with a message, showing the user's input.
  267. InteractionResponseChannelMessageWithSource InteractionResponseType = 4
  268. // InteractionResponseDeferredChannelMessageWithSource acknowledges that the event was received, and that a follow-up will come later.
  269. InteractionResponseDeferredChannelMessageWithSource InteractionResponseType = 5
  270. // InteractionResponseDeferredMessageUpdate acknowledges that the message component interaction event was received, and message will be updated later.
  271. InteractionResponseDeferredMessageUpdate InteractionResponseType = 6
  272. // InteractionResponseUpdateMessage is for updating the message to which message component was attached.
  273. InteractionResponseUpdateMessage InteractionResponseType = 7
  274. )
  275. // InteractionResponse represents a response for an interaction event.
  276. type InteractionResponse struct {
  277. Type InteractionResponseType `json:"type,omitempty"`
  278. Data *InteractionResponseData `json:"data,omitempty"`
  279. }
  280. // InteractionResponseData is response data for an interaction.
  281. type InteractionResponseData struct {
  282. TTS bool `json:"tts"`
  283. Content string `json:"content"`
  284. Components []MessageComponent `json:"components"`
  285. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  286. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  287. // NOTE: Undocumented feature, be careful with it.
  288. Flags uint64 `json:"flags,omitempty"`
  289. }
  290. // VerifyInteraction implements message verification of the discord interactions api
  291. // signing algorithm, as documented here:
  292. // https://discord.com/developers/docs/interactions/slash-commands#security-and-authorization
  293. func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool {
  294. var msg bytes.Buffer
  295. signature := r.Header.Get("X-Signature-Ed25519")
  296. if signature == "" {
  297. return false
  298. }
  299. sig, err := hex.DecodeString(signature)
  300. if err != nil {
  301. return false
  302. }
  303. if len(sig) != ed25519.SignatureSize {
  304. return false
  305. }
  306. timestamp := r.Header.Get("X-Signature-Timestamp")
  307. if timestamp == "" {
  308. return false
  309. }
  310. msg.WriteString(timestamp)
  311. defer r.Body.Close()
  312. var body bytes.Buffer
  313. // at the end of the function, copy the original body back into the request
  314. defer func() {
  315. r.Body = ioutil.NopCloser(&body)
  316. }()
  317. // copy body into buffers
  318. _, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
  319. if err != nil {
  320. return false
  321. }
  322. return ed25519.Verify(key, msg.Bytes(), sig)
  323. }