aboutsummaryrefslogtreecommitdiff
path: root/web
diff options
context:
space:
mode:
authorChristine Dodrill <me@christine.website>2018-10-05 08:29:57 -0700
committerChristine Dodrill <me@christine.website>2018-10-05 08:29:57 -0700
commit79d5cac32717b3444454f0849bc2e7816351d39a (patch)
treeb1b4a4d9e824f40fea4306af6bc8b643c607468a /web
parentad9c6f3ebf7c2f112f958cc952965e6173020651 (diff)
downloadx-79d5cac32717b3444454f0849bc2e7816351d39a.tar.xz
x-79d5cac32717b3444454f0849bc2e7816351d39a.zip
genericize discord webhook code
Diffstat (limited to 'web')
-rw-r--r--web/discordwebhook/webhook.go71
1 files changed, 71 insertions, 0 deletions
diff --git a/web/discordwebhook/webhook.go b/web/discordwebhook/webhook.go
new file mode 100644
index 0000000..152ec74
--- /dev/null
+++ b/web/discordwebhook/webhook.go
@@ -0,0 +1,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
+}