forked from nekomeowww/insights-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discordbot.go
92 lines (72 loc) · 1.9 KB
/
discordbot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package discordbot
import (
"context"
"crypto/ed25519"
"errors"
"net"
"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/bot"
"github.com/disgoorg/disgo/httpserver"
"github.com/leohearts/insights-bot-kimichat/internal/configs"
"github.com/leohearts/insights-bot-kimichat/pkg/logger"
"github.com/samber/lo"
"go.uber.org/zap"
)
type BotService struct {
bot.Client
logger *logger.Logger
webhookStarted bool
}
func NewBotService[E bot.Event](
f func(e E),
cfg configs.SectionDiscord,
logger *logger.Logger,
) *BotService {
discordBot := &BotService{
logger: logger,
}
port := lo.Ternary(cfg.Port == "", "7072", cfg.Port)
client, err := disgo.New(
cfg.Token,
bot.WithHTTPServerConfigOpts(
cfg.PublicKey,
httpserver.WithAddress(net.JoinHostPort("", port)),
httpserver.WithURL("/discord/command/smr"),
),
bot.WithEventListenerFunc(f),
)
if err != nil {
logger.Fatal("discord: failed to create bot instance", zap.Error(err))
}
discordBot.Client = client
return discordBot
}
func (b *BotService) SetLogger(logger *logger.Logger) {
b.logger = logger
}
func (b *BotService) Check(ctx context.Context) error {
return lo.Ternary(b.webhookStarted, nil, errors.New("discord bot service is not started yet"))
}
func (b *BotService) Run() error {
// use custom ed25519 verify implementation.
// this code is from examples of disgoorg/disgo.
httpserver.Verify = func(publicKey httpserver.PublicKey, message, sig []byte) bool {
return ed25519.Verify(publicKey, message, sig)
}
b.logger.Info("discord: registering commands...")
_, err := b.Rest().SetGlobalCommands(b.ApplicationID(), commands)
if err != nil {
return err
}
b.logger.Info("discord: starting webhook server...")
err = b.OpenHTTPServer()
if err != nil {
return err
}
b.webhookStarted = true
return nil
}
func (b *BotService) Stop(ctx context.Context) {
b.logger.Info("discord: shutting down...")
b.Close(ctx)
}