-
Notifications
You must be signed in to change notification settings - Fork 2
/
cmd.go
653 lines (558 loc) · 15.7 KB
/
cmd.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package gidbig
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
humanize "github.com/dustin/go-humanize"
"github.com/toksikk/gidbig/pkg/cfg"
"github.com/toksikk/gidbig/pkg/gbploader"
"github.com/toksikk/gidbig/pkg/util"
)
var (
// discordgo session
discord *discordgo.Session
// Config struct to pass around
conf *cfg.Config
// mutex for checking if voice connection already exists
mutex = &sync.Mutex{}
)
var (
// Map of Guild id's to *Play channels, used for queuing and rate-limiting guilds
queues = make(map[string]chan *Play)
// bitrate Sound encoding settings
// bitrate = 128
// maxQueueSize Sound encoding settings
maxQueueSize = 6
)
// COLLECTIONS all collections
var COLLECTIONS []*soundCollection
// Create collections
func createCollections() {
files, _ := os.ReadDir("./audio")
for _, f := range files {
if strings.Contains(f.Name(), ".dca") {
soundfile := strings.Split(strings.Replace(f.Name(), ".dca", "", -1), "_")
containsPrefix := false
containsSound := false
if len(COLLECTIONS) == 0 {
addNewSoundCollection(soundfile[0], soundfile[1])
}
for _, c := range COLLECTIONS {
if c.Prefix == soundfile[0] {
containsPrefix = true
for _, sound := range c.Sounds {
if sound.Name == soundfile[1] {
containsSound = true
}
}
if !containsSound {
c.Sounds = append(c.Sounds, createSound(soundfile[1], 1, 250))
}
}
}
if !containsPrefix {
addNewSoundCollection(soundfile[0], soundfile[1])
}
}
}
}
func addNewSoundCollection(prefix string, soundname string) {
var SC = &soundCollection{
Prefix: prefix,
Commands: []string{
"!" + prefix,
},
Sounds: []*soundClip{
createSound(soundname, 1, 250),
},
}
COLLECTIONS = append(COLLECTIONS, SC)
}
// Create a Sound struct
func createSound(Name string, Weight int, PartDelay int) *soundClip {
return &soundClip{
Name: Name,
Weight: Weight,
PartDelay: PartDelay,
buffer: make([][]byte, 0),
}
}
// Load soundcollection
func (sc *soundCollection) Load() {
for _, sound := range sc.Sounds {
sc.soundRange += sound.Weight
err := sound.Load(sc)
if err != nil {
slog.Error("error adding sound to soundCollection", "Error", err)
}
}
}
// Random select sound
func (sc *soundCollection) Random() *soundClip {
var (
i int
number = util.RandomRange(0, sc.soundRange)
)
for _, sound := range sc.Sounds {
i += sound.Weight
if number < i {
return sound
}
}
return nil
}
// Load attempts to load an encoded sound file from disk
// DCA files are pre-computed sound files that are easy to send to Discord.
// If you would like to create your own DCA files, please use:
// https://github.com/nstafie/dca-rs
// eg: dca-rs --raw -i <input wav file> > <output file>
func (s *soundClip) Load(c *soundCollection) error {
path := fmt.Sprintf("audio/%v_%v.dca", c.Prefix, s.Name)
file, err := os.Open(path)
if err != nil {
slog.Error("error opening dca file", "error", err)
return err
}
var opuslen int16
for {
// read opus frame length from dca file
err = binary.Read(file, binary.LittleEndian, &opuslen)
// If this is the end of the file, just return
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil
}
if err != nil {
slog.Error("error reading from dca file", "error", err)
return err
}
// read encoded pcm from dca file
InBuf := make([]byte, opuslen)
err = binary.Read(file, binary.LittleEndian, &InBuf)
// Should not be any end of file errors
if err != nil {
slog.Error("error reading from dca file", "error", err)
return err
}
// append encoded pcm data to the buffer
s.buffer = append(s.buffer, InBuf)
}
}
// Play plays this sound over the specified VoiceConnection
func (s *soundClip) Play(vc *discordgo.VoiceConnection) {
err := vc.Speaking(true)
if err != nil {
slog.Error("error setting setting speaking to true")
}
defer func() {
err := vc.Speaking(false)
if err != nil {
slog.Error("error setting setting speaking to false")
}
}()
for _, buff := range s.buffer {
vc.OpusSend <- buff
}
}
// Attempts to find the current users voice channel inside a given guild
func getCurrentVoiceChannel(user *discordgo.User, guild *discordgo.Guild) *discordgo.Channel {
for _, vs := range guild.VoiceStates {
if vs.UserID == user.ID {
channel, _ := discord.State.Channel(vs.ChannelID)
return channel
}
}
return nil
}
// Prepares a play
func createPlay(user *discordgo.User, guild *discordgo.Guild, coll *soundCollection, sound *soundClip) *Play {
// Grab the users voice channel
channel := getCurrentVoiceChannel(user, guild)
if channel == nil {
slog.Warn("Failed to find channel to play sound in", "user", user.ID, "guild", guild.ID)
return nil
}
// Create the play
play := &Play{
GuildID: guild.ID,
ChannelID: channel.ID,
UserID: user.ID,
Sound: sound,
Forced: true,
}
// If we didn't get passed a manual sound, generate a random one
if play.Sound == nil {
play.Sound = coll.Random()
play.Forced = false
}
// If the collection is a chained one, set the next sound
if coll.ChainWith != nil {
play.Next = &Play{
GuildID: play.GuildID,
ChannelID: play.ChannelID,
UserID: play.UserID,
Sound: coll.ChainWith.Random(),
Forced: play.Forced,
}
}
return play
}
// Prepares and enqueues a play into the ratelimit/buffer guild queue
func enqueuePlay(user *discordgo.User, guild *discordgo.Guild, coll *soundCollection, sound *soundClip) {
play := createPlay(user, guild, coll, sound)
if play == nil {
return
}
if sound != nil {
slog.Info("Playing sound", "username", user.Username, "prefix", coll.Prefix, "soundname", sound.Name, "server", guild.Name, "channel", play.ChannelID)
} else {
slog.Info("Playing random sound", "username", user.Username, "prefix", coll.Prefix, "soundname", sound.Name, "server", guild.Name, "channel", play.ChannelID)
}
// Check if we already have a connection to this guild
// this should be threadsafe
mutex.Lock()
_, exists := queues[guild.ID]
mutex.Unlock()
if exists {
if len(queues[guild.ID]) < maxQueueSize {
mutex.Lock()
queues[guild.ID] <- play
mutex.Unlock()
}
} else {
mutex.Lock()
queues[guild.ID] = make(chan *Play, maxQueueSize)
mutex.Unlock()
err := playSound(play, nil)
if err != nil {
slog.Error("could not playSound", "error", err)
}
}
}
// Play a sound
func playSound(play *Play, vc *discordgo.VoiceConnection) (err error) {
slog.Info("Playing sound", "play", play)
if vc != nil {
if vc.GuildID != play.GuildID {
err := vc.Disconnect()
if err != nil {
slog.Error("could not disconnect voice connection", "error", err)
}
vc = nil
}
}
if vc == nil {
vc, err = discord.ChannelVoiceJoin(play.GuildID, play.ChannelID, false, true)
if err != nil {
slog.Error("Failed to play sound", "error", err)
mutex.Lock()
delete(queues, play.GuildID)
mutex.Unlock()
return err
}
}
// If we need to change channels, do that now
if vc.ChannelID != play.ChannelID {
err := vc.ChangeChannel(play.ChannelID, false, true)
if err != nil {
slog.Error("could not change voice channel", "error", err)
}
time.Sleep(time.Millisecond * 125)
}
// Sleep for a specified amount of time before playing the sound
time.Sleep(time.Millisecond * 32)
// Play the sound
play.Sound.Play(vc)
// If this is chained, play the chained sound
if play.Next != nil {
err := playSound(play.Next, vc)
if err != nil {
slog.Error("could not playSound", "error", err)
}
}
// If there is another song in the queue, recurse and play that
if len(queues[play.GuildID]) > 0 {
play = <-queues[play.GuildID]
err := playSound(play, vc)
if err != nil {
slog.Error("could not playSound", "error", err)
}
return nil
}
// If the queue is empty, delete it
time.Sleep(time.Millisecond * time.Duration(play.Sound.PartDelay))
mutex.Lock()
delete(queues, play.GuildID)
err = vc.Disconnect()
if err != nil {
slog.Error("could not disconnect voice connection", "error", err)
return err
}
mutex.Unlock()
return nil
}
func onReady(s *discordgo.Session, event *discordgo.Ready) {
slog.Info("Received READY payload.")
}
func scontains(key string, options ...string) bool {
for _, item := range options {
if item == key {
return true
}
}
return false
}
func displayBotStats(cid string) {
stats := runtime.MemStats{}
runtime.ReadMemStats(&stats)
users := 0
for _, guild := range discord.State.Ready.Guilds {
users += len(guild.Members)
}
statusMessage := fmt.Sprintf(`Gidbig: %s
Discordgo: %s
Go: %s
Memory:
Alloc: %s
Sys: %s
TotalAlloc: %s
Live Memory Objects:
Malloc: %s
Frees: %s
Heap:
Alloc: %s
InUse: %s
Sys: %s
Heap Returnable:
HeapIdle: %s
HeapReleased: %s
Stack:
InUse: %s
Sys: %s
Pointer Lookups: %d
Tasks: %d
Servers: %d
Users: %d
Plugins: %d
Loaded Plugins:
`, version, discordgo.VERSION, runtime.Version(),
humanize.Bytes(stats.Alloc), humanize.Bytes(stats.Sys), humanize.Bytes(stats.TotalAlloc),
humanize.Bytes(stats.Mallocs), humanize.Bytes(stats.Frees),
humanize.Bytes(stats.HeapAlloc), humanize.Bytes(stats.HeapInuse), humanize.Bytes(stats.HeapSys),
humanize.Bytes(stats.HeapIdle), humanize.Bytes(stats.HeapReleased),
humanize.Bytes(stats.StackInuse), humanize.Bytes(stats.StackSys),
stats.Lookups, runtime.NumGoroutine(), len(discord.State.Ready.Guilds), users, len(*gbploader.GetLoadedPlugins()))
for n, p := range *gbploader.GetLoadedPlugins() {
statusMessage += fmt.Sprintf("%s %s\n", n, p[0])
}
_, err := discord.ChannelMessageSend(cid, "```"+statusMessage+"```")
if err != nil {
slog.Error("could not send channel message", "error", err)
}
}
// Handles bot operator messages, should be refactored (lmao)
func handleBotControlMessages(s *discordgo.Session, m *discordgo.MessageCreate, parts []string, g *discordgo.Guild) {
if len(parts) > 1 {
if scontains(parts[1], "status") {
displayBotStats(m.ChannelID)
}
}
}
func onMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Content == "ping" || m.Content == "pong" {
// If the message is "ping" reply with "Pong!"
if m.Content == "ping" {
msg, err := s.ChannelMessageSend(m.ChannelID, "Pong!")
if err != nil {
slog.Error("could not send channel message", "message", msg, "error", err)
}
}
// If the message is "pong" reply with "Ping!"
if m.Content == "pong" {
msg, err := s.ChannelMessageSend(m.ChannelID, "Ping!")
if err != nil {
slog.Error("could not send channel message", "message", msg, "error", err)
}
}
// Updating bot status
err := s.UpdateGameStatus(0, "Ping Pong with "+m.Author.Username)
if err != nil {
slog.Error("could not set game status", "error", err)
}
}
if len(m.Content) <= 0 || (m.Content[0] != '!' && len(m.Mentions) < 1) {
return
}
if m.Content == "!list" {
var list string
for _, c := range COLLECTIONS {
list += "**!" + c.Prefix + "**\n"
for _, sounds := range c.Sounds {
list += sounds.Name + "\n"
}
list += "\n"
}
st, _ := s.UserChannelCreate(m.Author.ID)
msg, err := s.ChannelMessageSend(st.ID, list)
if err != nil {
slog.Error("could not send channel message", "message", msg, "error", err)
}
go deleteCommandMessage(s, m.ChannelID, m.ID)
}
msg := strings.Replace(m.ContentWithMentionsReplaced(), s.State.Ready.User.Username, "username", 1)
parts := strings.Split(strings.ToLower(msg), " ")
channel, _ := discord.State.Channel(m.ChannelID)
if channel == nil {
slog.Warn("Failed to grab channel", "channel", m.ChannelID, "message", m.ID)
return
}
guild, _ := discord.State.Guild(channel.GuildID)
if guild == nil {
slog.Warn("Failed to grab guild", "guild", channel.GuildID, "channel", channel, "message", m.ID)
return
}
// If this is a mention, it should come from the owner (otherwise we don't care)
if len(m.Mentions) > 0 && m.Author.ID == conf.Owner && len(parts) > 0 {
mentioned := false
for _, mention := range m.Mentions {
mentioned = (mention.ID == s.State.Ready.User.ID)
if mentioned {
break
}
}
if mentioned {
handleBotControlMessages(s, m, parts, guild)
}
return
}
// Find the collection for the command we got
findAndPlaySound(s, m, parts, guild)
}
func notifyOwner(message string) {
// FIXME
st, err := discord.UserChannelCreate(conf.Owner)
if err != nil {
return
}
msg, err := discord.ChannelMessageSend(st.ID, message)
if err != nil {
slog.Error("could not send channel message", "message", msg, "error", err)
}
}
func findSoundAndCollection(command string, soundname string) (*soundClip, *soundCollection) {
for _, c := range COLLECTIONS {
if scontains(command, c.Commands...) {
for _, s := range c.Sounds {
if soundname == s.Name {
return s, c
}
}
return nil, c
}
}
return nil, nil
}
// Find sound in collection and play it or do nothing if not found
func findAndPlaySound(s *discordgo.Session, m *discordgo.MessageCreate, parts []string, g *discordgo.Guild) {
for _, coll := range COLLECTIONS {
if scontains(parts[0], coll.Commands...) {
go deleteCommandMessage(s, m.ChannelID, m.ID)
// If they passed a specific sound effect, find and select that (otherwise play nothing)
var sound *soundClip
if len(parts) > 1 {
for _, s := range coll.Sounds {
if parts[1] == s.Name {
sound = s
}
}
if sound == nil {
return
}
}
go enqueuePlay(m.Author, g, coll, sound)
return
}
}
}
// Delete the message after a delay so the channel does not get cluttered
func deleteCommandMessage(s *discordgo.Session, channelID string, messageID string) {
time.Sleep(30 * time.Second)
err := s.ChannelMessageDelete(channelID, messageID)
if err != nil {
slog.Error("Failed to delete message", "error", err)
}
}
// StartGidbig obviously
func StartGidbig() {
LogVersion()
conf = cfg.LoadConfigFile()
// set log level to debug if env var is set
if os.Getenv("DEBUG") != "" {
logLevel := new(slog.LevelVar)
logLevel.Set(slog.LevelDebug)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: logLevel,
}))
slog.SetDefault(logger)
}
var err error
// create SoundCollections by scanning the audio folder
createCollections()
// Start Webserver if a valid port is provided and if ClientID and ClientSecret are set
if conf.Port != 0 && conf.Port >= 1 && conf.Ci != 0 && conf.Cs != "" && conf.RedirectURL != "" {
slog.Info("Starting web server", "port", conf.Port)
go startWebServer(conf)
} else {
slog.Info("Required web server arguments missing or invalid. Skipping web server start.")
}
// Preload all the sounds
slog.Info("Preloading sounds...")
for _, coll := range COLLECTIONS {
coll.Load()
}
// Create a discord session
slog.Info("Starting discord session...")
discord, err = discordgo.New("Bot " + conf.Token)
if err != nil {
slog.Error("Failed to create discord session", "error", err)
os.Exit(1)
return
}
// Set sharding info
discord.ShardID, _ = strconv.Atoi(conf.Shard)
discord.ShardCount, _ = strconv.Atoi(conf.ShardCount)
if discord.ShardCount <= 0 {
discord.ShardCount = 1
}
discord.AddHandler(onReady)
discord.AddHandler(onMessageCreate)
err = discord.Open()
if err != nil {
slog.Error("Failed to create discord websocket connection", "error", err)
os.Exit(1)
return
}
gbploader.LoadPlugins(discord)
// We're running!
Banner(nil, *gbploader.GetLoadedPlugins())
slog.Info("Gidbig is ready. Quit with CTRL-C.")
banner := new(bytes.Buffer)
Banner(banner, *gbploader.GetLoadedPlugins())
if !conf.DevMode {
notifyOwner("```I just started!\n" + banner.String() + "```")
}
// Wait for a signal to quit
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
}