-
Notifications
You must be signed in to change notification settings - Fork 3
/
webhook.go
75 lines (62 loc) · 1.88 KB
/
webhook.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
package internal
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/WelcomerTeam/Discord/discord"
)
// Embed colours for webhooks.
const (
EmbedColourSandwich = 16701571
EmbedColourWarning = 16760839
EmbedColourDanger = 14431557
WebhookRateLimitDuration = 5 * time.Second
WebhookRateLimitLimit = 5
)
// PublishSimpleWebhook is a helper function for creating quicker webhook messages.
func (sg *Sandwich) PublishSimpleWebhook(title string, description string, footer string, colour int32) {
now := time.Now().UTC()
sg.PublishWebhook(discord.WebhookMessageParams{
Embeds: []*discord.Embed{
{
Title: title,
Description: description,
Color: colour,
Timestamp: &now,
Footer: &discord.EmbedFooter{
Text: footer,
},
},
},
})
}
// PublishWebhook sends a webhook message to all added webhooks in the configuration.
func (sg *Sandwich) PublishWebhook(message discord.WebhookMessageParams) {
for _, webhook := range sg.Configuration.Webhooks {
_, err := sg.SendWebhook(webhook, message)
if err != nil && !errors.Is(err, context.Canceled) {
sg.Logger.Warn().Err(err).Str("url", webhook).Msg("Failed to send webhook")
}
}
}
func (sg *Sandwich) SendWebhook(webhookURL string, message discord.WebhookMessageParams) (status int, err error) {
webhookURL = strings.TrimSpace(webhookURL)
_, err = url.Parse(webhookURL)
if err != nil {
return -1, fmt.Errorf("failed to parse webhook URL: %w", err)
}
res, err := json.Marshal(message)
if err != nil {
return -1, fmt.Errorf("failed to marshal webhook message: %w", err)
}
_ = sg.webhookBuckets.CreateWaitForBucket(webhookURL, WebhookRateLimitLimit, WebhookRateLimitDuration)
_, status, err = sg.Client.Fetch(sg.ctx, "POST", webhookURL, bytes.NewBuffer(res), map[string]string{
"Content-Type": "application/json",
})
return status, err
}