interactions.go 15 KB

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