-
Notifications
You must be signed in to change notification settings - Fork 3
/
messages-api.go
69 lines (56 loc) · 1.5 KB
/
messages-api.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
package corde
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"github.com/Karitham/corde/internal/rest"
)
// returns the content-type
func toBodyMessage(w io.Writer, m Message) (string, error) {
contentType := "application/json"
payloadJSON := &bytes.Buffer{}
err := json.NewEncoder(payloadJSON).Encode(m)
if err != nil {
return "", err
}
if len(m.Attachments) < 1 {
payloadJSON.WriteTo(w)
return contentType, nil
}
mw := multipart.NewWriter(w)
defer mw.Close()
contentType = mw.FormDataContentType()
mw.WriteField("payload_json", payloadJSON.String())
if err := writeAttachments(mw, m.Attachments); err != nil {
return contentType, err
}
return contentType, nil
}
// CreateMessage creates a new message in a channel
//
// https://discord.com/developers/docs/resources/channel#create-message
func (m *Mux) CreateMessage(channelID Snowflake, data Message) (*Message, error) {
body := &bytes.Buffer{}
contentType, err := toBodyMessage(body, data)
if err != nil {
return nil, err
}
resp, err := m.Client.Do(
rest.Req("/channels", channelID, "messages").
AnyBody(body).Post(m.authorize, rest.ContentType(contentType)),
)
if err != nil {
return nil, fmt.Errorf("failed to create message: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
anyerr := map[string]any{}
json.NewDecoder(resp.Body).Decode(&anyerr)
return nil, fmt.Errorf("failed to create message: %+v", anyerr)
}
msg := &Message{}
json.NewDecoder(resp.Body).Decode(msg)
return msg, nil
}