interactions.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. }
  196. // Type returns the type of interaction data.
  197. func (MessageComponentInteractionData) Type() InteractionType {
  198. return InteractionMessageComponent
  199. }
  200. // ApplicationCommandInteractionDataOption represents an option of a slash command.
  201. type ApplicationCommandInteractionDataOption struct {
  202. Name string `json:"name"`
  203. Type ApplicationCommandOptionType `json:"type"`
  204. // NOTE: Contains the value specified by Type.
  205. Value interface{} `json:"value,omitempty"`
  206. Options []*ApplicationCommandInteractionDataOption `json:"options,omitempty"`
  207. }
  208. // IntValue is a utility function for casting option value to integer
  209. func (o ApplicationCommandInteractionDataOption) IntValue() int64 {
  210. if o.Type != ApplicationCommandOptionInteger {
  211. panic("IntValue called on data option of type " + o.Type.String())
  212. }
  213. return int64(o.Value.(float64))
  214. }
  215. // UintValue is a utility function for casting option value to unsigned integer
  216. func (o ApplicationCommandInteractionDataOption) UintValue() uint64 {
  217. if o.Type != ApplicationCommandOptionInteger {
  218. panic("UintValue called on data option of type " + o.Type.String())
  219. }
  220. return uint64(o.Value.(float64))
  221. }
  222. // FloatValue is a utility function for casting option value to float
  223. func (o ApplicationCommandInteractionDataOption) FloatValue() float64 {
  224. // TODO: limit calls to Number type once it is released
  225. if v, ok := o.Value.(float64); ok {
  226. return v
  227. }
  228. return 0.0
  229. }
  230. // StringValue is a utility function for casting option value to string
  231. func (o ApplicationCommandInteractionDataOption) StringValue() string {
  232. if o.Type != ApplicationCommandOptionString {
  233. panic("StringValue called on data option of type " + o.Type.String())
  234. }
  235. return o.Value.(string)
  236. }
  237. // BoolValue is a utility function for casting option value to bool
  238. func (o ApplicationCommandInteractionDataOption) BoolValue() bool {
  239. if o.Type != ApplicationCommandOptionBoolean {
  240. panic("BoolValue called on data option of type " + o.Type.String())
  241. }
  242. return o.Value.(bool)
  243. }
  244. // ChannelValue is a utility function for casting option value to channel object.
  245. // s : Session object, if not nil, function additionally fetches all channel's data
  246. func (o ApplicationCommandInteractionDataOption) ChannelValue(s *Session) *Channel {
  247. if o.Type != ApplicationCommandOptionChannel {
  248. panic("ChannelValue called on data option of type " + o.Type.String())
  249. }
  250. chanID := o.Value.(string)
  251. if s == nil {
  252. return &Channel{ID: chanID}
  253. }
  254. ch, err := s.State.Channel(chanID)
  255. if err != nil {
  256. ch, err = s.Channel(chanID)
  257. if err != nil {
  258. return &Channel{ID: chanID}
  259. }
  260. }
  261. return ch
  262. }
  263. // RoleValue is a utility function for casting option value to role object.
  264. // s : Session object, if not nil, function additionally fetches all role's data
  265. func (o ApplicationCommandInteractionDataOption) RoleValue(s *Session, gID string) *Role {
  266. if o.Type != ApplicationCommandOptionRole && o.Type != ApplicationCommandOptionMentionable {
  267. panic("RoleValue called on data option of type " + o.Type.String())
  268. }
  269. roleID := o.Value.(string)
  270. if s == nil || gID == "" {
  271. return &Role{ID: roleID}
  272. }
  273. r, err := s.State.Role(roleID, gID)
  274. if err != nil {
  275. roles, err := s.GuildRoles(gID)
  276. if err == nil {
  277. for _, r = range roles {
  278. if r.ID == roleID {
  279. return r
  280. }
  281. }
  282. }
  283. return &Role{ID: roleID}
  284. }
  285. return r
  286. }
  287. // UserValue is a utility function for casting option value to user object.
  288. // s : Session object, if not nil, function additionally fetches all user's data
  289. func (o ApplicationCommandInteractionDataOption) UserValue(s *Session) *User {
  290. if o.Type != ApplicationCommandOptionUser && o.Type != ApplicationCommandOptionMentionable {
  291. panic("UserValue called on data option of type " + o.Type.String())
  292. }
  293. userID := o.Value.(string)
  294. if s == nil {
  295. return &User{ID: userID}
  296. }
  297. u, err := s.User(userID)
  298. if err != nil {
  299. return &User{ID: userID}
  300. }
  301. return u
  302. }
  303. // InteractionResponseType is type of interaction response.
  304. type InteractionResponseType uint8
  305. // Interaction response types.
  306. const (
  307. // InteractionResponsePong is for ACK ping event.
  308. InteractionResponsePong InteractionResponseType = 1
  309. // InteractionResponseChannelMessageWithSource is for responding with a message, showing the user's input.
  310. InteractionResponseChannelMessageWithSource InteractionResponseType = 4
  311. // InteractionResponseDeferredChannelMessageWithSource acknowledges that the event was received, and that a follow-up will come later.
  312. InteractionResponseDeferredChannelMessageWithSource InteractionResponseType = 5
  313. // InteractionResponseDeferredMessageUpdate acknowledges that the message component interaction event was received, and message will be updated later.
  314. InteractionResponseDeferredMessageUpdate InteractionResponseType = 6
  315. // InteractionResponseUpdateMessage is for updating the message to which message component was attached.
  316. InteractionResponseUpdateMessage InteractionResponseType = 7
  317. )
  318. // InteractionResponse represents a response for an interaction event.
  319. type InteractionResponse struct {
  320. Type InteractionResponseType `json:"type,omitempty"`
  321. Data *InteractionResponseData `json:"data,omitempty"`
  322. }
  323. // InteractionResponseData is response data for an interaction.
  324. type InteractionResponseData struct {
  325. TTS bool `json:"tts"`
  326. Content string `json:"content"`
  327. Components []MessageComponent `json:"components"`
  328. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  329. AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"`
  330. // NOTE: Undocumented feature, be careful with it.
  331. Flags uint64 `json:"flags,omitempty"`
  332. Files []*File `json:"-"`
  333. }
  334. // VerifyInteraction implements message verification of the discord interactions api
  335. // signing algorithm, as documented here:
  336. // https://discord.com/developers/docs/interactions/slash-commands#security-and-authorization
  337. func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool {
  338. var msg bytes.Buffer
  339. signature := r.Header.Get("X-Signature-Ed25519")
  340. if signature == "" {
  341. return false
  342. }
  343. sig, err := hex.DecodeString(signature)
  344. if err != nil {
  345. return false
  346. }
  347. if len(sig) != ed25519.SignatureSize {
  348. return false
  349. }
  350. timestamp := r.Header.Get("X-Signature-Timestamp")
  351. if timestamp == "" {
  352. return false
  353. }
  354. msg.WriteString(timestamp)
  355. defer r.Body.Close()
  356. var body bytes.Buffer
  357. // at the end of the function, copy the original body back into the request
  358. defer func() {
  359. r.Body = ioutil.NopCloser(&body)
  360. }()
  361. // copy body into buffers
  362. _, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
  363. if err != nil {
  364. return false
  365. }
  366. return ed25519.Verify(key, msg.Bytes(), sig)
  367. }