interactions.go 14 KB

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