-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
216 lines (191 loc) · 4.81 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// discordBot project main.go
package main
import (
"flag"
"os"
"os/signal"
"path/filepath"
"strconv"
"sync"
"syscall"
"github.com/bwmarrin/discordgo"
"github.com/matamegger/discordBot/logging"
)
const (
RELATIVE_SETTINGS_PATH = "settings"
RELATIVE_SOUNDS_PATH = "sounds"
SETTINGS_FILE = "settings.json"
BOT_NAME = "JoinBot"
MAX_QUEUE_SIZE = 5
BUILD = 2
)
var (
log *logging.Logger
OWNER string
BASEPATH string
exit chan bool
commands []command
foreignCommand bool
foreignCommandUser []string
foreignCommandType string
data Settings
playQueue map[string]chan *Play
queueLock sync.RWMutex
)
type Settings struct {
Soundcollections map[string]*SoundCollection `json:"soundcollections"`
Build int `json:"build"`
sclock sync.RWMutex `json:"-"`
changed bool `json:"-"`
}
type commandFunc func(*discordgo.Session, *discordgo.Message, []string)
type command struct {
Command string
Function commandFunc
}
func (d *Settings) prepareAndLoad() {
log.Info("Loading ")
data.sclock.Lock()
defer data.sclock.Unlock()
if d.Soundcollections == nil {
d.Soundcollections = make(map[string]*SoundCollection)
} else {
for _, c := range d.Soundcollections {
c.Load()
}
}
}
func initalize() {
ex, err := os.Executable()
if err == nil {
BASEPATH = filepath.Dir(ex)
}
addCommand("kill", Kill)
addCommand("get", Get)
addCommand("owner", WhoIsOwner)
addCommand("master", WhoIsOwner)
addCommand("set", Set)
addCommand("addsound", AddSound)
addCommand("sounds", SoundsHelp)
addCommand("play", PlayGame)
playQueue = make(map[string]chan *Play)
loadSettings()
data.prepareAndLoad()
}
func main() {
log = logging.NewLogger("discord_bot", os.Stdout, os.Stderr)
log.Info("Starting")
var (
Token = flag.String("t", "", "Discord Authentication Token")
Owner = flag.String("o", "", "Owner")
err error
)
flag.Parse()
if *Owner != "" {
OWNER = *Owner
} else {
log.Warning("Owner ID is not set!")
log.Notice("Set the owner ID with the -o parameter")
}
if *Token == "" {
log.Error("Token ID is not set!")
return
}
initalize()
discord, err := SetupDiscordConnectionAndListener(*Token)
if err != nil {
return
}
//-------------------------
// Closing
//-------------------------
// Wait for a signal to quit
c := make(chan os.Signal, 1)
exit = make(chan bool, 1)
signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)
go func() {
log.Debugf("Signal: %s", <-c)
exit <- true
}()
<-exit
log.Debug("Closing discord connection...")
err = discord.Close()
if err != nil {
log.Errorf("Error closing discord connection > %s", err)
}
saveSettings()
log.Info("Shutdown down")
}
//Creates a session, adds listeners and starts the session
func SetupDiscordConnectionAndListener(token string) (discord *discordgo.Session, err error) {
log.Debugf("Creating Bot with token=%s", token)
discord, err = discordgo.New("Bot " + token)
if err != nil {
log.Errorf("Error creating discord session > %s", err)
return
}
// Register Handler
discord.AddHandler(onMessageCreate)
discord.AddHandler(onReady)
discord.AddHandler(onGuildCreate)
// Open the websocket and begin listening.
err = discord.Open()
if err != nil {
log.Errorf("Error opening discord connection > %s", err)
}
return
}
func onReady(s *discordgo.Session, event *discordgo.Ready) {
//Set status
var status string
if BUILD > data.Build {
data.Build = BUILD
data.changed = true
status = "Updated to " + strconv.Itoa(BUILD)
} else {
status = "Lurking around"
}
log.Infof("Set status to: %s", status)
s.UpdateStatus(0, status)
}
func onMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if len(m.Content) > 0 && m.Content[0] == '!' {
m.Content = m.Content[1:]
processCommand(s, m.Message)
} else if len(m.Mentions) < 1 {
}
if foreignCommand {
onForeignCommand(s, m.Message)
}
}
func onGuildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
log.Debugf("Guild created: %s", event.Name)
//TODO
}
func loadSettings() {
cFile := filepath.Join(BASEPATH, RELATIVE_SETTINGS_PATH, SETTINGS_FILE)
exist, _ := exists(cFile)
if !exist {
log.Debug("Can't load settings, because the file does not exist.")
return
}
var d Settings
err := LoadObjectFromJsonFile(cFile, &d)
if err != nil {
log.Errorf("Error loading settings > %s", err)
}
data = d
}
func saveSettings() {
if !data.changed {
return
}
cFile := filepath.Join(BASEPATH, RELATIVE_SETTINGS_PATH, SETTINGS_FILE)
log.Debugf("Saving settings at: %s", cFile)
data.sclock.RLock()
defer data.sclock.RUnlock()
err := SaveObjectAsJsonToFile(cFile, &data)
if err != nil {
log.Error("Error saving settings")
}
}