discordBots/cmd/dealsbot/main.go

119 lines
2.8 KiB
Go
Raw Normal View History

2023-01-26 00:28:18 +00:00
package main
2023-03-04 11:54:08 +00:00
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"
"os"
"os/signal"
"reflect"
"syscall"
"time"
)
var (
webhookID = snowflake.GetEnv("webhook_id")
webhookToken = os.Getenv("webhook_token")
)
2023-01-26 00:28:18 +00:00
func main() {
// query different sources store to db
2023-03-04 11:54:08 +00:00
// try to incorporate operagx apiUrl:
// - https://gx-proxy.operacdn.com/content/free-games?_limit=300&_sort=order%3AASC
2023-01-26 00:28:18 +00:00
// send messages to discord
2023-03-04 11:54:08 +00:00
// ideas:
// - https://github.com/TheLovinator1/discord-free-game-notifier
// - https://gg.deals/news/free-gog-games/
// - origin
// - check ubisoft works
2023-03-06 18:02:40 +00:00
log.SetLevel(log.LevelInfo)
2023-03-04 11:54:08 +00:00
log.Info("starting dealsbot...")
log.Info("disgo version: ", disgo.Version)
client := webhook.New(webhookID, webhookToken)
defer client.Close(context.TODO())
repo := 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:
var apis []Api
apis = append(apis, newUbsioftApi(), newEpicApi(), newSteamApi(), newGogApi(), newHumbleBundleApi())
for _, api := range apis {
err := api.load()
if err != nil {
log.Error(err)
}
}
var deals []Deal
for _, api := range apis {
apiDeals := api.get()
deals = append(deals, apiDeals...)
}
for _, deal := range deals {
retrievedDeal, _ := repo.GetValue(deal.Id)
if deal.Id == retrievedDeal.Id {
log.Debugf("%v is already published", deal.Id)
} else if reflect.DeepEqual(deal, retrievedDeal) {
log.Errorf("%v is published but not equal", deal.Id)
} else {
log.Infof("%v is new and will be published", deal.Id)
go sendWebhook(client, deal)
err := repo.SetValue(deal)
if err != nil {
log.Error(err)
}
}
}
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("dealsbot 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, deal Deal) {
var status string
status = fmt.Sprintf("currently free: %v\n", deal.Url)
if _, err := client.CreateMessage(discord.NewWebhookMessageCreateBuilder().
SetContent(status).Build(),
rest.WithDelay(2*time.Second),
); err != nil {
log.Errorf("error sending message %v", err.Error())
}
2023-01-26 00:28:18 +00:00
}