/
bot.go
111 lines (95 loc) · 2.66 KB
/
bot.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package common
import (
"errors"
"fmt"
"github.com/anhgelus/discord-bots/common/utils"
"github.com/bwmarrin/discordgo"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
var (
Debug bool
ErrBadStatusType = errors.New("bad status type, please use the constant")
ErrStatusUrlNotFound = errors.New("status url not found")
)
const (
GameStatus = 0
WatchStatus = 1
StreamingStatus = 2
ListeningStatus = 3
AdminPermission int64 = discordgo.PermissionManageServer // AdminPermission of the command
)
// Bot is the representation of a discord bot
type Bot struct {
Token string // Token of the Bot
Status []*Status // Status of the Bot
Commands []*Cmd // Commands of the Bot
Handlers []interface{} // Handlers of the Bot
}
// Status contains all required information for updating the status
type Status struct {
Type int // Type of the Status (use GameStatus or WatchStatus or StreamingStatus or ListeningStatus)
Content string // Content of the Status
Url string // Url of the StreamingStatus
}
// Start the Bot
func (b *Bot) Start() {
dg, err := discordgo.New("Bot " + b.Token) // Define connection to discord API with bot token
if err != nil {
utils.SendAlert("bot.go - Token", err.Error())
}
err = dg.Open() // Bot start
if err != nil {
utils.SendAlert("bot.go - Start", err.Error())
}
go func() {
time.Sleep(30 * time.Second)
utils.SendSuccess(fmt.Sprintf("Bot started as %s", dg.State.User.Username))
utils.NewTimers(30*time.Second, func(_ chan struct{}) {
rand.NewSource(time.Now().Unix())
r := rand.Intn(len(b.Status))
s := b.Status[r]
if s.Type == GameStatus {
err = dg.UpdateGameStatus(0, s.Content)
} else if s.Type == WatchStatus {
err = dg.UpdateWatchStatus(0, s.Content)
} else if s.Type == StreamingStatus {
if s.Url == "" {
err = ErrStatusUrlNotFound
} else {
err = dg.UpdateStreamingStatus(0, s.Content, s.Url)
}
} else if s.Type == ListeningStatus {
err = dg.UpdateListeningStatus(s.Content)
} else {
err = ErrBadStatusType
}
if err != nil {
utils.SendAlert("bot.go - Update status", err.Error())
err = nil
}
})
}()
go func() {
b.registerCommands(dg)
utils.SendSuccess("Commands registered")
}()
b.setupCommandsHandlers(dg)
for h := range b.Handlers {
dg.AddHandler(h)
}
dg.Identify.Intents = discordgo.IntentsAll
dg.StateEnabled = true
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
utils.SendDebug("Unregistering local commands")
b.unregisterCommands(dg)
err = dg.Close() // Bot Shutdown
if err != nil {
utils.SendAlert("bot.go - Shutdown", err.Error())
}
}