-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
398 lines (375 loc) · 10.4 KB
/
main.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/slack-go/slack"
"github.com/slack-go/slack/socketmode"
"golang.org/x/sync/errgroup"
)
// SlackRequest takes in the StatusCode and Content from other functions to display to the user's slack.
type SlackRequest struct {
// StatusCode is the http code that will be returned back to the user.
StatusCode int `json:"statusCode"`
// Content will contain the presigned url, error messages, or success messages.
Content string `json:"body"`
}
// SlackResponse returns back the http code, type of data, and the presigned url to the user.
type SlackResponse struct {
// StatusCode is the http code that will be returned back to the user.
StatusCode int `json:"statusCode,omitempty"`
// Headers is the information about the type of data being returned back.
Headers map[string]string `json:"headers,omitempty"`
// Body will contain the success or failed messages.
Body string `json:"body,omitempty"`
}
// Email is the json struct of the email message that contains the email addresses, subject, and message.
type Email struct {
// From is the email address of the user.
From string `json:"from"`
// To is the email address that the user wants to send to.
To string `json:"to"`
// Subject is the subject of the email that the user wants to send.
Subject string `json:"subject"`
// Message is the body of the email that the user wants to send.
Content string `json:"content"`
}
// Sms is the json struct of the sms message that contains the phone numbers and message.
type Sms struct {
// From is the user's phone number that they are sending from.
From string `json:"from"`
// Number is the phone number they are sending a message to.
Number string `json:"number"`
// Message is the body of the message that the user wants to send.
Message string `json:"message"`
}
// Url is the json struct of the presigned url function that contains the filename, type, and duration.
type Url struct {
// Filename is the name of the file that will be uploaded or downloaded.
Filename string `json:"filename"`
// Type is a presigned request type to "GET" or "PUT" an object.
Type string `json:"type"`
// Duration is the duration in which the presigned url will last.
Duration string `json:"duration"`
}
// funcResponse takes in the StatusCode and Content from other functions to display to the user's slack.
type funcResponse struct {
// StatusCode is the http code that will be returned back to the user.
StatusCode int `json:"statusCode"`
// Content will contain the presigned url, error messages, or success messages.
Body string `json:"body"`
}
var (
authToken, appToken, channelid, url string
// ErrNotEnoughArgs will return an error if the user does not provide the right number of arguments.
ErrNotEnoughArgs = errors.New("not enough arguments provided")
)
const (
// EmailsCommand is the slash command to send an email.
EmailsCommand = "/emails"
// SmsCommand is the slash command to send sms.
SmsCommand = "/sms"
// UrlCommand is the slash command to get a presigned url.
UrlCommand = "/url"
)
func init() {
authToken = os.Getenv("AUTH_TOKEN")
if authToken == "" {
panic("no authToken provided")
}
appToken = os.Getenv("APP_TOKEN")
if appToken == "" {
panic("no appToken provided")
}
channelid = os.Getenv("CHANNEL_ID")
if channelid == "" {
panic("no channelid provided")
}
url = os.Getenv("URL")
if url == "" {
panic("no url provided")
}
}
// main configures a client with socketmode and slacks API using the token, app token, and channelid that the slack bot will be in,
// handles the different slash commands, and returns back a slack attachment with the body returned by the different functions.
func main() {
var eg errgroup.Group
api := slack.New(authToken, slack.OptionDebug(true), slack.OptionAppLevelToken(appToken))
client := socketmode.New(
api,
socketmode.OptionDebug(true),
)
c, cancel := context.WithCancel(context.Background())
defer cancel()
eg.Go(func() error {
for {
select {
case <-c.Done():
return nil
case event := <-client.Events:
switch event.Type {
case socketmode.EventTypeSlashCommand:
command, ok := event.Data.(slack.SlashCommand)
if !ok {
continue
}
client.Ack(*event.Request)
var (
err error
slackRequest *SlackRequest
)
switch command.Command {
case EmailsCommand:
emailResponse, err := handleEmail(command)
if err != nil {
fmt.Fprintf(os.Stderr, "error handling email response: %s\n", err.Error())
}
slackRequest = &SlackRequest{
StatusCode: emailResponse.StatusCode,
Content: emailResponse.Body,
}
case SmsCommand:
smsResponse, err := handleSMS(command)
if err != nil {
fmt.Fprintf(os.Stderr, "error handling sms response: %s\n", err.Error())
}
slackRequest = &SlackRequest{
StatusCode: smsResponse.StatusCode,
Content: smsResponse.Body,
}
case UrlCommand:
urlResponse, err := handleURL(command)
if err != nil {
fmt.Fprintf(os.Stderr, "error handling url response: %s\n", err.Error())
}
slackRequest = &SlackRequest{
StatusCode: urlResponse.StatusCode,
Content: urlResponse.Body,
}
default:
slackRequest = &SlackRequest{
StatusCode: 404,
Content: "command not found",
}
}
err = makeRequest(slackRequest, api)
if err != nil {
fmt.Fprintf(os.Stderr, "error sending slack attachment: %s\n", err.Error())
}
}
}
}
})
eg.Go(func() error {
return client.Run()
})
err := eg.Wait()
if err != nil {
log.Fatal(err)
}
}
func handleEmail(command slack.SlashCommand) (*funcResponse, error) {
params := &slack.Msg{Text: command.Text}
str := strings.Split(params.Text, " ")
temp := deleteEmpty(str)
if len(temp) < 4 {
resp := &funcResponse{
StatusCode: http.StatusBadRequest,
Body: ErrNotEnoughArgs.Error(),
}
return resp, ErrNotEnoughArgs
}
from, to, subject, content := temp[0], temp[1], temp[2], temp[3:]
contentstr := strings.Join(content, " ")
emailUrl := fmt.Sprintf("%s/sendgrid-email/sample/emails", url)
payload := Email{
From: from,
To: to,
Subject: subject,
Content: contentstr,
}
json, err := json.Marshal(payload)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req, err := http.NewRequest(http.MethodPost, emailUrl, bytes.NewBuffer(json))
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req.Header.Add("content-type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
bytes, err := io.ReadAll(res.Body)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
resp := &funcResponse{
StatusCode: res.StatusCode,
Body: string(bytes),
}
defer res.Body.Close()
return resp, nil
}
func handleSMS(command slack.SlashCommand) (*funcResponse, error) {
params := &slack.Msg{Text: command.Text}
str := strings.Split(params.Text, " ")
temp := deleteEmpty(str)
if len(temp) < 3 {
resp := &funcResponse{
StatusCode: http.StatusBadRequest,
Body: ErrNotEnoughArgs.Error(),
}
return resp, ErrNotEnoughArgs
}
from, number, msg := temp[0], temp[1], temp[2:]
msgstr := strings.Join(msg, " ")
smsUrl := fmt.Sprintf("%s/twilio-sms/sample/sms", url)
payload := Sms{
From: from,
Number: number,
Message: msgstr,
}
json, err := json.Marshal(payload)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req, err := http.NewRequest(http.MethodPost, smsUrl, bytes.NewBuffer(json))
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req.Header.Add("content-type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
bytes, err := io.ReadAll(res.Body)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
resp := &funcResponse{
StatusCode: res.StatusCode,
Body: string(bytes),
}
defer res.Body.Close()
return resp, nil
}
func handleURL(command slack.SlashCommand) (*funcResponse, error) {
params := &slack.Msg{Text: command.Text}
str := strings.Split(params.Text, " ")
temp := deleteEmpty(str)
if len(temp) < 3 {
resp := &funcResponse{
StatusCode: http.StatusBadRequest,
Body: ErrNotEnoughArgs.Error(),
}
return resp, ErrNotEnoughArgs
}
filename, request, duration := temp[0], temp[1], temp[2]
preUrl := fmt.Sprintf("%s/presigned-url/presign/url", url)
payload := Url{
Filename: filename,
Type: request,
Duration: duration,
}
json, err := json.Marshal(payload)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req, err := http.NewRequest(http.MethodPost, preUrl, bytes.NewBuffer(json))
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
req.Header.Add("content-type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
bytes, err := io.ReadAll(res.Body)
if err != nil {
resp := &funcResponse{
StatusCode: http.StatusInternalServerError,
}
return resp, err
}
resp := &funcResponse{
StatusCode: res.StatusCode,
Body: string(bytes),
}
defer res.Body.Close()
return resp, nil
}
func deleteEmpty(s []string) []string {
var temp []string
for _, str := range s {
if str != "" {
temp = append(temp, str)
}
}
return temp
}
func makeRequest(in *SlackRequest, api *slack.Client) error {
code := strconv.Itoa(in.StatusCode)
attachment := slack.Attachment{
Color: "#0069ff",
Fields: []slack.AttachmentField{
{
Title: (fmt.Sprintf("Response: %s", code)),
Value: in.Content,
},
},
Footer: "DigitalOcean" + " | " + time.Now().Format("01-02-2006 3:4:5 MST"),
}
_, _, err := api.PostMessage(
channelid,
slack.MsgOptionAttachments(attachment),
slack.MsgOptionAsUser(true),
)
if err != nil {
return err
}
return nil
}