interactions.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. Type ApplicationCommandType `json:"type,omitempty"`
  31. Name string `json:"name"`
  32. // NOTE: Chat commands only. Otherwise it mustn't be set.
  33. Description string `json:"description,omitempty"`
  34. Version string `json:"version,omitempty"`
  35. // NOTE: Chat commands only. Otherwise it mustn't be set.
  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. )
  52. func (t ApplicationCommandOptionType) String() string {
  53. switch t {
  54. case ApplicationCommandOptionSubCommand:
  55. return "SubCommand"
  56. case ApplicationCommandOptionSubCommandGroup:
  57. return "SubCommandGroup"
  58. case ApplicationCommandOptionString:
  59. return "String"
  60. case ApplicationCommandOptionInteger:
  61. return "Integer"
  62. case ApplicationCommandOptionBoolean:
  63. return "Boolean"
  64. case ApplicationCommandOptionUser:
  65. return "User"
  66. case ApplicationCommandOptionChannel:
  67. return "Channel"
  68. case ApplicationCommandOptionRole:
  69. return "Role"
  70. case ApplicationCommandOptionMentionable:
  71. return "Mentionable"
  72. }
  73. return fmt.Sprintf("ApplicationCommandOptionType(%d)", t)
  74. }
  75. // ApplicationCommandOption represents an option/subcommand/subcommands group.
  76. type ApplicationCommandOption struct {
  77. Type ApplicationCommandOptionType `json:"type"`
  78. Name string `json:"name"`
  79. Description string `json:"description,omitempty"`
  80. // NOTE: This feature was on the API, but at some point developers decided to remove it.
  81. // So I commented it, until it will be officially on the docs.
  82. // Default bool `json:"default"`
  83. ChannelTypes []ChannelType `json:"channel_types"`
  84. Required bool `json:"required"`
  85. Options []*ApplicationCommandOption `json:"options"`
  86. // NOTE: mutually exclusive with Choices.
  87. Autocomplete bool `json:"autocomplete"`
  88. Choices []*ApplicationCommandOptionChoice `json:"choices"`
  89. }
  90. // ApplicationCommandOptionChoice represents a slash command option choice.
  91. type ApplicationCommandOptionChoice struct {
  92. Name string `json:"name"`
  93. Value interface{} `json:"value"`
  94. }
  95. // InteractionType indicates the type of an interaction event.
  96. type InteractionType uint8
  97. // Interaction types
  98. const (
  99. InteractionPing InteractionType = 1
  100. InteractionApplicationCommand InteractionType = 2
  101. InteractionMessageComponent InteractionType = 3
  102. InteractionApplicationCommandAutocomplete InteractionType = 4
  103. )
  104. func (t InteractionType) String() string {
  105. switch t {
  106. case InteractionPing:
  107. return "Ping"
  108. case InteractionApplicationCommand:
  109. return "ApplicationCommand"
  110. case InteractionMessageComponent:
  111. return "MessageComponent"
  112. }
  113. return fmt.Sprintf("InteractionType(%d)", t)
  114. }
  115. // Interaction represents data of an interaction.
  116. type Interaction struct {
  117. ID string `json:"id"`
  118. Type InteractionType `json:"type"`
  119. Data InteractionData `json:"data"`
  120. GuildID string `json:"guild_id"`
  121. ChannelID string `json:"channel_id"`
  122. // The message on which interaction was used.
  123. // NOTE: this field is only filled when a button click triggered the interaction. Otherwise it will be nil.
  124. Message *Message `json:"message"`
  125. // The member who invoked this interaction.
  126. // NOTE: this field is only filled when the slash command was invoked in a guild;
  127. // if it was invoked in a DM, the `User` field will be filled instead.
  128. // Make sure to check for `nil` before using this field.
  129. Member *Member `json:"member"`
  130. // The user who invoked this interaction.
  131. // NOTE: this field is only filled when the slash command was invoked in a DM;
  132. // if it was invoked in a guild, the `Member` field will be filled instead.
  133. // Make sure to check for `nil` before using this field.
  134. User *User `json:"user"`
  135. // The user's discord client locale.
  136. Locale Locale `json:"locale"`
  137. // The guild's locale. This defaults to EnglishUS
  138. // NOTE: this field is only filled when the interaction was invoked in a guild.
  139. GuildLocale *Locale `json:"guild_locale"`
  140. Token string `json:"token"`
  141. Version int `json:"version"`
  142. }
  143. type interaction Interaction
  144. type rawInteraction struct {
  145. interaction
  146. Data json.RawMessage `json:"data"`
  147. }
  148. // UnmarshalJSON is a method for unmarshalling JSON object to Interaction.
  149. func (i *Interaction) UnmarshalJSON(raw []byte) error {
  150. var tmp rawInteraction
  151. err := json.Unmarshal(raw, &tmp)
  152. if err != nil {
  153. return err
  154. }
  155. *i = Interaction(tmp.interaction)
  156. switch tmp.Type {
  157. case InteractionApplicationCommand, InteractionApplicationCommandAutocomplete:
  158. v := ApplicationCommandInteractionData{}
  159. err = json.Unmarshal(tmp.Data, &v)
  160. if err != nil {
  161. return err
  162. }
  163. i.Data = v
  164. case InteractionMessageComponent:
  165. v := MessageComponentInteractionData{}
  166. err = json.Unmarshal(tmp.Data, &v)
  167. if err != nil {
  168. return err
  169. }
  170. i.Data = v
  171. }
  172. return nil
  173. }
  174. // MessageComponentData is helper function to assert the inner InteractionData to MessageComponentInteractionData.
  175. // Make sure to check that the Type of the interaction is InteractionMessageComponent before calling.
  176. func (i Interaction) MessageComponentData() (data MessageComponentInteractionData) {
  177. if i.Type != InteractionMessageComponent {
  178. panic("MessageComponentData called on interaction of type " + i.Type.String())
  179. }
  180. return i.Data.(MessageComponentInteractionData)
  181. }
  182. // ApplicationCommandData is helper function to assert the inner InteractionData to ApplicationCommandInteractionData.
  183. // Make sure to check that the Type of the interaction is InteractionApplicationCommand before calling.
  184. func (i Interaction) ApplicationCommandData() (data ApplicationCommandInteractionData) {
  185. if i.Type != InteractionApplicationCommand && i.Type != InteractionApplicationCommandAutocomplete {
  186. panic("ApplicationCommandData called on interaction of type " + i.Type.String())
  187. }
  188. return i.Data.(ApplicationCommandInteractionData)
  189. }
  190. // InteractionData is a common interface for all types of interaction data.
  191. type InteractionData interface {
  192. Type() InteractionType
  193. }
  194. // ApplicationCommandInteractionData contains the data of application command interaction.
  195. type ApplicationCommandInteractionData struct {
  196. ID string `json:"id"`
  197. Name string `json:"name"`
  198. Resolved *ApplicationCommandInteractionDataResolved `json:"resolved"`
  199. // Slash command options
  200. Options []*ApplicationCommandInteractionDataOption `json:"options"`
  201. // Target (user/message) id on which context menu command was called.
  202. // The details are stored in Resolved according to command type.
  203. TargetID string `json:"target_id"`
  204. }
  205. // ApplicationCommandInteractionDataResolved contains resolved data of command execution.
  206. // Partial Member objects are missing user, deaf and mute fields.
  207. // Partial Channel objects only have id, name, type and permissions fields.
  208. type ApplicationCommandInteractionDataResolved struct {
  209. Users map[string]*User `json:"users"`
  210. Members map[string]*Member `json:"members"`
  211. Roles map[string]*Role `json:"roles"`
  212. Channels map[string]*Channel `json:"channels"`
  213. Messages map[string]*Message `json:"messages"`
  214. }
  215. // Type returns the type of interaction data.
  216. func (ApplicationCommandInteractionData) Type() InteractionType {
  217. return InteractionApplicationCommand
  218. }
  219. // MessageComponentInteractionData contains the data of message component interaction.
  220. type MessageComponentInteractionData struct {
  221. CustomID string `json:"custom_id"`
  222. ComponentType ComponentType `json:"component_type"`
  223. // NOTE: Only filled when ComponentType is SelectMenuComponent (3). Otherwise is nil.
  224. Values []string `json:"values"`
  225. }
  226. // Type returns the type of interaction data.
  227. func (MessageComponentInteractionData) Type() InteractionType {
  228. return InteractionMessageComponent
  229. }
  230. // ApplicationCommandInteractionDataOption represents an option of a slash command.
  231. type ApplicationCommandInteractionDataOption struct {
  232. Name string `json:"name"`
  233. Type ApplicationCommandOptionType `json:"type"`
  234. // NOTE: Contains the value specified by Type.
  235. Value interface{} `json:"value,omitempty"`
  236. Options []*ApplicationCommandInteractionDataOption `json:"options,omitempty"`
  237. // NOTE: autocomplete interaction only.
  238. Focused bool `json:"focused,omitempty"`
  239. }
  240. // IntValue is a utility function for casting option value to integer
  241. func (o ApplicationCommandInteractionDataOption) IntValue() int64 {
  242. if o.Type != ApplicationCommandOptionInteger {
  243. panic("IntValue called on data option of type " + o.Type.String())
  244. }
  245. return int64(o.Value.(float64))
  246. }
  247. // UintValue is a utility function for casting option value to unsigned integer
  248. func (o ApplicationCommandInteractionDataOption) UintValue() uint64 {
  249. if o.Type != ApplicationCommandOptionInteger {
  250. panic("UintValue called on data option of type " + o.Type.String())
  251. }
  252. return uint64(o.Value.(float64))
  253. }
  254. // FloatValue is a utility function for casting option value to float
  255. func (o ApplicationCommandInteractionDataOption) FloatValue() float64 {
  256. // TODO: limit calls to Number type once it is released
  257. if v, ok := o.Value.(float64); ok {
  258. return v
  259. }
  260. return 0.0
  261. }
  262. // StringValue is a utility function for casting option value to string
  263. func (o ApplicationCommandInteractionDataOption) StringValue() string {
  264. if o.Type != ApplicationCommandOptionString {
  265. panic("StringValue called on data option of type " + o.Type.String())
  266. }
  267. return o.Value.(string)
  268. }
  269. // BoolValue is a utility function for casting option value to bool
  270. func (o ApplicationCommandInteractionDataOption) BoolValue() bool {
  271. if o.Type != ApplicationCommandOptionBoolean {
  272. panic("BoolValue called on data option of type " + o.Type.String())
  273. }
  274. return o.Value.(bool)
  275. }
  276. // ChannelValue is a utility function for casting option value to channel object.
  277. // s : Session object, if not nil, function additionally fetches all channel's data
  278. func (o ApplicationCommandInteractionDataOption) ChannelValue(s *Session) *Channel {
  279. if o.Type != ApplicationCommandOptionChannel {
  280. panic("ChannelValue called on data option of type " + o.Type.String())
  281. }
  282. chanID := o.Value.(string)
  283. if s == nil {
  284. return &Channel{ID: chanID}
  285. }
  286. ch, err := s.State.Channel(chanID)
  287. if err != nil {
  288. ch, err = s.Channel(chanID)
  289. if err != nil {
  290. return &Channel{ID: chanID}
  291. }
  292. }
  293. return ch
  294. }
  295. // RoleValue is a utility function for casting option value to role object.
  296. // s : Session object, if not nil, function additionally fetches all role's data
  297. func (o ApplicationCommandInteractionDataOption) RoleValue(s *Session, gID string) *Role {
  298. if o.Type != ApplicationCommandOptionRole && o.Type != ApplicationCommandOptionMentionable {
  299. panic("RoleValue called on data option of type " + o.Type.String())
  300. }
  301. roleID := o.Value.(string)
  302. if s == nil || gID == "" {
  303. return &Role{ID: roleID}
  304. }
  305. r, err := s.State.Role(roleID, gID)
  306. if err != nil {
  307. roles, err := s.GuildRoles(gID)
  308. if err == nil {
  309. for _, r = range roles {
  310. if r.ID == roleID {
  311. return r
  312. }
  313. }
  314. }
  315. return &Role{ID: roleID}
  316. }
  317. return r
  318. }
  319. // UserValue is a utility function for casting option value to user object.
  320. // s : Session object, if not nil, function additionally fetches all user's data
  321. func (o ApplicationCommandInteractionDataOption) UserValue(s *Session) *User {
  322. if o.Type != ApplicationCommandOptionUser && o.Type != ApplicationCommandOptionMentionable {
  323. panic("UserValue called on data option of type " + o.Type.String())
  324. }
  325. userID := o.Value.(string)
  326. if s == nil {
  327. return &User{ID: userID}
  328. }
  329. u, err := s.User(userID)
  330. if err != nil {
  331. return &User{ID: userID}
  332. }
  333. return u
  334. }
  335. // InteractionResponseType is type of interaction response.
  336. type InteractionResponseType uint8
  337. // Interaction response types.
  338. const (
  339. // InteractionResponsePong is for ACK ping event.
  340. InteractionResponsePong InteractionResponseType = 1
  341. // InteractionResponseChannelMessageWithSource is for responding with a message, showing the user's input.
  342. InteractionResponseChannelMessageWithSource InteractionResponseType = 4
  343. // InteractionResponseDeferredChannelMessageWithSource acknowledges that the event was received, and that a follow-up will come later.
  344. InteractionResponseDeferredChannelMessageWithSource InteractionResponseType = 5
  345. // InteractionResponseDeferredMessageUpdate acknowledges that the message component interaction event was received, and message will be updated later.
  346. InteractionResponseDeferredMessageUpdate InteractionResponseType = 6
  347. // InteractionResponseUpdateMessage is for updating the message to which message component was attached.
  348. InteractionResponseUpdateMessage InteractionResponseType = 7
  349. // InteractionApplicationCommandAutocompleteResult shows autocompletion results. Autocomplete interaction only.
  350. InteractionApplicationCommandAutocompleteResult InteractionResponseType = 8
  351. )
  352. // InteractionResponse represents a response for an interaction event.
  353. type InteractionResponse struct {
  354. Type InteractionResponseType `json:"type,omitempty"`
  355. Data *InteractionResponseData `json:"data,omitempty"`
  356. }
  357. // InteractionResponseData is response data for an interaction.
  358. type InteractionResponseData struct {
  359. TTS bool `json:"tts"`
  360. Content string `json:"content"`
  361. Components []MessageComponent `json:"components"`
  362. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  363. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  364. Flags uint64 `json:"flags,omitempty"`
  365. Files []*File `json:"-"`
  366. // NOTE: autocomplete interaction only.
  367. Choices []*ApplicationCommandOptionChoice `json:"choices,omitempty"`
  368. }
  369. // VerifyInteraction implements message verification of the discord interactions api
  370. // signing algorithm, as documented here:
  371. // https://discord.com/developers/docs/interactions/receiving-and-responding#security-and-authorization
  372. func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool {
  373. var msg bytes.Buffer
  374. signature := r.Header.Get("X-Signature-Ed25519")
  375. if signature == "" {
  376. return false
  377. }
  378. sig, err := hex.DecodeString(signature)
  379. if err != nil {
  380. return false
  381. }
  382. if len(sig) != ed25519.SignatureSize {
  383. return false
  384. }
  385. timestamp := r.Header.Get("X-Signature-Timestamp")
  386. if timestamp == "" {
  387. return false
  388. }
  389. msg.WriteString(timestamp)
  390. defer r.Body.Close()
  391. var body bytes.Buffer
  392. // at the end of the function, copy the original body back into the request
  393. defer func() {
  394. r.Body = ioutil.NopCloser(&body)
  395. }()
  396. // copy body into buffers
  397. _, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
  398. if err != nil {
  399. return false
  400. }
  401. return ed25519.Verify(key, msg.Bytes(), sig)
  402. }