interactions.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. package discordgo
  2. import (
  3. "bytes"
  4. "crypto/ed25519"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "time"
  12. )
  13. // InteractionDeadline is the time allowed to respond to an interaction.
  14. const InteractionDeadline = time.Second * 3
  15. // ApplicationCommandType represents the type of application command.
  16. type ApplicationCommandType uint8
  17. // Application command types
  18. const (
  19. // ChatApplicationCommand is default command type. They are slash commands (i.e. called directly from the chat).
  20. ChatApplicationCommand ApplicationCommandType = 1
  21. // UserApplicationCommand adds command to user context menu.
  22. UserApplicationCommand ApplicationCommandType = 2
  23. // MessageApplicationCommand adds command to message context menu.
  24. MessageApplicationCommand ApplicationCommandType = 3
  25. )
  26. // ApplicationCommand represents an application's slash command.
  27. type ApplicationCommand struct {
  28. ID string `json:"id,omitempty"`
  29. ApplicationID string `json:"application_id,omitempty"`
  30. Version string `json:"version,omitempty"`
  31. Type ApplicationCommandType `json:"type,omitempty"`
  32. Name string `json:"name"`
  33. DefaultPermission *bool `json:"default_permission,omitempty"`
  34. // NOTE: Chat commands only. Otherwise it mustn't be set.
  35. Description string `json:"description,omitempty"`
  36. Options []*ApplicationCommandOption `json:"options"`
  37. }
  38. // ApplicationCommandOptionType indicates the type of a slash command's option.
  39. type ApplicationCommandOptionType uint8
  40. // Application command option types.
  41. const (
  42. ApplicationCommandOptionSubCommand ApplicationCommandOptionType = 1
  43. ApplicationCommandOptionSubCommandGroup ApplicationCommandOptionType = 2
  44. ApplicationCommandOptionString ApplicationCommandOptionType = 3
  45. ApplicationCommandOptionInteger ApplicationCommandOptionType = 4
  46. ApplicationCommandOptionBoolean ApplicationCommandOptionType = 5
  47. ApplicationCommandOptionUser ApplicationCommandOptionType = 6
  48. ApplicationCommandOptionChannel ApplicationCommandOptionType = 7
  49. ApplicationCommandOptionRole ApplicationCommandOptionType = 8
  50. ApplicationCommandOptionMentionable ApplicationCommandOptionType = 9
  51. ApplicationCommandOptionNumber ApplicationCommandOptionType = 10
  52. ApplicationCommandOptionAttachment ApplicationCommandOptionType = 11
  53. )
  54. func (t ApplicationCommandOptionType) String() string {
  55. switch t {
  56. case ApplicationCommandOptionSubCommand:
  57. return "SubCommand"
  58. case ApplicationCommandOptionSubCommandGroup:
  59. return "SubCommandGroup"
  60. case ApplicationCommandOptionString:
  61. return "String"
  62. case ApplicationCommandOptionInteger:
  63. return "Integer"
  64. case ApplicationCommandOptionBoolean:
  65. return "Boolean"
  66. case ApplicationCommandOptionUser:
  67. return "User"
  68. case ApplicationCommandOptionChannel:
  69. return "Channel"
  70. case ApplicationCommandOptionRole:
  71. return "Role"
  72. case ApplicationCommandOptionMentionable:
  73. return "Mentionable"
  74. case ApplicationCommandOptionNumber:
  75. return "Number"
  76. case ApplicationCommandOptionAttachment:
  77. return "Attachment"
  78. }
  79. return fmt.Sprintf("ApplicationCommandOptionType(%d)", t)
  80. }
  81. // ApplicationCommandOption represents an option/subcommand/subcommands group.
  82. type ApplicationCommandOption struct {
  83. Type ApplicationCommandOptionType `json:"type"`
  84. Name string `json:"name"`
  85. Description string `json:"description,omitempty"`
  86. // NOTE: This feature was on the API, but at some point developers decided to remove it.
  87. // So I commented it, until it will be officially on the docs.
  88. // Default bool `json:"default"`
  89. ChannelTypes []ChannelType `json:"channel_types"`
  90. Required bool `json:"required"`
  91. Options []*ApplicationCommandOption `json:"options"`
  92. // NOTE: mutually exclusive with Choices.
  93. Autocomplete bool `json:"autocomplete"`
  94. Choices []*ApplicationCommandOptionChoice `json:"choices"`
  95. // Minimal value of number/integer option.
  96. MinValue *float64 `json:"min_value,omitempty"`
  97. // Maximum value of number/integer option.
  98. MaxValue float64 `json:"max_value,omitempty"`
  99. }
  100. // ApplicationCommandOptionChoice represents a slash command option choice.
  101. type ApplicationCommandOptionChoice struct {
  102. Name string `json:"name"`
  103. Value interface{} `json:"value"`
  104. }
  105. // ApplicationCommandPermissions represents a single user or role permission for a command.
  106. type ApplicationCommandPermissions struct {
  107. ID string `json:"id"`
  108. Type ApplicationCommandPermissionType `json:"type"`
  109. Permission bool `json:"permission"`
  110. }
  111. // ApplicationCommandPermissionsList represents a list of ApplicationCommandPermissions, needed for serializing to JSON.
  112. type ApplicationCommandPermissionsList struct {
  113. Permissions []*ApplicationCommandPermissions `json:"permissions"`
  114. }
  115. // GuildApplicationCommandPermissions represents all permissions for a single guild command.
  116. type GuildApplicationCommandPermissions struct {
  117. ID string `json:"id"`
  118. ApplicationID string `json:"application_id"`
  119. GuildID string `json:"guild_id"`
  120. Permissions []*ApplicationCommandPermissions `json:"permissions"`
  121. }
  122. // ApplicationCommandPermissionType indicates whether a permission is user or role based.
  123. type ApplicationCommandPermissionType uint8
  124. // Application command permission types.
  125. const (
  126. ApplicationCommandPermissionTypeRole ApplicationCommandPermissionType = 1
  127. ApplicationCommandPermissionTypeUser ApplicationCommandPermissionType = 2
  128. )
  129. // InteractionType indicates the type of an interaction event.
  130. type InteractionType uint8
  131. // Interaction types
  132. const (
  133. InteractionPing InteractionType = 1
  134. InteractionApplicationCommand InteractionType = 2
  135. InteractionMessageComponent InteractionType = 3
  136. InteractionApplicationCommandAutocomplete InteractionType = 4
  137. InteractionModalSubmit InteractionType = 5
  138. )
  139. func (t InteractionType) String() string {
  140. switch t {
  141. case InteractionPing:
  142. return "Ping"
  143. case InteractionApplicationCommand:
  144. return "ApplicationCommand"
  145. case InteractionMessageComponent:
  146. return "MessageComponent"
  147. case InteractionModalSubmit:
  148. return "ModalSubmit"
  149. }
  150. return fmt.Sprintf("InteractionType(%d)", t)
  151. }
  152. // Interaction represents data of an interaction.
  153. type Interaction struct {
  154. ID string `json:"id"`
  155. Type InteractionType `json:"type"`
  156. Data InteractionData `json:"data"`
  157. GuildID string `json:"guild_id"`
  158. ChannelID string `json:"channel_id"`
  159. // The message on which interaction was used.
  160. // NOTE: this field is only filled when a button click triggered the interaction. Otherwise it will be nil.
  161. Message *Message `json:"message"`
  162. // The member who invoked this interaction.
  163. // NOTE: this field is only filled when the slash command was invoked in a guild;
  164. // if it was invoked in a DM, the `User` field will be filled instead.
  165. // Make sure to check for `nil` before using this field.
  166. Member *Member `json:"member"`
  167. // The user who invoked this interaction.
  168. // NOTE: this field is only filled when the slash command was invoked in a DM;
  169. // if it was invoked in a guild, the `Member` field will be filled instead.
  170. // Make sure to check for `nil` before using this field.
  171. User *User `json:"user"`
  172. // The user's discord client locale.
  173. Locale Locale `json:"locale"`
  174. // The guild's locale. This defaults to EnglishUS
  175. // NOTE: this field is only filled when the interaction was invoked in a guild.
  176. GuildLocale *Locale `json:"guild_locale"`
  177. Token string `json:"token"`
  178. Version int `json:"version"`
  179. }
  180. type interaction Interaction
  181. type rawInteraction struct {
  182. interaction
  183. Data json.RawMessage `json:"data"`
  184. }
  185. // UnmarshalJSON is a method for unmarshalling JSON object to Interaction.
  186. func (i *Interaction) UnmarshalJSON(raw []byte) error {
  187. var tmp rawInteraction
  188. err := json.Unmarshal(raw, &tmp)
  189. if err != nil {
  190. return err
  191. }
  192. *i = Interaction(tmp.interaction)
  193. switch tmp.Type {
  194. case InteractionApplicationCommand, InteractionApplicationCommandAutocomplete:
  195. v := ApplicationCommandInteractionData{}
  196. err = json.Unmarshal(tmp.Data, &v)
  197. if err != nil {
  198. return err
  199. }
  200. i.Data = v
  201. case InteractionMessageComponent:
  202. v := MessageComponentInteractionData{}
  203. err = json.Unmarshal(tmp.Data, &v)
  204. if err != nil {
  205. return err
  206. }
  207. i.Data = v
  208. case InteractionModalSubmit:
  209. v := ModalSubmitInteractionData{}
  210. err = json.Unmarshal(tmp.Data, &v)
  211. if err != nil {
  212. return err
  213. }
  214. i.Data = v
  215. }
  216. return nil
  217. }
  218. // MessageComponentData is helper function to assert the inner InteractionData to MessageComponentInteractionData.
  219. // Make sure to check that the Type of the interaction is InteractionMessageComponent before calling.
  220. func (i Interaction) MessageComponentData() (data MessageComponentInteractionData) {
  221. if i.Type != InteractionMessageComponent {
  222. panic("MessageComponentData called on interaction of type " + i.Type.String())
  223. }
  224. return i.Data.(MessageComponentInteractionData)
  225. }
  226. // ApplicationCommandData is helper function to assert the inner InteractionData to ApplicationCommandInteractionData.
  227. // Make sure to check that the Type of the interaction is InteractionApplicationCommand before calling.
  228. func (i Interaction) ApplicationCommandData() (data ApplicationCommandInteractionData) {
  229. if i.Type != InteractionApplicationCommand && i.Type != InteractionApplicationCommandAutocomplete {
  230. panic("ApplicationCommandData called on interaction of type " + i.Type.String())
  231. }
  232. return i.Data.(ApplicationCommandInteractionData)
  233. }
  234. // ModalSubmitData is helper function to assert the inner InteractionData to ModalSubmitInteractionData.
  235. // Make sure to check that the Type of the interaction is InteractionModalSubmit before calling.
  236. func (i Interaction) ModalSubmitData() (data ModalSubmitInteractionData) {
  237. if i.Type != InteractionModalSubmit {
  238. panic("ModalSubmitData called on interaction of type " + i.Type.String())
  239. }
  240. return i.Data.(ModalSubmitInteractionData)
  241. }
  242. // InteractionData is a common interface for all types of interaction data.
  243. type InteractionData interface {
  244. Type() InteractionType
  245. }
  246. // ApplicationCommandInteractionData contains the data of application command interaction.
  247. type ApplicationCommandInteractionData struct {
  248. ID string `json:"id"`
  249. Name string `json:"name"`
  250. Resolved *ApplicationCommandInteractionDataResolved `json:"resolved"`
  251. // Slash command options
  252. Options []*ApplicationCommandInteractionDataOption `json:"options"`
  253. // Target (user/message) id on which context menu command was called.
  254. // The details are stored in Resolved according to command type.
  255. TargetID string `json:"target_id"`
  256. }
  257. // ApplicationCommandInteractionDataResolved contains resolved data of command execution.
  258. // Partial Member objects are missing user, deaf and mute fields.
  259. // Partial Channel objects only have id, name, type and permissions fields.
  260. type ApplicationCommandInteractionDataResolved struct {
  261. Users map[string]*User `json:"users"`
  262. Members map[string]*Member `json:"members"`
  263. Roles map[string]*Role `json:"roles"`
  264. Channels map[string]*Channel `json:"channels"`
  265. Messages map[string]*Message `json:"messages"`
  266. Attachments map[string]*MessageAttachment `json:"attachments"`
  267. }
  268. // Type returns the type of interaction data.
  269. func (ApplicationCommandInteractionData) Type() InteractionType {
  270. return InteractionApplicationCommand
  271. }
  272. // MessageComponentInteractionData contains the data of message component interaction.
  273. type MessageComponentInteractionData struct {
  274. CustomID string `json:"custom_id"`
  275. ComponentType ComponentType `json:"component_type"`
  276. // NOTE: Only filled when ComponentType is SelectMenuComponent (3). Otherwise is nil.
  277. Values []string `json:"values"`
  278. }
  279. // Type returns the type of interaction data.
  280. func (MessageComponentInteractionData) Type() InteractionType {
  281. return InteractionMessageComponent
  282. }
  283. // ModalSubmitInteractionData contains the data of modal submit interaction.
  284. type ModalSubmitInteractionData struct {
  285. CustomID string `json:"custom_id"`
  286. Components []MessageComponent `json:"-"`
  287. }
  288. // Type returns the type of interaction data.
  289. func (ModalSubmitInteractionData) Type() InteractionType {
  290. return InteractionModalSubmit
  291. }
  292. // UnmarshalJSON is a helper function to correctly unmarshal Components.
  293. func (d *ModalSubmitInteractionData) UnmarshalJSON(data []byte) error {
  294. type modalSubmitInteractionData ModalSubmitInteractionData
  295. var v struct {
  296. modalSubmitInteractionData
  297. RawComponents []unmarshalableMessageComponent `json:"components"`
  298. }
  299. err := json.Unmarshal(data, &v)
  300. if err != nil {
  301. return err
  302. }
  303. *d = ModalSubmitInteractionData(v.modalSubmitInteractionData)
  304. d.Components = make([]MessageComponent, len(v.RawComponents))
  305. for i, v := range v.RawComponents {
  306. d.Components[i] = v.MessageComponent
  307. }
  308. return err
  309. }
  310. // ApplicationCommandInteractionDataOption represents an option of a slash command.
  311. type ApplicationCommandInteractionDataOption struct {
  312. Name string `json:"name"`
  313. Type ApplicationCommandOptionType `json:"type"`
  314. // NOTE: Contains the value specified by Type.
  315. Value interface{} `json:"value,omitempty"`
  316. Options []*ApplicationCommandInteractionDataOption `json:"options,omitempty"`
  317. // NOTE: autocomplete interaction only.
  318. Focused bool `json:"focused,omitempty"`
  319. }
  320. // IntValue is a utility function for casting option value to integer
  321. func (o ApplicationCommandInteractionDataOption) IntValue() int64 {
  322. if o.Type != ApplicationCommandOptionInteger {
  323. panic("IntValue called on data option of type " + o.Type.String())
  324. }
  325. return int64(o.Value.(float64))
  326. }
  327. // UintValue is a utility function for casting option value to unsigned integer
  328. func (o ApplicationCommandInteractionDataOption) UintValue() uint64 {
  329. if o.Type != ApplicationCommandOptionInteger {
  330. panic("UintValue called on data option of type " + o.Type.String())
  331. }
  332. return uint64(o.Value.(float64))
  333. }
  334. // FloatValue is a utility function for casting option value to float
  335. func (o ApplicationCommandInteractionDataOption) FloatValue() float64 {
  336. if o.Type != ApplicationCommandOptionNumber {
  337. panic("FloatValue called on data option of type " + o.Type.String())
  338. }
  339. return o.Value.(float64)
  340. }
  341. // StringValue is a utility function for casting option value to string
  342. func (o ApplicationCommandInteractionDataOption) StringValue() string {
  343. if o.Type != ApplicationCommandOptionString {
  344. panic("StringValue called on data option of type " + o.Type.String())
  345. }
  346. return o.Value.(string)
  347. }
  348. // BoolValue is a utility function for casting option value to bool
  349. func (o ApplicationCommandInteractionDataOption) BoolValue() bool {
  350. if o.Type != ApplicationCommandOptionBoolean {
  351. panic("BoolValue called on data option of type " + o.Type.String())
  352. }
  353. return o.Value.(bool)
  354. }
  355. // ChannelValue is a utility function for casting option value to channel object.
  356. // s : Session object, if not nil, function additionally fetches all channel's data
  357. func (o ApplicationCommandInteractionDataOption) ChannelValue(s *Session) *Channel {
  358. if o.Type != ApplicationCommandOptionChannel {
  359. panic("ChannelValue called on data option of type " + o.Type.String())
  360. }
  361. chanID := o.Value.(string)
  362. if s == nil {
  363. return &Channel{ID: chanID}
  364. }
  365. ch, err := s.State.Channel(chanID)
  366. if err != nil {
  367. ch, err = s.Channel(chanID)
  368. if err != nil {
  369. return &Channel{ID: chanID}
  370. }
  371. }
  372. return ch
  373. }
  374. // RoleValue is a utility function for casting option value to role object.
  375. // s : Session object, if not nil, function additionally fetches all role's data
  376. func (o ApplicationCommandInteractionDataOption) RoleValue(s *Session, gID string) *Role {
  377. if o.Type != ApplicationCommandOptionRole && o.Type != ApplicationCommandOptionMentionable {
  378. panic("RoleValue called on data option of type " + o.Type.String())
  379. }
  380. roleID := o.Value.(string)
  381. if s == nil || gID == "" {
  382. return &Role{ID: roleID}
  383. }
  384. r, err := s.State.Role(roleID, gID)
  385. if err != nil {
  386. roles, err := s.GuildRoles(gID)
  387. if err == nil {
  388. for _, r = range roles {
  389. if r.ID == roleID {
  390. return r
  391. }
  392. }
  393. }
  394. return &Role{ID: roleID}
  395. }
  396. return r
  397. }
  398. // UserValue is a utility function for casting option value to user object.
  399. // s : Session object, if not nil, function additionally fetches all user's data
  400. func (o ApplicationCommandInteractionDataOption) UserValue(s *Session) *User {
  401. if o.Type != ApplicationCommandOptionUser && o.Type != ApplicationCommandOptionMentionable {
  402. panic("UserValue called on data option of type " + o.Type.String())
  403. }
  404. userID := o.Value.(string)
  405. if s == nil {
  406. return &User{ID: userID}
  407. }
  408. u, err := s.User(userID)
  409. if err != nil {
  410. return &User{ID: userID}
  411. }
  412. return u
  413. }
  414. // InteractionResponseType is type of interaction response.
  415. type InteractionResponseType uint8
  416. // Interaction response types.
  417. const (
  418. // InteractionResponsePong is for ACK ping event.
  419. InteractionResponsePong InteractionResponseType = 1
  420. // InteractionResponseChannelMessageWithSource is for responding with a message, showing the user's input.
  421. InteractionResponseChannelMessageWithSource InteractionResponseType = 4
  422. // InteractionResponseDeferredChannelMessageWithSource acknowledges that the event was received, and that a follow-up will come later.
  423. InteractionResponseDeferredChannelMessageWithSource InteractionResponseType = 5
  424. // InteractionResponseDeferredMessageUpdate acknowledges that the message component interaction event was received, and message will be updated later.
  425. InteractionResponseDeferredMessageUpdate InteractionResponseType = 6
  426. // InteractionResponseUpdateMessage is for updating the message to which message component was attached.
  427. InteractionResponseUpdateMessage InteractionResponseType = 7
  428. // InteractionApplicationCommandAutocompleteResult shows autocompletion results. Autocomplete interaction only.
  429. InteractionApplicationCommandAutocompleteResult InteractionResponseType = 8
  430. // InteractionResponseModal is for responding to an interaction with a modal window.
  431. InteractionResponseModal InteractionResponseType = 9
  432. )
  433. // InteractionResponse represents a response for an interaction event.
  434. type InteractionResponse struct {
  435. Type InteractionResponseType `json:"type,omitempty"`
  436. Data *InteractionResponseData `json:"data,omitempty"`
  437. }
  438. // InteractionResponseData is response data for an interaction.
  439. type InteractionResponseData struct {
  440. TTS bool `json:"tts"`
  441. Content string `json:"content"`
  442. Components []MessageComponent `json:"components"`
  443. Embeds []*MessageEmbed `json:"embeds"`
  444. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  445. Flags uint64 `json:"flags,omitempty"`
  446. Files []*File `json:"-"`
  447. // NOTE: autocomplete interaction only.
  448. Choices []*ApplicationCommandOptionChoice `json:"choices,omitempty"`
  449. // NOTE: modal interaction only.
  450. CustomID string `json:"custom_id,omitempty"`
  451. Title string `json:"title,omitempty"`
  452. }
  453. // VerifyInteraction implements message verification of the discord interactions api
  454. // signing algorithm, as documented here:
  455. // https://discord.com/developers/docs/interactions/receiving-and-responding#security-and-authorization
  456. func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool {
  457. var msg bytes.Buffer
  458. signature := r.Header.Get("X-Signature-Ed25519")
  459. if signature == "" {
  460. return false
  461. }
  462. sig, err := hex.DecodeString(signature)
  463. if err != nil {
  464. return false
  465. }
  466. if len(sig) != ed25519.SignatureSize {
  467. return false
  468. }
  469. timestamp := r.Header.Get("X-Signature-Timestamp")
  470. if timestamp == "" {
  471. return false
  472. }
  473. msg.WriteString(timestamp)
  474. defer r.Body.Close()
  475. var body bytes.Buffer
  476. // at the end of the function, copy the original body back into the request
  477. defer func() {
  478. r.Body = ioutil.NopCloser(&body)
  479. }()
  480. // copy body into buffers
  481. _, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
  482. if err != nil {
  483. return false
  484. }
  485. return ed25519.Verify(key, msg.Bytes(), sig)
  486. }