/
dbot.go
73 lines (62 loc) · 1.59 KB
/
dbot.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
/*
* @Author: SpenserCai
* @Date: 2023-08-16 11:06:01
* @version:
* @LastEditors: SpenserCai
* @LastEditTime: 2023-10-16 21:09:08
* @Description: file content
*/
package dbot
import (
"log"
"os"
"os/signal"
"time"
"github.com/bwmarrin/discordgo"
)
type DiscordBot struct {
AppCommands []*discordgo.ApplicationCommand
RegisteredCommands []*discordgo.ApplicationCommand
Session *discordgo.Session
ServerID string
SlashHandlerMap map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)
}
func NewDiscordBot(token string, serverID string) (*DiscordBot, error) {
session, err := discordgo.New("Bot " + token)
if err != nil {
return nil, err
}
session.Client.Timeout = 120 * time.Second
dbot := &DiscordBot{
Session: session,
ServerID: serverID,
SlashHandlerMap: make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)),
AppCommands: make([]*discordgo.ApplicationCommand, 0),
}
// 预存长选项
dbot.SetLongChoice()
// 生成命令列表
dbot.GenerateCommandList()
dbot.SetLocation()
// 根据命令列表生成Handler
dbot.GenerateSlashMap()
dbot.Session.AddHandler(dbot.Ready)
dbot.Session.AddHandler(dbot.InteractionCreate)
return dbot, nil
}
func (d *DiscordBot) Run() {
err := d.Session.Open()
if err != nil {
log.Println(err)
return
}
d.SyncCommands()
d.SetBaseCommandHelperInfo()
defer d.Session.Close()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Println("Press Ctrl+C to exit")
<-stop
//d.RemoveCommand()
log.Println("Gracefully shutting down.")
}