forked from devoxin/Lavalink.py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlavalink.py
More file actions
332 lines (271 loc) · 10 KB
/
lavalink.py
File metadata and controls
332 lines (271 loc) · 10 KB
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
import asyncio
import json
import aiohttp
import websockets
class Requests:
def __init__(self):
self.pool = aiohttp.ClientSession()
async def get(self, url, jsonify=False, *args, **kwargs):
try:
async with self.pool.get(url, *args, **kwargs) as r:
if r.status != 200:
return None
if jsonify:
return await r.json(content_type=None)
return await r.read()
except (aiohttp.ClientOSError, aiohttp.ClientConnectorError, asyncio.TimeoutError):
return None
class AudioTrack:
def __init__(self, track, identifier, can_seek, author, duration, stream, title, uri, requester):
self.track = track
self.identifier = identifier
self.can_seek = can_seek
self.author = author
self.duration = duration
self.stream = stream
self.title = title
self.uri = uri
self.requester = requester
class Player:
def __init__(self, client, guild_id):
self.client = client
self.shard_id = client.bot.get_guild(guild_id).shard_id
self.guild_id = str(guild_id)
self.channel_id = None
self.is_connected = lambda: self.channel_id is not None
self.is_playing = lambda: self.current is not None
self.paused = False
self.position = 0
self.position_timestamp = 0
self.volume = 100
self.queue = []
self.current = None
async def connect(self, channel_id):
payload = {
'op': 'connect',
'guildId': self.guild_id,
'channelId': str(channel_id)
}
await self.client.send(payload)
self.channel_id = str(channel_id)
async def disconnect(self):
if not self.is_connected():
return
if self.is_playing():
await self.stop()
payload = {
'op': 'disconnect',
'guildId': self.guild_id
}
await self.client.send(payload)
self.channel_id = None
async def add(self, requester, track, play=False):
await self._build_track(requester, track)
if play and not self.is_playing():
await self.play()
async def play(self):
if not self.is_connected() or not self.queue:
if self.is_playing():
await self.stop()
self.current = None
return
track = self.queue.pop(0)
payload = {
'op': 'play',
'guildId': self.guild_id,
'track': track.track
}
await self.client.send(payload)
self.current = track
async def stop(self):
payload = {
'op': 'stop',
'guildId': self.guild_id
}
await self.client.send(payload)
self.current = None
async def skip(self):
await self.play()
async def set_paused(self, pause):
payload = {
'op': 'pause',
'guildId': self.guild_id,
'pause': pause
}
await self.client.send(payload)
self.paused = pause
async def set_volume(self, vol):
if vol < 0:
vol = 0
if vol > 150:
vol = 150
payload = {
'op': 'volume',
'guildId': self.guild_id,
'volume': vol
}
await self.client.send(payload)
self.volume = vol
return vol
async def seek(self, pos):
payload = {
'op': 'seek',
'guildId': self.guild_id,
'position': pos
}
await self.client.send(payload)
async def _on_track_end(self, data):
self.position = 0
self.paused = False
if data.get('reason') == 'FINISHED':
await self.play()
async def _build_track(self, requester, track):
try:
a = track.get('track')
info = track.get('info')
b = info.get('identifier')
c = info.get('isSeekable')
d = info.get('author')
e = info.get('length')
f = info.get('isStream')
g = info.get('title')
h = info.get('uri')
i = requester
t = AudioTrack(a, b, c, d, e, f, g, h, i)
self.queue.append(t)
except KeyError:
return # Raise invalid track passed
async def _validate_join(self, data):
payload = {
'op': 'validationRes',
'guildId': data.get('guildId'),
'channelId': data.get('channelId', None),
'valid': True
}
await self.client.send(payload)
class Client:
def __init__(self, bot, password='', host='localhost', port=80, rest=2333, loop=asyncio.get_event_loop()):
self.bot = bot
if not hasattr(self.bot, 'players'):
self.bot.players = {}
self.loop = loop
self.shard_count = len(self.bot.shards) if hasattr(self.bot, 'shards') else 1
self.user_id = self.bot.user.id
self.password = password
self.host = host
self.port = port
self.rest = rest
self.uri = f'ws://{host}:{port}'
self.requester = Requests()
asyncio.ensure_future(self._connect())
async def _connect(self):
try:
headers = {
'Authorization': self.password,
'Num-Shards': self.shard_count,
'User-Id': self.user_id
}
self.ws = await websockets.connect(self.uri, extra_headers=headers)
self.loop.create_task(self._listen())
print("[Lavalink.py] Established connection to lavalink")
except OSError:
print('[Lavalink.py] Failed to connect to lavalink')
async def _listen(self):
try:
while True:
data = await self.ws.recv()
j = json.loads(data)
if 'op' in j:
if j.get('op') == 'validationReq':
await self._dispatch_join_validator(j)
elif j.get('op') == 'isConnectedReq':
await self._validate_shard(j)
elif j.get('op') == 'sendWS':
await self.bot._connection._get_websocket(330777295952543744).send(j.get('message')) # todo: move this to play (voice updates)
elif j.get('op') == 'event':
await self._dispatch_event(j)
elif j.get('op') == 'playerUpdate':
await self._update_state(j)
except websockets.ConnectionClosed:
print('[Lavalink.py] Connection closed... Attempting to reconnect in 30 seconds')
self.ws.close()
for a in [1, 2, 3]: # 3 Attempts
await asyncio.sleep(30)
print(f'[Lavalink.py] Attempting to reconnect (attempt: {a})')
await self._connect()
if self.ws.open:
return
print('[Lavalink.py] Failed to re-establish a connection with lavalink.')
async def _dispatch_event(self, data):
t = data.get('type')
g = int(data.get('guildId'))
if g not in self.bot.players:
return
if t == 'TrackEndEvent':
player = self.bot.players[g]
asyncio.ensure_future(player._on_track_end(data))
async def _dispatch_join_validator(self, data):
if int(data.get('guildId')) in self.bot.players:
p = self.bot.players[int(data.get('guildId'))]
await p._validate_join(data)
else:
payload = {
'op': 'validationRes',
'guildId': data.get('guildId'),
'channelId': data.get('channelId', None),
'valid': False
}
await self.send(payload)
async def _update_state(self, data):
g = int(data.get('guildId'))
if g not in self.bot.players:
return
p = self.bot.players[g]
if not p.is_playing():
return
p.position = data['state'].get('position', 0)
p.position_timestamp = data['state'].get('time', 0)
async def _validate_shard(self, data):
payload = {
'op': 'isConnectedRes',
'shardId': data.get('shardId'),
'connected': True
}
await self.send(payload)
async def send(self, data):
if not hasattr(self, 'ws') or not self.ws.open:
return
payload = json.dumps(data)
await self.ws.send(payload)
async def dispatch_voice_update(self, payload):
await self.send(payload)
async def get_player(self, guild_id):
if guild_id not in self.bot.players:
p = Player(client=self, guild_id=guild_id)
self.bot.players[guild_id] = p
return self.bot.players[guild_id]
async def get_tracks(self, query):
headers = {
'Authorization': self.password,
'Accept': 'application/json'
}
return await self.requester.get(url=f'http://{self.host}:{self.rest}/loadtracks?identifier={query}', jsonify=True, headers=headers)
# data = {
# 'is_search': any(s in query for s in ['ytsearch', 'scsearch']),
# 'results': tracks
# }
# return data
class Utils:
@staticmethod
def format_time(time):
seconds = (time / 1000) % 60
minutes = (time / (1000 * 60)) % 60
hours = (time / (1000 * 60 * 60)) % 24
return "%02d:%02d:%02d" % (hours, minutes, seconds)
@staticmethod
def is_number(num):
try:
int(num)
return True
except ValueError:
return False