-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhooks.go
61 lines (53 loc) · 1.42 KB
/
webhooks.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
package main
import (
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/gtuk/discordwebhook"
)
// Get Discord webhook item by channel ID. If not found, create one. Finds and creates by name "FEEDBOT".
func getWebhookForChannel(channel string) (*discordgo.Webhook, error) {
webhooks, err := discord.ChannelWebhooks(channel)
if err != nil {
return nil, err
}
// Find
for _, webhook := range webhooks {
if webhook != nil {
if webhook.Name == "FEEDBOT" {
return webhook, nil
}
}
}
// Create
newWebhook, err := discord.WebhookCreate(channel, "FEEDBOT", "")
if err != nil {
return nil, err
}
return newWebhook, nil
}
// Simple function for webhook url formatting.
func getWebhookURL(webhook *discordgo.Webhook) string {
if webhook != nil {
return fmt.Sprintf("https://discord.com/api/webhooks/%s/%s", webhook.ID, webhook.Token)
}
return ""
}
// Send webhook, handle error returning, log in database if successful, identified by channel+ref.
func sendWebhook(channel string, ref string, webhookData discordwebhook.Message, module string) error {
webhook, err := getWebhookForChannel(channel)
if err != nil {
return err
}
webhookURL := getWebhookURL(webhook)
if webhookURL == "" {
return errors.New("error parsing webhook url")
} else {
if err = discordwebhook.SendMessage(webhookURL, webhookData); err != nil {
return err
} else {
refLogSent(ref, channel, module)
}
}
return nil
}