This repository has been archived by the owner on Sep 3, 2022. It is now read-only.
/
msgYoutube.go
362 lines (301 loc) · 9.08 KB
/
msgYoutube.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
package main
import (
"errors"
"fmt"
"io"
"strings"
"sync"
"time"
"github.com/Strum355/go-queue/queue"
"github.com/Necroforger/dgwidgets"
"github.com/bwmarrin/discordgo"
"github.com/jonas747/dca"
"github.com/rylio/ytdl"
)
const (
stdURL = "https://www.youtube.com/watch"
shortURL = "https://youtu.be/"
embedURL = "https://www.youtube.com/embed/"
)
type voiceInst struct {
ChannelID string
Playing bool
Done chan error
*sync.RWMutex
Queue *queue.Queue
VoiceCon *discordgo.VoiceConnection
StreamingSession *dca.StreamingSession
}
type song struct {
URL string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
Image string `json:"image,omitempty"`
Duration time.Duration `json:"duration"`
}
func init() {
newCommand("yt", 0, false, msgYoutube).setHelp("Args: [play,stop] [url]\n\nWork In Progress!!! Play music from Youtube straight to your Discord Server!\n\n" +
"Example 1: `!owo yt play https://www.youtube.com/watch?v=MvLdxtICOIY`\n" +
"Example 2: `!owo yt stop`\n\n" +
"SubCommands:\nplay\nstop\nlist, queue, songs\npause\nresume, unpause\nskip, next").add()
}
func msgYoutube(s *discordgo.Session, m *discordgo.MessageCreate, msglist []string) {
if len(msglist) == 1 {
return
}
switch msglist[1] {
case "play":
addToQueue(s, m, msglist[2:])
case "stop":
stopQueue(s, m)
case "list", "queue", "songs":
listQueue(s, m)
case "pause":
pauseQueue(s, m)
case "resume", "unpause":
unpauseQueue(s, m)
case "skip", "next":
skipSong(s, m)
default:
s.ChannelMessageSend(m.ChannelID, activeCommands["youtube"].Help)
}
}
func addToQueue(s *discordgo.Session, m *discordgo.MessageCreate, msglist []string) {
if len(msglist) == 0 {
return
}
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was a problem adding to queue :( please try again")
return
}
srvr, ok := sMap.server(guild.ID)
if !ok {
s.ChannelMessageSend(m.ChannelID, "An error occurred that really shouldn't have happened...")
log.Error("not in server map?", guild.ID)
return
}
if srvr.VoiceInst == nil {
srvr.newVoiceInstance()
}
srvr.VoiceInst.Lock()
defer srvr.VoiceInst.Unlock()
url := msglist[0]
if !strings.HasPrefix(url, stdURL) && !strings.HasPrefix(url, shortURL) && !strings.HasPrefix(url, embedURL) {
s.ChannelMessageSend(m.ChannelID, "Please make sure the URL is a valid YouTube URL. If I got this wrong, please let my creator know~")
return
}
vid, err := getVideoInfo(url, s, m)
if err != nil {
return
}
vc, err := createVoiceConnection(s, m, guild, srvr)
if err != nil {
return
}
srvr.addSong(song{
URL: url,
Name: vid.Title,
Duration: vid.Duration,
Image: vid.GetThumbnailURL(ytdl.ThumbnailQualityMedium).String(),
})
s.ChannelMessageSend(m.ChannelID, "Added "+vid.Title+" to the queue!")
if !srvr.VoiceInst.Playing {
srvr.VoiceInst.VoiceCon = vc
srvr.VoiceInst.Playing = true
srvr.VoiceInst.ChannelID = vc.ChannelID
go play(s, m, srvr, vc)
}
s.ChannelMessageSend(m.ChannelID, "Need to be in a voice channel!")
}
func createVoiceConnection(s *discordgo.Session, m *discordgo.MessageCreate, guild *discordgo.Guild, srvr *server) (*discordgo.VoiceConnection, error) {
for _, vs := range guild.VoiceStates {
if vs.UserID == m.Author.ID && (vs.ChannelID == srvr.VoiceInst.ChannelID || !srvr.VoiceInst.Playing) {
vc, err := s.ChannelVoiceJoin(guild.ID, vs.ChannelID, false, true)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error joining voice channel")
log.Error("error joining voice channel", err)
return nil, err
}
return vc, nil
}
}
return nil, errors.New("not in voice channel")
}
func getVideoInfo(url string, s *discordgo.Session, m *discordgo.MessageCreate) (*ytdl.VideoInfo, error) {
vid, err := ytdl.GetVideoInfo(url)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error getting video info")
log.Error("error getting video info", err)
return nil, err
}
return vid, nil
}
func play(s *discordgo.Session, m *discordgo.MessageCreate, srvr *server, vc *discordgo.VoiceConnection) {
if srvr.queueLength() == 0 {
srvr.youtubeCleanup()
s.ChannelMessageSend(m.ChannelID, "🔇 Done queue!")
return
}
srvr.VoiceInst.Lock()
vid, err := getVideoInfo(srvr.nextSong().URL, s, m)
if err != nil {
srvr.VoiceInst.Unlock()
return
}
reader, writer := io.Pipe()
defer reader.Close()
formats := vid.Formats.Best(ytdl.FormatAudioBitrateKey)
if len(formats) > 0 {
go func() {
defer writer.Close()
if err := vid.Download(formats[0], writer); err != nil && err != io.ErrClosedPipe {
s.ChannelMessageSend(m.ChannelID, xmark+" Error downloading the music")
log.Error("error downloading YouTube video", err)
srvr.VoiceInst.Done <- err
return
}
}()
}
encSesh, err := dca.EncodeMem(reader, dca.StdEncodeOptions)
if err != nil {
s.ChannelMessageSend(m.ChannelID, xmark+" Error starting the stream")
srvr.youtubeCleanup()
srvr.VoiceInst.Unlock()
// will only return non nill error if options arent valid
log.Error("error validating options", err)
return
}
defer encSesh.Cleanup()
srvr.VoiceInst.StreamingSession = dca.NewStream(encSesh, vc, srvr.VoiceInst.Done)
s.ChannelMessageSend(m.ChannelID, "🔊 Playing: "+vid.Title)
srvr.VoiceInst.Unlock()
Outer:
for {
err = <-srvr.VoiceInst.Done
done, _ := srvr.VoiceInst.StreamingSession.Finished()
switch {
case err.Error() == "stop":
srvr.youtubeCleanup()
s.ChannelMessageSend(m.ChannelID, "🔇 Stopped")
return
case err.Error() == "skip":
s.ChannelMessageSend(m.ChannelID, "⏩ Skipping")
break Outer
case !done && err != io.EOF:
srvr.youtubeCleanup()
s.ChannelMessageSend(m.ChannelID, "There was an error streaming music :(")
log.Error("error streaming music", err)
return
case done && err == io.EOF:
// Remove the currently playing song from the queue and then start the next one
srvr.finishedSong()
break Outer
}
}
go play(s, m, srvr, vc)
}
func listQueue(s *discordgo.Session, m *discordgo.MessageCreate) {
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was an issue loading the list :( please try again")
return
}
srvr, ok := sMap.server(guild.ID)
if !ok {
s.ChannelMessageSend(m.ChannelID, "An error occurred that really shouldn't have happened...")
log.Error("not in server map?", guild.ID)
return
}
if srvr.queueLength() == 0 {
s.ChannelMessageSend(m.ChannelID, "No songs in queue!")
return
}
p := dgwidgets.NewPaginator(s, m.ChannelID)
p.Add(&discordgo.MessageEmbed{
Title: guild.Name + "'s queue",
Fields: func() (out []*discordgo.MessageEmbedField) {
for i, song := range srvr.iterateQueue() {
out = append(out, &discordgo.MessageEmbedField{
Name: fmt.Sprintf("%d - %s", i, song.Name),
Value: song.Duration.String(),
})
}
return
}(),
})
for _, song := range srvr.iterateQueue() {
p.Add(&discordgo.MessageEmbed{
Title: fmt.Sprintf("Title: %s\nDuration: %s\nURL: %s", song.Name, song.Duration, song.URL),
Image: &discordgo.MessageEmbedImage{
URL: song.Image,
},
})
}
p.SetPageFooters()
p.Loop = true
p.ColourWhenDone = 0xff0000
p.DeleteReactionsWhenDone = true
p.Widget.Timeout = time.Minute * 2
p.Spawn()
}
func stopQueue(s *discordgo.Session, m *discordgo.MessageCreate) {
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was an error stopping the queue :( Please try again.")
return
}
if srvr, ok := sMap.server(guild.ID); ok {
srvr.VoiceInst.Done <- errors.New("stop")
}
}
func pauseQueue(s *discordgo.Session, m *discordgo.MessageCreate) {
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was an error pausing the video :( Please try again.")
return
}
srvr, ok := sMap.server(guild.ID)
if !ok {
return
}
srvr.VoiceInst.Lock()
defer srvr.VoiceInst.Unlock()
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("⏸ Paused. To unpause, use the command `%syt unpause`", func() string {
if srvr.Prefix == "" {
return conf.Prefix
}
return srvr.Prefix
}()))
srvr.VoiceInst.StreamingSession.SetPaused(true)
}
func unpauseQueue(s *discordgo.Session, m *discordgo.MessageCreate) {
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was an error unpausing the song :( please try again")
return
}
if srvr, ok := sMap.server(guild.ID); ok {
srvr.VoiceInst.Lock()
defer srvr.VoiceInst.Unlock()
srvr.VoiceInst.StreamingSession.SetPaused(false)
}
}
func skipSong(s *discordgo.Session, m *discordgo.MessageCreate) {
guild, err := guildDetails(m.ChannelID, "", s)
if err != nil {
s.ChannelMessageSend(m.ChannelID, "There was an error skipping the song :( please try again")
return
}
if srvr, ok := sMap.server(guild.ID); ok {
srvr.VoiceInst.Lock()
defer srvr.VoiceInst.Unlock()
srvr.VoiceInst.Done <- errors.New("skip")
}
}
func (s *server) youtubeCleanup() {
s.VoiceInst.Lock()
defer s.VoiceInst.Unlock()
s.VoiceInst.VoiceCon.Disconnect()
s.newVoiceInstance()
//sMap.VoiceInsts--
}