/
run.go
89 lines (74 loc) · 2.02 KB
/
run.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
package minidis
import (
"fmt"
"log"
"os"
"os/signal"
"github.com/bwmarrin/discordgo"
)
// Run executes the command handler.
func (m *Minidis) Run() error {
return run(m)
}
// Execute the bot.
// It is similar to `Run()` function of `Minidis` struct.
func Execute(bot *Minidis) error {
return run(bot)
}
// main bot command handler
func run(m *Minidis) error {
m.session.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
switch i.Type {
case discordgo.InteractionApplicationCommand:
err, exists := m.executeSlash(s, i.Interaction)
if err != nil {
log.Printf("failed to execute slash command: %v\n", err)
}
if exists {
break
}
err, exists = m.executeUser(s, i.Interaction)
if err != nil {
log.Printf("failed to execute user command: %v\n", err)
}
if exists {
break
}
if err, _ := m.executeMessage(s, i.Interaction); err != nil {
log.Printf("failed to execute message command: %v\n", err)
}
case discordgo.InteractionMessageComponent:
if err := m.executeComponentHandler(s, i.Interaction); err != nil {
log.Printf("failed to execute component handler: %v\n", err)
}
case discordgo.InteractionModalSubmit:
if err := m.executeModalSubmit(s, i.Interaction); err != nil {
log.Printf("failed to execute modal submit handler: %v\n", err)
}
default:
}
})
// try to open websocket
if err := m.session.Open(); err != nil {
return fmt.Errorf("cannot open session: %v", err)
}
// set app id
m.AppID = m.session.State.User.ID
if m.customHandlers.onBeforeStart != nil {
// call beforeStart wrapper if not nil
m.customHandlers.onBeforeStart(m.session)
}
// sync commands internally
if err := m.syncCommands(m.guilds); err != nil {
return fmt.Errorf("failed to sync commands: %v", err)
}
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
<-sc
if m.customHandlers.onClose != nil {
// call onClose wrapper if not nil
m.customHandlers.onClose(m.session)
}
// Close the websocket as final.
return m.session.Close()
}