interactions.go 15 KB

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