-
Notifications
You must be signed in to change notification settings - Fork 0
/
rbot.go
392 lines (311 loc) · 7.86 KB
/
rbot.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package main
import (
"encoding/json"
"fmt"
"github.com/bwmarrin/discordgo"
"io/ioutil"
"os"
"os/signal"
"strings"
"syscall"
)
/*
Type config holds all information about the bots current
servers and a path to its corresponding json file.
Config should be updated using Config.updateConfig() so changes
will be saved.
*/
type Config struct {
Token string `json:"token"`
Game string `json:"game"`
Server []ConfigServer `json:"server"`
ConfigFile string
}
/*
Type ConfigServer represents one server and holds its
Server specific settings.
*/
type ConfigServer struct {
ServerID string `json:"serverid"`
ChannelID string `json:"channelid"`
Admin string `json:"adminid"`
SecondaryAdmins []string `json:"secondary_admins"`
Roles []ConfigRoles `json:"roles"`
}
/* Type ConfigRoles holds a emoji/roleid pair */
type ConfigRoles struct {
Emoji string `json:"emoji"`
Role string `json:"role"`
}
var config Config
const configFile = "rbot.json"
func loadConfig() {
file, err := os.Open(configFile)
if err != nil {
panic(err)
}
defer file.Close()
buf, err2 := ioutil.ReadAll(file)
if err2 != nil {
panic(err2)
}
config.ConfigFile = configFile
json.Unmarshal(buf, &config)
}
func (c ConfigServer) isAdmin(userID string) bool {
if c.Admin == userID {
return true
}
for _, admin := range c.SecondaryAdmins {
if userID == admin {
return true
}
}
return false
}
func main() {
loadConfig()
discord, _ := botMain()
defer discord.Close()
// This basically waits for some Interrupt signal and then stops the bot
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
}
func botMain() (d *discordgo.Session, e error) {
discord, err := discordgo.New("Bot " + config.Token)
if err != nil {
fmt.Println("Failed to connect to discord api")
e = err
return
}
discord.AddHandler(messageCreate)
discord.AddHandler(reactionAdd)
discord.AddHandler(reactionRemove)
err = discord.Open()
if err != nil {
fmt.Println("Failed to connect to discord api")
e = err
return
}
fmt.Println("Bot is booted up and ready!")
d = discord
e = nil
return
}
// Function will be called when some message is send
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Content == "!addserver" {
config.addServer(m.Message)
}
if strings.Index(m.Content, "!addrole") == 0 {
config.addRoleToServer(m.Message)
}
if strings.Index(m.Content, "!remrole") == 0 {
config.removeRoleFromServer(m.Message)
}
if strings.Index(m.Content, "!addadmin") == 0 {
id, err := extractUserId(m.Message)
server := config.getServer(m.GuildID)
if server == nil || err != nil {
return
}
server.addSecondaryAdmin(id)
config.updateConfig()
}
if strings.Index(m.Content, "!remadmin") == 0 {
id, err := extractUserId(m.Message)
server := config.getServer(m.GuildID)
if server == nil || err != nil {
return
}
server.removeSecondaryAdmin(id)
config.updateConfig()
}
}
// Will be called when !addserver command was send
func (c *Config) addServer(m *discordgo.Message) {
if config.getServer(m.GuildID) != nil {
return // Dont add server that already exist
}
server := ConfigServer{
ServerID: m.GuildID,
ChannelID: m.ChannelID,
Roles: make([]ConfigRoles, 1),
Admin: m.Author.ID,
}
c.Server = append(c.Server, server)
c.updateConfig()
fmt.Printf("Server %v has been added to this bot.\n", server.ServerID)
}
// will be called when discord Reaction add event fires
func reactionAdd(s *discordgo.Session, m *discordgo.MessageReactionAdd) {
server := config.getServer(m.GuildID)
if server == nil {
return
}
if server.ChannelID != m.ChannelID {
return
}
for _, role := range server.Roles {
if role.Emoji == m.Emoji.Name {
fmt.Printf("Adding role %v to user %v\n", role.Role, m.UserID)
err := s.GuildMemberRoleAdd(m.GuildID, m.UserID, role.Role)
if err != nil {
fmt.Println(err)
}
}
}
}
func reactionRemove(s *discordgo.Session, m *discordgo.MessageReactionRemove) {
server := config.getServer(m.GuildID)
if server == nil {
return
}
if server.ChannelID != m.ChannelID {
return
}
for _, role := range server.Roles {
if role.Emoji == m.Emoji.Name {
fmt.Printf("Removing role %v from user %v\n", role.Role, m.UserID)
err := s.GuildMemberRoleRemove(m.GuildID, m.UserID, role.Role)
if err != nil {
fmt.Println(err)
}
}
}
}
// Update config function writes the Config struct c to a json file
func (c Config) updateConfig() {
data, err := json.Marshal(c)
if err != nil {
fmt.Printf("Failed to update config: %v\n", err)
}
file, err2 := os.Create(c.ConfigFile)
defer file.Close()
if err2 != nil {
fmt.Printf("Can't replace config file: %v\n", err2)
}
_, err2 = file.Write(data)
if err2 != nil {
fmt.Printf("Can't write to config file: %v\n", err2)
}
}
func (c *Config) getServer(id string) *ConfigServer {
for i, server := range c.Server {
if server.ServerID == id {
return &c.Server[i]
}
}
return nil
}
// GenericError is a placeholder for actual errors
type GenericError struct{}
func (g GenericError) Error() string {
return "error"
}
/*
The next 3 functions extract ids for users, roles and emojis
from a message. Discords id's are represented in a string as follows:
RoleID: <@&id>
UserID: <@!id>
EmojiID: <:name:id> Note that non custom emojis will be send as Unicode runes
*/
func extractRoleId(message *discordgo.Message) (s string, e error) {
i := strings.Index(message.Content, "<@&")
if i == -1 {
e = GenericError{}
return
}
slice := message.Content[i+3:]
j := strings.Index(slice, ">")
if j == -1 {
e = GenericError{}
return
}
s = slice[:j]
return
}
func extractUserId(message *discordgo.Message) (s string, e error) {
i := strings.Index(message.Content, "<@!")
if i == -1 {
e = GenericError{}
return
}
slice := message.Content[i+3:]
j := strings.Index(slice, ">")
if j == -1 {
e = GenericError{}
return
}
s = slice[:j]
return
}
func extractEmojiName(message *discordgo.Message) (s string, e error) {
i := strings.Index(message.Content, "<:")
if i == -1 {
e = GenericError{}
return
}
slice := message.Content[i+2:]
j := strings.Index(slice, ":")
if j == -1 {
e = GenericError{}
return
}
s = slice[:j]
return
}
func (c *Config) addRoleToServer(message *discordgo.Message) error {
id, err := extractRoleId(message)
server := c.getServer(message.GuildID)
emoji, err2 := extractEmojiName(message)
if err != nil || err2 != nil || server == nil {
return GenericError{}
}
roles := ConfigRoles{
Emoji: emoji,
Role: id,
}
if server.isAdmin(message.Author.ID) {
server.Roles = append(server.Roles, roles)
c.updateConfig()
}
return nil
}
func (c *Config) removeRoleFromServer(message *discordgo.Message) error {
id, err := extractRoleId(message)
server := c.getServer(message.GuildID)
if err != nil || server == nil {
return GenericError{}
}
if !server.isAdmin(message.Author.ID) {
fmt.Println("Permission denied")
return GenericError{}
}
for j, role := range server.Roles {
if role.Role == id {
fmt.Printf("Deleting role %v from server\n", id)
server.Roles[len(server.Roles)-1], server.Roles[j] =
server.Roles[j], server.Roles[len(server.Roles)-1]
server.Roles = server.Roles[:len(server.Roles)-1]
c.updateConfig()
return nil
}
}
return GenericError{}
}
func (c *ConfigServer) addSecondaryAdmin(userID string) error {
c.SecondaryAdmins = append(c.SecondaryAdmins, userID)
return nil
}
func (c *ConfigServer) removeSecondaryAdmin(userID string) error {
for i, id := range c.SecondaryAdmins {
if id == userID {
c.SecondaryAdmins[i], c.SecondaryAdmins[len(c.SecondaryAdmins)-1] =
c.SecondaryAdmins[len(c.SecondaryAdmins)-1], c.SecondaryAdmins[i]
c.SecondaryAdmins = c.SecondaryAdmins[:len(c.SecondaryAdmins)-1]
}
}
return nil
}