discordBots/cmd/domaincheckbot/main.go

99 lines
2.4 KiB
Go
Raw Normal View History

package main
import (
"context"
"errors"
"fmt"
"github.com/dgraph-io/badger/v4"
"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/rest"
"github.com/disgoorg/disgo/webhook"
"github.com/disgoorg/log"
"github.com/disgoorg/snowflake/v2"
"grow.rievo.dev/discordBots/cmd/domaincheckbot/config"
"grow.rievo.dev/discordBots/cmd/domaincheckbot/dns"
"grow.rievo.dev/discordBots/cmd/domaincheckbot/repository"
"os"
"os/signal"
"reflect"
"syscall"
"time"
)
var (
webhookID = snowflake.GetEnv("webhook_id")
webhookToken = os.Getenv("webhook_token")
)
// TODO: clear db from domains removed from json
func main() {
log.SetLevel(log.LevelInfo)
log.Info("starting domainCheck...")
log.Info("disgo version: ", disgo.Version)
client := webhook.New(webhookID, webhookToken)
defer client.Close(context.TODO())
repo := repository.InitDb()
defer repo.Close()
ticker := time.NewTicker(10 * time.Minute)
tickerGC := time.NewTicker(15 * time.Minute)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
for _, d := range config.Domains {
domain := dns.CheckDomain(d)
retrievedDomain, _ := repo.GetValue(d)
if reflect.DeepEqual(domain, retrievedDomain) {
log.Debugf(" %v: did not change", d)
} else {
log.Infof("!%v: changed", d)
go sendWebhook(client, domain, retrievedDomain)
repo.SetValue(domain)
}
}
case <-tickerGC.C:
err := repo.RunGC()
if err != nil && !errors.Is(err, badger.ErrNoRewrite) {
log.Errorf("error with GC: %v", err)
} else {
log.Debug("GC successful")
}
case <-quit:
ticker.Stop()
tickerGC.Stop()
return
}
}
}()
log.Infof("domainCheck is now running. Press CTRL-C to exit.")
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-s
}
func sendWebhook(client webhook.Client, domain repository.Domain, oldDomain repository.Domain) {
var status string
status = fmt.Sprintf("```md\n# %v", domain.Name)
status = fmt.Sprintf("%v\n - %v", status, oldDomain.NS)
status = fmt.Sprintf("%v\n + %v", status, domain.NS)
status = fmt.Sprintf("%v```\n", status)
if _, err := client.CreateMessage(discord.NewWebhookMessageCreateBuilder().
SetContent(status).Build(),
rest.WithDelay(2*time.Second),
); err != nil {
log.Errorf("error sending message %v", err.Error())
}
}