-
Notifications
You must be signed in to change notification settings - Fork 15
/
soundboard.go
408 lines (343 loc) · 8.92 KB
/
soundboard.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/rylio/ytdl"
"github.com/jonas747/dca"
"sync"
"github.com/Necroforger/dgrouter/exrouter"
"github.com/bwmarrin/discordgo"
)
// Command line flags
var (
fToken = flag.String("t", "", "bot token")
fPrefix = flag.String("p", "!", "bot prefix")
fSoundDir = flag.String("d", "sounds", "directory of sound files")
fWatch = flag.Bool("watch", false, "watch the sound directory for changes")
)
func reply(ctx *exrouter.Context, args ...interface{}) {
_, err := ctx.Reply(args...)
if err != nil {
log.Println("error sending message: ", err)
}
}
func decodeFromFile(path string, v *[][]string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if strings.HasSuffix(path, ".txt") {
t, err := ioutil.ReadFile(path)
if err != nil {
return err
}
decodeFromString(string(t), v)
}
return json.NewDecoder(f).Decode(v)
}
func decodeFromString(txt string, v *[][]string) {
lines := strings.Split(txt, "\n")
for _, ln := range lines {
// Skip comments and empty lines
if strings.HasPrefix(ln, "#") || strings.TrimSpace(ln) == "" {
continue
}
// Split into space separated pairs
pair := strings.SplitN(ln, " ", 2)
// Trim the extra spaces
for i := 0; i < len(pair); i++ {
pair[i] = strings.TrimSpace(pair[i])
}
*v = append(*v, pair)
}
}
func trimExtension(p string) string {
return strings.TrimSuffix(p, filepath.Ext(p))
}
func createRouter(s *discordgo.Session) *exrouter.Route {
router := exrouter.New()
// Create playback functions
files, err := ioutil.ReadDir(*fSoundDir)
if err != nil {
log.Fatal("no sound directory: ", err)
}
for _, v := range files {
if v.IsDir() {
continue
}
if filepath.Ext(v.Name()) == ".json" || filepath.Ext(v.Name()) == ".txt" {
var data = [][]string{}
decodeFromFile(path.Join(*fSoundDir, v.Name()), &data)
for _, d := range data {
router.On(trimExtension(d[0]), createYoutubeFunction(d[1])).Desc("Plays " + d[1])
}
continue
}
router.On(
trimExtension(v.Name()),
createMusicFunction(filepath.Join(*fSoundDir, v.Name())),
).Desc("plays " + v.Name())
}
router.On("stop", func(ctx *exrouter.Context) {
stopStreaming(ctx.Msg.GuildID)
}).Desc("Stops the currently running stream")
router.On("leave", func(ctx *exrouter.Context) {
s.Lock()
if vc, ok := s.VoiceConnections[ctx.Msg.GuildID]; ok {
err := vc.Disconnect()
if err != nil {
reply(ctx, "error disconnecting from voice channel: ", err)
}
}
s.Unlock()
}).Desc("Leaves the current voice channel")
router.On("yt", func(ctx *exrouter.Context) {
createYoutubeFunction(ctx.Args.Get(1))(ctx)
}).Desc("plays a youtube link").Alias("youtube")
// Create help route and set it to the default route for bot mentions
router.Default = router.On("help", func(ctx *exrouter.Context) {
var text = ""
var maxlen int
for _, v := range router.Routes {
if len(v.Name) > maxlen {
maxlen = len(v.Name)
}
}
for _, v := range router.Routes {
text += fmt.Sprintf("%-"+strconv.Itoa(maxlen+5)+"s: %s\n", v.Name, v.Description)
}
reply(ctx, "```"+text+"```")
}).Desc("prints this help menu")
return router
}
func watchDirectory(dir string, fn func(fsnotify.Event)) *fsnotify.Watcher {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
}
fn(event)
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(dir)
if err != nil {
log.Fatal(err)
}
log.Println("Listening for changes in directory: " + dir)
return watcher
}
func main() {
flag.Parse()
s, err := discordgo.New(*fToken)
if err != nil {
log.Fatal(err)
}
var rmu sync.RWMutex
router := createRouter(s)
// Rebuild the router when the sound directory is modified
if *fWatch {
watcher := watchDirectory(*fSoundDir, func(evt fsnotify.Event) {
rmu.Lock()
defer rmu.Unlock()
router = createRouter(s)
})
defer watcher.Close()
}
// Add message handler
s.AddHandler(func(_ *discordgo.Session, m *discordgo.MessageCreate) {
rmu.RLock()
defer rmu.RUnlock()
// TODO : allow handlers to be called in goroutines to fix race condition when hot-reloading
go router.FindAndExecute(s, *fPrefix, s.State.User.ID, m.Message)
})
err = s.Open()
if err != nil {
log.Fatal(err)
}
log.Println("bot is running...")
// Prevent the bot from exiting
<-make(chan struct{})
}
// thread safe map
type syncmap struct {
sync.RWMutex
Data map[string]interface{}
}
func newSyncmap() *syncmap {
return &syncmap{
Data: map[string]interface{}{},
}
}
// Set ...
func (s *syncmap) Set(key string, value interface{}) {
s.Lock()
s.Data[key] = value
s.Unlock()
}
// Get ...
func (s *syncmap) Get(key string) (interface{}, bool) {
s.RLock()
defer s.RUnlock()
if v, ok := s.Data[key]; ok {
return v, true
}
return nil, false
}
// links guild ids to their dca encoder session
var streams = newSyncmap()
type streamSession struct {
EncodeSession *dca.EncodeSession
StreamSession *dca.StreamingSession
}
func createMusicFunction(fpath string) func(ctx *exrouter.Context) {
return func(ctx *exrouter.Context) {
vc, err := getVoiceConnection(ctx.Ses, ctx.Msg.Author.ID, ctx.Msg.GuildID)
if err != nil {
reply(ctx, "error obtaining voice connection")
log.Println("error getting voice connection: ", err)
return
}
log.Println("Creating encoding session")
opts := dca.StdEncodeOptions
opts.RawOutput = true
opts.Bitrate = 120
encodeSession, err := dca.EncodeFile(fpath, opts)
if err != nil {
reply(ctx, "error creating encode session")
log.Println("error creating encode session: ", err)
return
}
// set speaking to true
if err := vc.Speaking(true); err != nil {
reply(ctx, "could not set speaking to true")
return
}
defer vc.Speaking(false)
done := make(chan error)
streamer := dca.NewStream(encodeSession, vc, done)
// Stop any currently running stream
stopStreaming(vc.GuildID)
log.Println("Adding streaming to map")
streams.Set(ctx.Msg.GuildID, &streamSession{
EncodeSession: encodeSession,
StreamSession: streamer,
})
if err := <-done; err != nil {
log.Println(err)
// Clean up incase something happened and ffmpeg is still running
encodeSession.Truncate()
}
}
}
// createYoutubeFunction creates a function for streaming youtube videos
func createYoutubeFunction(yurl string) func(ctx *exrouter.Context) {
return func(ctx *exrouter.Context) {
vc, err := getVoiceConnection(ctx.Ses, ctx.Msg.Author.ID, ctx.Msg.GuildID)
if err != nil {
reply(ctx, "error obtaining voice connection")
log.Println("error getting voice connection: ", err)
return
}
err = playYoutubeVideo(vc, yurl)
if err != nil {
reply(ctx, "error playing youtube video: ", err)
}
}
}
func playYoutubeVideo(vc *discordgo.VoiceConnection, yurl string) error {
info, err := ytdl.GetVideoInfo(yurl)
if err != nil {
return err
}
rd, wr := io.Pipe()
go func() {
if key := info.Formats.Best(ytdl.FormatAudioEncodingKey); len(key) != 0 {
err := info.Download(key[0], wr)
if err != nil {
log.Println(err)
}
}
wr.Close()
}()
opts := dca.StdEncodeOptions
opts.RawOutput = true
opts.Bitrate = 120
encodeSession, err := dca.EncodeMem(rd, opts)
if err != nil {
return err
}
// set speaking to true
if err := vc.Speaking(true); err != nil {
return err
}
defer vc.Speaking(false)
done := make(chan error)
streamer := dca.NewStream(encodeSession, vc, done)
// Stop any currently running stream
stopStreaming(vc.GuildID)
log.Println("Adding streaming to map")
streams.Set(vc.GuildID, &streamSession{
EncodeSession: encodeSession,
StreamSession: streamer,
})
if err := <-done; err != nil {
log.Println(err)
// Clean up incase something happened and ffmpeg is still running
encodeSession.Cleanup()
}
return nil
}
func stopStreaming(guildID string) {
if v, ok := streams.Get(guildID); ok {
// v.(*streamSession).EncodeSession.Cleanup()
err := v.(*streamSession).EncodeSession.Stop()
if err != nil {
log.Println("error stopping streaming session: ", err)
}
v.(*streamSession).EncodeSession.Cleanup()
}
}
// getVoiceConnection gets a bot's voice connection
func getVoiceConnection(s *discordgo.Session, userID string, guildID string) (*discordgo.VoiceConnection, error) {
guild, err := s.State.Guild(guildID)
if err != nil {
guild, err = s.Guild(guildID)
if err != nil {
return nil, err
}
}
for _, v := range guild.VoiceStates {
if v.UserID == userID {
return s.ChannelVoiceJoin(guildID, v.ChannelID, false, false)
}
}
return nil, errors.New("Voice connection not found")
}