Replace webhook with discordgo

This commit is contained in:
ekzyis 2023-04-25 01:57:37 +02:00
parent 6010e47dde
commit b2b957e5c3
3 changed files with 27 additions and 65 deletions

View File

@ -1,3 +1,3 @@
SN_AUTH_COOKIE= SN_AUTH_COOKIE=
DISCORD_WEBHOOK=
DISCORD_TOKEN= DISCORD_TOKEN=
DISCORD_CHANNEL_ID=

View File

@ -1,12 +1,9 @@
package main package main
import ( import (
"bytes"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"log" "log"
"net/http"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
@ -15,55 +12,31 @@ import (
) )
var ( var (
DiscordWebhook string DiscordToken string
DiscordToken string DiscordClient *discordgo.Session
DiscordClient *discordgo.Session DiscordChannelId string
) )
type DiscordEmbedFooter struct {
Text string `json:"text"`
IconUrl string `json:"icon_url"`
}
type DiscordEmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline"`
}
type DiscordEmbed struct {
Title string `json:"title"`
Url string `json:"url"`
Color int `json:"color"`
Footer DiscordEmbedFooter `json:"footer"`
Timestamp string `json:"timestamp"`
Fields []DiscordEmbedField `json:"fields"`
}
type DiscordWebhookPayload struct {
Embeds []DiscordEmbed `json:"embeds"`
}
func init() { func init() {
err := godotenv.Load() err := godotenv.Load()
if err != nil { if err != nil {
log.Fatal("Error loading .env file") log.Fatal("Error loading .env file")
} }
flag.StringVar(&DiscordWebhook, "DISCORD_WEBHOOK", "", "Webhook to send logs to discord")
flag.StringVar(&DiscordToken, "DISCORD_TOKEN", "", "Discord bot token") flag.StringVar(&DiscordToken, "DISCORD_TOKEN", "", "Discord bot token")
flag.StringVar(&DiscordChannelId, "DISCORD_CHANNEL_ID", "", "Discord channel id")
flag.Parse() flag.Parse()
if DiscordWebhook == "" {
log.Fatal("DISCORD_WEBHOOK not set")
}
if DiscordToken == "" { if DiscordToken == "" {
log.Fatal("DISCORD_TOKEN not set") log.Fatal("DISCORD_TOKEN not set")
} }
if DiscordChannelId == "" {
log.Fatal("DISCORD_CHANNEL_ID not set")
}
initBot() initBot()
} }
func initBot() { func initBot() {
var err error var err error
DiscordClient, err = discordgo.New(DiscordToken) DiscordClient, err = discordgo.New("Bot " + DiscordToken)
if err != nil { if err != nil {
log.Fatal("error creating discord session:", err) log.Fatal("error creating discord session:", err)
} }
@ -102,69 +75,57 @@ func onMessage(s *discordgo.Session, m *discordgo.MessageCreate) {
func SendDupesErrorToDiscord(dupesErr *DupesError) { func SendDupesErrorToDiscord(dupesErr *DupesError) {
title := fmt.Sprintf("%d dupe(s) found for %s:", len(dupesErr.Dupes), dupesErr.Url) title := fmt.Sprintf("%d dupe(s) found for %s:", len(dupesErr.Dupes), dupesErr.Url)
color := 0xffc107 color := 0xffc107
var fields []DiscordEmbedField var fields []*discordgo.MessageEmbedField
for _, dupe := range dupesErr.Dupes { for _, dupe := range dupesErr.Dupes {
fields = append(fields, fields = append(fields,
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Title", Name: "Title",
Value: dupe.Title, Value: dupe.Title,
Inline: false, Inline: false,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Id", Name: "Id",
Value: StackerNewsItemLink(dupe.Id), Value: StackerNewsItemLink(dupe.Id),
Inline: true, Inline: true,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Url", Name: "Url",
Value: dupe.Url, Value: dupe.Url,
Inline: true, Inline: true,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "User", Name: "User",
Value: dupe.User.Name, Value: dupe.User.Name,
Inline: true, Inline: true,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Created", Name: "Created",
Value: humanize.Time(dupe.CreatedAt), Value: humanize.Time(dupe.CreatedAt),
Inline: true, Inline: true,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Sats", Name: "Sats",
Value: fmt.Sprint(dupe.Sats), Value: fmt.Sprint(dupe.Sats),
Inline: true, Inline: true,
}, },
DiscordEmbedField{ &discordgo.MessageEmbedField{
Name: "Comments", Name: "Comments",
Value: fmt.Sprint(dupe.NComments), Value: fmt.Sprint(dupe.NComments),
Inline: true, Inline: true,
}, },
) )
} }
embed := DiscordEmbed{ embed := discordgo.MessageEmbed{
Title: title, Title: title,
Color: color, Color: color,
Fields: fields, Fields: fields,
} }
SendEmbedToDiscord(embed) SendEmbedToDiscord(&embed)
} }
func SendEmbedToDiscord(embed DiscordEmbed) { func SendEmbedToDiscord(embed *discordgo.MessageEmbed) {
bodyJSON, err := json.Marshal( _, err := DiscordClient.ChannelMessageSendEmbed(DiscordChannelId, embed)
DiscordWebhookPayload{
Embeds: []DiscordEmbed{embed},
},
)
if err != nil { if err != nil {
log.Fatal("Error during json.Marshal:", err) log.Fatal("Error during json.Marshal:", err)
} }
req, err := http.NewRequest("POST", DiscordWebhook, bytes.NewBuffer(bodyJSON))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Discord webhook error:", err)
}
defer resp.Body.Close()
} }

11
sn.go
View File

@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/namsral/flag" "github.com/namsral/flag"
@ -236,15 +237,15 @@ func SendStackerNewsEmbedToDiscord(title string, id int) {
Timestamp := time.Now().Format(time.RFC3339) Timestamp := time.Now().Format(time.RFC3339)
url := StackerNewsItemLink(id) url := StackerNewsItemLink(id)
color := 0xffc107 color := 0xffc107
embed := DiscordEmbed{ embed := discordgo.MessageEmbed{
Title: title, Title: title,
Url: url, URL: url,
Color: color, Color: color,
Footer: DiscordEmbedFooter{ Footer: &discordgo.MessageEmbedFooter{
Text: "Stacker News", Text: "Stacker News",
IconUrl: "https://stacker.news/favicon.png", IconURL: "https://stacker.news/favicon.png",
}, },
Timestamp: Timestamp, Timestamp: Timestamp,
} }
SendEmbedToDiscord(embed) SendEmbedToDiscord(&embed)
} }