-
Notifications
You must be signed in to change notification settings - Fork 1
/
interactions.go
234 lines (207 loc) · 6.34 KB
/
interactions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package interactions
import (
"context"
"crypto/ed25519"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"time"
"github.com/rs/zerolog"
"wumpgo.dev/wumpgo/objects"
"wumpgo.dev/wumpgo/rest"
)
type (
HandlerFunc func(context.Context, *objects.Interaction) *objects.InteractionResponse
)
// App is the primary interactions server
type App struct {
logger zerolog.Logger
restClient rest.RESTClient
commandHandler HandlerFunc
componentHandler HandlerFunc
autocompleteHandler HandlerFunc
modalHandler HandlerFunc
pubKey ed25519.PublicKey
}
// Create a new interactions server instance
func New(publicKey string, opts ...InteractionOption) (*App, error) {
pubKey, err := parsePublicKey(publicKey)
if err != nil {
return nil, err
}
a := &App{
pubKey: pubKey,
logger: zerolog.Nop(),
}
for _, o := range opts {
o(a)
}
return a, nil
}
// CommandHandler sets the function to handle slash command events
func (a *App) CommandHandler(handler HandlerFunc) {
a.commandHandler = handler
}
// ComponentHandler sets the function to handle Component events.
func (a *App) ComponentHandler(handler HandlerFunc) {
a.componentHandler = handler
}
func (a *App) AutocompleteHandler(handler HandlerFunc) {
a.autocompleteHandler = handler
}
func (a *App) ModalHandler(handler HandlerFunc) {
a.modalHandler = handler
}
// ServeHTTP makes App implement the http.Handler interface
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.HTTPHandler()(w, r)
}
func FailUnknownError(w http.ResponseWriter, jr *json.Encoder) {
w.Header().Set("Content-Type", "application/json")
_ = jr.Encode(objects.InteractionResponse{
Type: objects.ResponseChannelMessageWithSource,
Data: &objects.InteractionMessagesCallbackData{
Content: "An unknown error occurred",
Flags: objects.MsgFlagEphemeral,
},
})
}
// HTTPHandler exposes a net/http handler to process incoming interactions
func (a *App) HTTPHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
jr := json.NewEncoder(w)
signature := r.Header.Get("X-Signature-Ed25519")
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
FailUnknownError(w, jr)
return
}
body := append([]byte(r.Header.Get("X-Signature-Timestamp")), bodyBytes...)
if !verifyMessage(body, signature, a.pubKey) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
return
}
resp, err := a.ProcessRequest(a.logger.WithContext(r.Context()), bodyBytes)
if err != nil {
FailUnknownError(w, jr)
return
}
if resp.Type == objects.ResponseChannelMessageWithSource ||
resp.Type == objects.ResponseUpdateMessage {
var data *objects.InteractionMessagesCallbackData
switch d := resp.Data.(type) {
case objects.InteractionMessagesCallbackData:
data = &d
case *objects.InteractionMessagesCallbackData:
data = d
default:
data = nil
}
if data != nil && len(data.Files) > 0 {
m := multipart.NewWriter(w)
w.Header().Set("Content-Type", m.FormDataContentType())
for n, file := range data.Files {
// Generate the attachment object, assign a number to it, and write it to the multipart writer
attach, err := file.GenerateAttachment(objects.Snowflake(n+1), m)
if err != nil {
a.logger.Error().Err(err).Msg("failed to generate attachment")
continue
}
data.Attachments = append(data.Attachments, attach)
}
if field, err := m.CreateFormField("payload_json"); err != nil {
a.logger.Error().Err(err).Msg("failed to create payload_json form field")
FailUnknownError(w, jr)
return
} else {
if err := json.NewEncoder(field).Encode(resp); err != nil {
a.logger.Error().Err(err).Msg("failed to encode payload_json")
FailUnknownError(w, jr)
return
}
}
if err := m.Close(); err != nil {
a.logger.Error().Err(err).Msg("failed to close multipart writer")
FailUnknownError(w, jr)
return
}
return
}
}
w.Header().Set("Content-Type", "application/json")
err = jr.Encode(resp)
if err != nil {
a.logger.Error().Err(err).Msg("failed to write response")
}
})
}
// ProcessRequest is used internally to process a validated request.
// It is exposed to allow users to tied Postcord in with any web framework
// of their choosing. Ensure you only pass validated requests.
func (a *App) ProcessRequest(ctx context.Context, data []byte) (resp *objects.InteractionResponse, err error) {
var req objects.Interaction
err = json.Unmarshal(data, &req)
if err != nil {
a.logger.Error().Err(err).Msg("failed to unmarshal request")
err = fmt.Errorf("failed to decode request body")
return
}
l := zerolog.Ctx(ctx)
newLogger := l.With().Int("interaction_type", int(req.Type)).Int("interaction_id", int(req.ID)).Logger()
ctx = newLogger.WithContext(ctx)
l.Debug().Msg("received request")
// Discord requires all interactions respond within 3 seconds
// so we may as well enforce this here
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(3*time.Second))
defer cancel()
switch req.Type {
case objects.InteractionRequestPing:
resp = &objects.InteractionResponse{Type: objects.ResponsePong}
return
case objects.InteractionApplicationCommand:
if a.commandHandler != nil {
resp = a.commandHandler(ctx, &req)
} else {
l.Warn().Msg("no command handler set")
}
case objects.InteractionComponent:
if a.componentHandler != nil {
resp = a.componentHandler(ctx, &req)
if resp == nil {
return &objects.InteractionResponse{
Type: objects.ResponseDeferredMessageUpdate,
}, nil
}
} else {
l.Warn().Msg("no component handler set")
}
case objects.InteractionAutoComplete:
if a.autocompleteHandler != nil {
resp = a.autocompleteHandler(ctx, &req)
} else {
l.Warn().Msg("no autocomplete handler set")
}
case objects.InteractionModalSubmit:
if a.modalHandler != nil {
resp = a.modalHandler(ctx, &req)
} else {
l.Warn().Msg("no modal handler set")
}
default:
l.Warn().Msg("unknown interaction type")
err = fmt.Errorf("unknown interaction type: %d", req.Type)
}
if resp == nil {
err = fmt.Errorf("nil response")
} else {
l.Debug().Msg("sending response")
}
return
}
// Rest exposes the internal Rest client so you can make calls to the Discord API
func (a *App) Rest() rest.RESTClient {
return a.restClient
}