-
Notifications
You must be signed in to change notification settings - Fork 925
/
util.go
91 lines (75 loc) · 1.94 KB
/
util.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
package discordgo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"reflect"
)
// MultipartBodyWithJSON returns the contentType and body for a discord request
// data : The object to encode for payload_json in the multipart request
// files : Files to include in the request
func MultipartBodyWithJSON(data interface{}, files []*File) (requestContentType string, requestBody []byte, err error) {
body := &bytes.Buffer{}
bodywriter := multipart.NewWriter(body)
payload, err := json.Marshal(data)
if err != nil {
return
}
var p io.Writer
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", `form-data; name="payload_json"`)
h.Set("Content-Type", "application/json")
p, err = bodywriter.CreatePart(h)
if err != nil {
return
}
if _, err = p.Write(payload); err != nil {
return
}
for i, file := range files {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file%d"; filename="%s"`, i, quoteEscaper.Replace(file.Name)))
contentType := file.ContentType
if contentType == "" {
contentType = "application/octet-stream"
}
h.Set("Content-Type", contentType)
p, err = bodywriter.CreatePart(h)
if err != nil {
return
}
if _, err = io.Copy(p, file.Reader); err != nil {
return
}
}
err = bodywriter.Close()
if err != nil {
return
}
return bodywriter.FormDataContentType(), body.Bytes(), nil
}
func IsEmbedEmpty(embed *MessageEmbed) bool {
return reflect.DeepEqual(embed, &MessageEmbed{})
}
func ValidateComplexMessageEmbeds(embeds []*MessageEmbed) []*MessageEmbed {
totalNils := 0
totalEmbeds := len(embeds)
parsedEmbeds := make([]*MessageEmbed, 0, totalEmbeds)
for _, e := range embeds {
if e == nil || IsEmbedEmpty(e) {
totalNils++
} else {
if e.Type != "" {
e.Type = "rich"
}
parsedEmbeds = append(parsedEmbeds, e)
}
}
if totalEmbeds > 0 && totalNils == totalEmbeds {
return nil
}
return parsedEmbeds
}