This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
forked from discord/airhornbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
499 lines (423 loc) · 10.9 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
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
package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"math/rand"
"os"
"os/signal"
"strconv"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/bwmarrin/discordgo"
)
var (
// discordgo session
discord *discordgo.Session
// Map of Guild id's to *Play channels, used for queuing and rate-limiting guilds
queues map[string]chan *Play = make(map[string]chan *Play)
// Sound encoding settings
BITRATE = 128
MAX_QUEUE_SIZE = 6
// Owner
OWNER string
)
// Play represents an individual use of the !airhorn command
type Play struct {
GuildID string
ChannelID string
UserID string
Sound *Sound
// The next play to occur after this, only used for chaining sounds like anotha
Next *Play
// If true, this was a forced play using a specific airhorn sound name
Forced bool
}
type SoundCollection struct {
Prefix string
Commands []string
Sounds []*Sound
ChainWith *SoundCollection
soundRange int
}
// Sound represents a sound clip
type Sound struct {
Name string
// Weight adjust how likely it is this song will play, higher = more likely
Weight int
// Delay (in milliseconds) for the bot to wait before sending the disconnect request
PartDelay int
// Buffer to store encoded PCM packets
buffer [][]byte
}
// Array of all the sounds we have
var AIRHORN *SoundCollection = &SoundCollection{
Prefix: "airhorn",
Commands: []string{
"!airhorn",
},
Sounds: []*Sound{
createSound("default", 1000, 250),
createSound("reverb", 800, 250),
createSound("spam", 800, 0),
createSound("tripletap", 800, 250),
createSound("fourtap", 800, 250),
createSound("distant", 500, 250),
createSound("echo", 500, 250),
createSound("clownfull", 250, 250),
createSound("clownshort", 250, 250),
createSound("clownspam", 250, 0),
createSound("highfartlong", 200, 250),
createSound("highfartshort", 200, 250),
createSound("midshort", 100, 250),
createSound("truck", 10, 250),
},
}
var KHALED *SoundCollection = &SoundCollection{
Prefix: "another",
ChainWith: AIRHORN,
Commands: []string{
"!anotha",
"!anothaone",
},
Sounds: []*Sound{
createSound("one", 1, 250),
createSound("one_classic", 1, 250),
createSound("one_echo", 1, 250),
},
}
var CENA *SoundCollection = &SoundCollection{
Prefix: "jc",
Commands: []string{
"!johncena",
"!cena",
},
Sounds: []*Sound{
createSound("airhorn", 1, 250),
createSound("echo", 1, 250),
createSound("full", 1, 250),
createSound("jc", 1, 250),
createSound("nameis", 1, 250),
createSound("spam", 1, 250),
},
}
var BIRTHDAY *SoundCollection = &SoundCollection{
Prefix: "birthday",
Commands: []string{
"!birthday",
"!bday",
},
Sounds: []*Sound{
createSound("horn", 50, 250),
createSound("horn3", 30, 250),
createSound("sadhorn", 25, 250),
createSound("weakhorn", 25, 250),
},
}
var BASSEM *SoundCollection = &SoundCollection{
Prefix: "bassem",
Commands: []string{
"!bassem",
},
Sounds: []*Sound{
createSound("apprend", 50, 250),
createSound("chante", 50, 250),
createSound("juif1", 50, 250),
createSound("juif2", 50, 250),
createSound("spiderman", 50, 250),
},
}
var COLLECTIONS []*SoundCollection = []*SoundCollection{
AIRHORN,
KHALED,
CENA,
BIRTHDAY,
BASSEM,
}
// Create a Sound struct
func createSound(Name string, Weight int, PartDelay int) *Sound {
return &Sound{
Name: Name,
Weight: Weight,
PartDelay: PartDelay,
buffer: make([][]byte, 0),
}
}
func (sc *SoundCollection) Load() {
for _, sound := range sc.Sounds {
sc.soundRange += sound.Weight
sound.Load(sc)
}
}
func (s *SoundCollection) Random() *Sound {
var (
i int
number int = randomRange(0, s.soundRange)
)
for _, sound := range s.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 *Sound) Load(c *SoundCollection) error {
path := fmt.Sprintf("audio/%v_%v.dca", c.Prefix, s.Name)
file, err := os.Open(path)
if err != nil {
fmt.Println("error opening dca file :", 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 {
fmt.Println("error reading from dca file :", 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 {
fmt.Println("error reading from dca file :", err)
return err
}
// append encoded pcm data to the buffer
s.buffer = append(s.buffer, InBuf)
}
}
// Plays this sound over the specified VoiceConnection
func (s *Sound) Play(vc *discordgo.VoiceConnection) {
vc.Speaking(true)
defer vc.Speaking(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
}
// Returns a random integer between min and max
func randomRange(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max-min) + min
}
// Prepares a play
func createPlay(user *discordgo.User, guild *discordgo.Guild, coll *SoundCollection, sound *Sound) *Play {
// Grab the users voice channel
channel := getCurrentVoiceChannel(user, guild)
if channel == nil {
log.WithFields(log.Fields{
"user": user.ID,
"guild": guild.ID,
}).Warning("Failed to find channel to play sound in")
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 *Sound) {
play := createPlay(user, guild, coll, sound)
if play == nil {
return
}
// Check if we already have a connection to this guild
// yes, this isn't threadsafe, but its "OK" 99% of the time
_, exists := queues[guild.ID]
if exists {
if len(queues[guild.ID]) < MAX_QUEUE_SIZE {
queues[guild.ID] <- play
}
} else {
queues[guild.ID] = make(chan *Play, MAX_QUEUE_SIZE)
playSound(play, nil)
}
}
// Play a sound
func playSound(play *Play, vc *discordgo.VoiceConnection) (err error) {
log.WithFields(log.Fields{
"play": play,
}).Info("Playing sound")
if vc == nil {
vc, err = discord.ChannelVoiceJoin(play.GuildID, play.ChannelID, false, false)
// vc.Receive = false
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Failed to play sound")
delete(queues, play.GuildID)
return err
}
}
// If we need to change channels, do that now
if vc.ChannelID != play.ChannelID {
vc.ChangeChannel(play.ChannelID, false, false)
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 {
playSound(play.Next, vc)
}
// If there is another song in the queue, recurse and play that
if len(queues[play.GuildID]) > 0 {
play := <-queues[play.GuildID]
playSound(play, vc)
return nil
}
// If the queue is empty, delete it
time.Sleep(time.Millisecond * time.Duration(play.Sound.PartDelay))
delete(queues, play.GuildID)
vc.Disconnect()
return nil
}
func onReady(s *discordgo.Session, event *discordgo.Ready) {
log.Info("Recieved READY payload")
s.UpdateStatus(0, "")
}
func scontains(key string, options ...string) bool {
for _, item := range options {
if item == key {
return true
}
}
return false
}
func onMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if len(m.Content) <= 0 || (m.Content[0] != '!' && len(m.Mentions) < 1) {
return
}
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 {
log.WithFields(log.Fields{
"channel": m.ChannelID,
"message": m.ID,
}).Warning("Failed to grab channel")
return
}
guild, _ := discord.State.Guild(channel.GuildID)
if guild == nil {
log.WithFields(log.Fields{
"guild": channel.GuildID,
"channel": channel,
"message": m.ID,
}).Warning("Failed to grab guild")
return
}
// Find the collection for the command we got
for _, coll := range COLLECTIONS {
if scontains(parts[0], coll.Commands...) {
// If they passed a specific sound effect, find and select that (otherwise play nothing)
var sound *Sound
if len(parts) > 1 {
for _, s := range coll.Sounds {
if parts[1] == s.Name {
sound = s
}
}
if sound == nil {
return
}
}
go enqueuePlay(m.Author, guild, coll, sound)
return
}
}
}
func main() {
var (
Token = flag.String("t", "", "Discord Authentication Token")
Shard = flag.String("s", "", "Shard ID")
ShardCount = flag.String("c", "", "Number of shards")
Owner = flag.String("o", "", "Owner ID")
err error
)
flag.Parse()
if *Owner != "" {
OWNER = *Owner
}
// Preload all the sounds
log.Info("Preloading sounds...")
for _, coll := range COLLECTIONS {
coll.Load()
}
// Create a discord session
log.Info("Starting discord session...")
discord, err = discordgo.New(*Token)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to create discord session")
return
}
// Set sharding info
discord.ShardID, _ = strconv.Atoi(*Shard)
discord.ShardCount, _ = strconv.Atoi(*ShardCount)
if discord.ShardCount <= 0 {
discord.ShardCount = 1
}
discord.AddHandler(onReady)
discord.AddHandler(onMessageCreate)
err = discord.Open()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to create discord websocket connection")
return
}
// We're running!
log.Info("AIRHORNBOT is ready to horn it up.")
// Wait for a signal to quit
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
<-c
}