Files
backend/bot/onMessageCreate.go
Yi-Ting Shih 47f09b733a
All checks were successful
Go test / run-go-vet (push) Successful in 20s
Go test / check-swagger-up-to-date (push) Successful in 9s
Go test / run-go-test (push) Successful in 47s
Go test / cleanup-go-test (push) Successful in 4s
Go test / release-image (push) Successful in 3m35s
Refactor: migrate discordbot
2025-12-13 04:58:12 +08:00

70 lines
1.5 KiB
Go

package bot
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"gitea.konchin.com/go2025/backend/handlers/api"
"gitea.konchin.com/go2025/backend/tracing"
"github.com/bwmarrin/discordgo"
"github.com/spf13/viper"
"go.uber.org/zap"
"golang.org/x/exp/rand"
)
func (b *Bot) fetchAliases() {
for {
var res []api.GetAliasesOutputAlias
resp, err := b.Client.R().
SetResult(&res).
Get("/bot/api/aliases")
if err == nil && resp.StatusCode() == http.StatusOK {
aliases := make(map[string]int64)
for _, alias := range res {
aliases[alias.Name] = alias.Id
}
b.aliases = aliases
tracing.Logger.Ctx(context.Background()).
Info("nmsl",
zap.String("aliases", fmt.Sprintf("%+v", aliases)))
}
time.Sleep(10 * time.Second)
}
}
func (b *Bot) onMessageCreate(
s *discordgo.Session,
m *discordgo.MessageCreate,
) {
// Ignore messages from the bot itself
if m.Author.ID == s.State.User.ID {
return
}
key := strings.ToLower(strings.TrimSpace(m.Content))
tracing.Logger.Ctx(context.Background()).
Info("wtf",
zap.String("key", key))
if id, ok := b.aliases[key]; ok {
var res []api.GetImagesOutputImage
resp, err := b.Client.R().
SetResult(&res).
SetQueryParam("aliases", strconv.FormatInt(id, 10)).
Get("/bot/api/images")
if err == nil && resp.StatusCode() == http.StatusOK {
image := res[rand.Intn(len(res))]
s.ChannelMessageSend(m.ChannelID,
fmt.Sprintf("%s/img/%d.%s",
viper.GetString("external-url"),
image.Id, image.Extension))
}
}
}