Files
backend/bot/onMessageCreate.go
Yi-Ting Shih 7c89c0a144
All checks were successful
Go test / run-go-vet (push) Successful in 6s
Go test / check-swagger-up-to-date (push) Successful in 11s
Go test / run-go-test (push) Successful in 23s
Go test / cleanup-go-test (push) Successful in 4s
Go test / release-image (push) Successful in 3m37s
Chore: trim debug message
2025-12-13 06:35:29 +08:00

60 lines
1.2 KiB
Go

package bot
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
"gitea.konchin.com/go2025/backend/handlers/api"
"github.com/bwmarrin/discordgo"
"github.com/spf13/viper"
"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
}
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))
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))
}
}
}