-
Notifications
You must be signed in to change notification settings - Fork 2
/
Music.py
300 lines (284 loc) · 12.4 KB
/
Music.py
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
import asyncio
import aiohttp
import re
try:
import youtube_dl
import discord
has_voice = True
except ImportError:
has_voice = False
if has_voice:
youtube_dl.utils.bug_reports_message = lambda: ''
ydl = youtube_dl.YoutubeDL({"format": "bestaudio/best", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": True, "logtostderr": False, "quiet": True, "no_warnings": True, "source_address": "0.0.0.0"})
class EmptyQueue(Exception):
"""Cannot skip because queue is empty"""
class NotConnectedToVoice(Exception):
"""Cannot create the player because bot is not connected to voice"""
class NotPlaying(Exception):
"""Cannot <do something> because nothing is being played"""
async def ytbettersearch(query):
url = f"https://www.youtube.com/results?search_query={query}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
html = await resp.text()
index = html.find('watch?v')
url = ""
while True:
char = html[index]
if char == '"':
break
url += char
index += 1
url = f"https://www.youtube.com/{url}"
return url
async def get_video_data(url, search, bettersearch, loop):
if not has_voice:
raise RuntimeError("DiscordUtils[voice] install needed in order to use voice")
if not search and not bettersearch:
data = await loop.run_in_executor(None, lambda: ydl.extract_info(url, download=False))
source = data["url"]
url = "https://www.youtube.com/watch?v="+data["id"]
title = data["title"]
description = data["description"]
views = data["view_count"]
duration = data["duration"]
thumbnail = data["thumbnail"]
channel = data["uploader"]
channel_url = data["uploader_url"]
return Song(source, url, title, description, views, duration, thumbnail, channel, channel_url, False)
else:
if bettersearch:
url = await ytbettersearch(url)
data = await loop.run_in_executor(None, lambda: ydl.extract_info(url, download=False))
source = data["url"]
url = "https://www.youtube.com/watch?v="+data["id"]
title = data["title"]
description = data["description"]
views = data["view_count"]
duration = data["duration"]
thumbnail = data["thumbnail"]
channel = data["uploader"]
channel_url = data["uploader_url"]
return Song(source, url, title, description, views, duration, thumbnail, channel, channel_url, False)
elif search:
ytdl = youtube_dl.YoutubeDL({"format": "bestaudio/best", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": True, "logtostderr": False, "quiet": True, "no_warnings": True, "default_search": "auto", "source_address": "0.0.0.0"})
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))
try:
data = data["entries"][0]
except KeyError or TypeError:
pass
del ytdl
source = data["url"]
url = "https://www.youtube.com/watch?v="+data["id"]
title = data["title"]
description = data["description"]
views = data["view_count"]
duration = data["duration"]
thumbnail = data["thumbnail"]
channel = data["uploader"]
channel_url = data["uploader_url"]
return Song(source, url, title, description, views, duration, thumbnail, channel, channel_url, False)
def check_queue(ctx, opts, music, after, on_play, loop):
if not has_voice:
raise RuntimeError("DiscordUtils[voice] install needed in order to use voice")
try:
song = music.queue[ctx.guild.id][0]
except IndexError:
return
if not song.is_looping:
try:
music.queue[ctx.guild.id].pop(0)
except IndexError:
return
if len(music.queue[ctx.guild.id]) > 0:
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(music.queue[ctx.guild.id][0].source, **opts))
ctx.voice_client.play(source, after=lambda error: after(ctx, opts, music, after, on_play, loop))
song = music.queue[ctx.guild.id][0]
if on_play:
loop.create_task(on_play(ctx, song))
else:
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(music.queue[ctx.guild.id][0].source, **opts))
ctx.voice_client.play(source, after=lambda error: after(ctx, opts, music, after, on_play, loop))
song = music.queue[ctx.guild.id][0]
if on_play:
loop.create_task(on_play(ctx, song))
class Music(object):
def __init__(self):
if not has_voice:
raise RuntimeError("DiscordUtils[voice] install needed in order to use voice")
self.queue = {}
self.players = []
def create_player(self, ctx, **kwargs):
if not ctx.voice_client:
raise NotConnectedToVoice("Cannot create the player because bot is not connected to voice")
player = MusicPlayer(ctx, self, **kwargs)
self.players.append(player)
return player
def get_player(self, **kwargs):
guild = kwargs.get("guild_id")
channel = kwargs.get("channel_id")
for player in self.players:
if guild and channel and player.ctx.guild.id == guild and player.voice.channel.id == channel:
return player
elif not guild and channel and player.voice.channel.id == channel:
return player
elif not channel and guild and player.ctx.guild.id == guild:
return player
else:
return None
class MusicPlayer(object):
def __init__(self, ctx, music, **kwargs):
if not has_voice:
raise RuntimeError("DiscordUtils[voice] install needed in order to use voice")
self.ctx = ctx
self.voice = ctx.voice_client
self.loop = ctx.bot.loop
self.music = music
if self.ctx.guild.id not in self.music.queue.keys():
self.music.queue[self.ctx.guild.id] = []
self.after_func = check_queue
self.on_play_func = self.on_queue_func = self.on_skip_func = self.on_stop_func = self.on_pause_func = self.on_resume_func = self.on_loop_toggle_func = self.on_volume_change_func = self.on_remove_from_queue_func = None
ffmpeg_error = kwargs.get("ffmpeg_error_betterfix", kwargs.get("ffmpeg_error_fix"))
if ffmpeg_error and "ffmpeg_error_betterfix" in kwargs.keys():
self.ffmpeg_opts = {"options": "-vn -loglevel quiet -hide_banner -nostats", "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 0 -nostdin"}
elif ffmpeg_error:
self.ffmpeg_opts = {"options": "-vn", "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 0 -nostdin"}
else:
self.ffmpeg_opts = {"options": "-vn", "before_options": "-nostdin"}
def disable(self):
self.music.players.remove(self)
def on_queue(self, func):
self.on_queue_func = func
def on_play(self, func):
self.on_play_func = func
def on_skip(self, func):
self.on_skip_func = func
def on_stop(self, func):
self.on_stop_func = func
def on_pause(self, func):
self.on_pause_func = func
def on_resume(self, func):
self.on_resume_func = func
def on_loop_toggle(self, func):
self.on_loop_toggle_func = func
def on_volume_change(self, func):
self.on_volume_change_func = func
def on_remove_from_queue(self, func):
self.on_remove_from_queue_func = func
async def queue(self, url, search=False, bettersearch=False):
song = await get_video_data(url, search, bettersearch, self.loop)
self.music.queue[self.ctx.guild.id].append(song)
if self.on_queue_func:
await self.on_queue_func(self.ctx, song)
return song
async def play(self):
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(self.music.queue[self.ctx.guild.id][0].source, **self.ffmpeg_opts))
self.voice.play(source, after=lambda error: self.after_func(self.ctx, self.ffmpeg_opts, self.music, self.after_func, self.on_play_func, self.loop))
song = self.music.queue[self.ctx.guild.id][0]
if self.on_play_func:
await self.on_play_func(self.ctx, song)
return song
async def skip(self, force=False):
if len(self.music.queue[self.ctx.guild.id]) == 0:
raise NotPlaying("Cannot loop because nothing is being played")
elif not len(self.music.queue[self.ctx.guild.id]) > 1 and not force:
raise EmptyQueue("Cannot skip because queue is empty")
else:
old = self.music.queue[self.ctx.guild.id][0]
old.is_looping = False if old.is_looping else False
self.voice.stop()
try:
new = self.music.queue[self.ctx.guild.id][0]
if self.on_skip_func:
await self.on_skip_func(self.ctx, old, new)
return (old, new)
except IndexError:
if self.on_skip_func:
await self.on_skip_func(self.ctx, old)
return old
async def stop(self):
try:
self.music.queue[self.ctx.guild.id] = []
self.voice.stop()
self.music.players.remove(self)
except:
raise NotPlaying("Cannot loop because nothing is being played")
if self.on_stop_func:
await self.on_stop_func(self.ctx)
async def pause(self):
try:
self.voice.pause()
song = self.music.queue[self.ctx.guild.id][0]
except:
raise NotPlaying("Cannot pause because nothing is being played")
if self.on_pause_func:
await self.on_pause_func(self.ctx, song)
return song
async def resume(self):
try:
self.voice.resume()
song = self.music.queue[self.ctx.guild.id][0]
except:
raise NotPlaying("Cannot resume because nothing is being played")
if self.on_resume_func:
await self.on_resume_func(self.ctx, song)
return song
def current_queue(self):
try:
return self.music.queue[self.ctx.guild.id]
except KeyError:
raise EmptyQueue("Queue is empty")
def now_playing(self):
try:
return self.music.queue[self.ctx.guild.id][0]
except:
return None
async def toggle_song_loop(self):
try:
song = self.music.queue[self.ctx.guild.id][0]
except:
raise NotPlaying("Cannot loop because nothing is being played")
if not song.is_looping:
song.is_looping = True
else:
song.is_looping = False
if self.on_loop_toggle_func:
await self.on_loop_toggle_func(self.ctx, song)
return song
async def change_volume(self, vol):
self.voice.source.volume = vol
try:
song = self.music.queue[self.ctx.guild.id][0]
except:
raise NotPlaying("Cannot loop because nothing is being played")
if self.on_volume_change_func:
await self.on_volume_change_func(self.ctx, song, vol)
return (song, vol)
async def remove_from_queue(self, index):
if index == 0:
try:
song = self.music.queue[self.ctx.guild.id][0]
except:
raise NotPlaying("Cannot loop because nothing is being played")
await self.skip(force=True)
return song
song = self.music.queue[self.ctx.guild.id][index]
self.music.queue[self.ctx.guild.id].pop(index)
if self.on_remove_from_queue_func:
await self.on_remove_from_queue_func(self.ctx, song)
return song
def delete(self):
self.music.players.remove(self)
class Song(object):
def __init__(self, source, url, title, description, views, duration, thumbnail, channel, channel_url, loop):
self.source = source
self.url = url
self.title = title
self.description = description
self.views = views
self.name = title
self.duration = duration
self.thumbnail = thumbnail
self.channel = channel
self.channel_url = channel_url
self.is_looping = loop