aboutsummaryrefslogtreecommitdiff
path: root/web/discordwebhook/webhook.go
blob: 152ec749f86a6bfda04b4e1201a897340d5144a7 (plain)
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
package discordwebhook

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// Webhook is the parent structure fired off to Discord.
type Webhook struct {
	Content   string   `json:"content,omitifempty"`
	Username  string   `json:"username"`
	AvatarURL string   `json:"avatar_url"`
	Embeds    []Embeds `json:"embeds,omitifempty"`
}

// EmbedField is an individual field being embedded in a message.
type EmbedField struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Inline bool   `json:"inline"`
}

// EmbedFooter is the message footer.
type EmbedFooter struct {
	Text    string `json:"text"`
	IconURL string `json:"icon_url"`
}

// Embeds is a set of embed fields and a footer.
type Embeds struct {
	Fields []EmbedField `json:"fields"`
	Footer EmbedFooter  `json:"footer"`
}

// Send returns a request for a Discord webhook.
func Send(whurl string, w Webhook) *http.Request {
	if len(w.Username) > 32 {
		w.Username = w.Username[:32]
	}

	data, err := json.Marshal(&w)
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest(http.MethodPost, whurl, bytes.NewBuffer(data))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/json")

	return req
}

// Validate validates the response from Discord.
func Validate(resp *http.Response) error {
	if resp.StatusCode/100 != 2 {
		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		resp.Body.Close()
		return fmt.Errorf("status code was %v: %s", resp.StatusCode, string(data))
	}

	return nil
}