-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathmusic_player.py
481 lines (449 loc) · 17.5 KB
/
music_player.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
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
# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >.
#
# This file is part of < https://github.com/DevsExpo/FridayUserBot > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/DevsExpo/blob/master/LICENSE >
#
# All rights reserved.
import os
import math
import os
import shlex
import time
from math import ceil
import logging
import ffmpeg
from main_startup import Friday
import functools
import threading
from concurrent.futures import ThreadPoolExecutor
from pyrogram.errors import FloodWait, MessageNotModified
import multiprocessing
import time
import calendar
from main_startup.core.decorators import friday_on_cmd
from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes, time_formatter, run_in_exc
from pytgcalls import GroupCallFactory, GroupCallFileAction
import signal
import random
import string
import asyncio
import os
import time
import requests
import datetime
from youtube_dl import YoutubeDL
from youtubesearchpython import SearchVideos
s_dict = {}
GPC = {}
@friday_on_cmd(
["playlist"],
is_official=False,
cmd_help={"help": "Get Current Chat Playlist!", "example": "{ch}playlist"},
)
async def pl(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
play = await edit_or_reply(message, "`Please Wait!`")
song = f"**PlayList in {message.chat.title}** \n"
s = s_dict.get((message.chat.id, client.me.id))
if not group_call:
return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`")
if not s:
if group_call.is_connected:
return await play.edit(f"**Currently Playing :** `{group_call.song_name}`")
else:
return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`")
if group_call.is_connected:
song += f"**Currently Playing :** `{group_call.song_name}` \n\n"
for sno, i in enumerate(s, start=1):
song += f"**{sno} ▶** [{i['song_name']}]({i['url']}) `| {i['singer']} | {i['dur']}` \n\n"
await play.edit(song, disable_web_page_preview=True)
async def get_chat_(client, chat_):
chat_ = str(chat_)
if chat_.startswith("-100"):
try:
return (await client.get_chat(int(chat_))).id
except ValueError:
chat_ = chat_.split("-100")[1]
chat_ = '-' + str(chat_)
return int(chat_)
async def playout_ended_handler(group_call, filename):
client_ = group_call.client
chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}")
chat_ = int(chat_)
s = s_dict.get((chat_, client_.me.id))
if os.path.exists(group_call.input_filename):
os.remove(group_call.input_filename)
if not s:
await group_call.stop()
del GPC[(chat_, client.me.id)]
return
name_ = s[0]['song_name']
singer_ = s[0]['singer']
dur_ = s[0]['dur']
raw_file = s[0]['raw']
link = s[0]['url']
file_size = humanbytes(os.stat(raw_file).st_size)
song_info = f'<u><b>🎼 Now Playing 🎼</b></u> \n<b>🎵 Song :</b> <a href="{link}">{name_}</a> \n<b>🎸 Singer :</b> <code>{singer_}</code> \n<b>⏲️ Duration :</b> <code>{dur_}</code> \n<b>📂 Size :</b> <code>{file_size}</code>'
await client_.send_message(
chat_,
song_info,
disable_web_page_preview=True,
)
s.pop(0)
logging.debug(song_info)
group_call.song_name = name_
group_call.input_filename = raw_file
@friday_on_cmd(
["skip_vc"],
is_official=False,
cmd_help={"help": "Skip Song in Playlist.", "example": "{ch}skip_vc (key_len)"}
)
async def ski_p(client, message):
m_ = await edit_or_reply(message, "`Please Wait!`")
no_t_s = get_text(message)
group_call = GPC.get((message.chat.id, client.me.id))
s = s_dict.get((message.chat.id, client.me.id))
if not group_call:
await m_.edit("`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await m_.edit("`Is Group Call Even Connected?`")
return
if not no_t_s:
return await m_.edit("`Give Me Valid List Key Len.`")
if no_t_s == "current":
if not s:
return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`")
next_s = s[0]['raw']
name = str(s[0]['song_name'])
s.pop(0)
prev = group_call.song_name
group_call.input_filename = next_s
return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`")
else:
if not s:
return await m_.edit("`There is No Playlist!`")
if not no_t_s.isdigit():
return await m_.edit("`Input Should Be In Digits.`")
no_t_s = int(no_t_s)
if int(no_t_s) == 0:
return await m_.edit("`0? What?`")
no_t_s = int(no_t_s - 1)
try:
s_ = s[no_t_s]['song_name']
s.pop(no_t_s)
except:
return await m_.edit("`Invalid Key.`")
return await m_.edit(f"`Skipped : {s_} At Position #{no_t_s}`")
@friday_on_cmd(
["play_vc"],
is_official=False,
cmd_help={"help": "Play The Song In VC Directly From Youtube Or Telegram!", "example": "{ch}play_vc (song query)"},
)
async def play_m(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
u_s = await edit_or_reply(message, "`Processing..`")
input_str = get_text(message)
if not input_str:
if not message.reply_to_message:
return await u_s.edit_text("`Reply To A File To PLay It.`")
if not message.reply_to_message.audio:
return await u_s.edit("`Reply To A File To PLay It.`")
await u_s.edit_text("`Please Wait, Let Me Download This File!`")
audio = message.reply_to_message.audio
audio_original = await message.reply_to_message.download()
vid_title = audio.title or audio.file_name
uploade_r = message.reply_to_message.audio.performer or "Unknown Artist."
dura_ = message.reply_to_message.audio.duration
dur = datetime.timedelta(seconds=dura_)
raw_file_name = (
''.join(random.choice(string.ascii_lowercase) for i in range(5))
+ ".raw"
)
url = message.reply_to_message.link
else:
search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
rt = search.result()
result_s = rt.get("search_result")
if not result_s:
return await u_s.edit(f"`No Song Found Matching With Query - {input_str}, Please Try Giving Some Other Name.`")
url = result_s[0]["link"]
dur = result_s[0]["duration"]
vid_title = result_s[0]["title"]
yt_id = result_s[0]["id"]
uploade_r = result_s[0]["channel"]
start = time.time()
try:
audio_original = await yt_dl(url, client, message, start)
except BaseException as e:
return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
raw_file_name = (
''.join(random.choice(string.ascii_lowercase) for i in range(5))
+ ".raw"
)
try:
raw_file_name = await convert_to_raw(audio_original, raw_file_name)
except BaseException as e:
return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`")
if os.path.exists(audio_original):
os.remove(audio_original)
if not group_call:
group_call = GroupCallFactory(client).get_file_group_call()
group_call.song_name = vid_title
GPC[(message.chat.id, client.me.id)] = group_call
try:
await group_call.start(message.chat.id)
except BaseException as e:
return await u_s.edit(f"**Error While Joining VC:** `{e}`")
group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED)
group_call.input_filename = raw_file_name
return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!")
elif not group_call.is_connected:
try:
await group_call.start(message.chat.id)
except BaseException as e:
return await u_s.edit(f"**Error While Joining VC:** `{e}`")
group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED)
group_call.input_filename = raw_file_name
group_call.song_name = vid_title
return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!")
else:
s_d = s_dict.get((message.chat.id, client.me.id))
f_info = {"song_name": vid_title,
"raw": raw_file_name,
"singer": uploade_r,
"dur": dur,
"url": url
}
if s_d:
s_d.append(f_info)
else:
s_dict[(message.chat.id, client.me.id)] = [f_info]
s_d = s_dict.get((message.chat.id, client.me.id))
return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!")
@run_in_exc
def convert_to_raw(audio_original, raw_file_name):
ffmpeg.input(audio_original).output(raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run()
return raw_file_name
def edit_msg(client, message, to_edit):
try:
client.loop.create_task(message.edit(to_edit))
except MessageNotModified:
pass
except FloodWait as e:
client.loop.create_task(asyncio.sleep(e.x))
except TypeError:
pass
def download_progress_hook(d, message, client, start):
if d['status'] == 'downloading':
current = d.get("_downloaded_bytes_str") or humanbytes(d.get("downloaded_bytes", 1))
total = d.get("_total_bytes_str") or d.get("_total_bytes_estimate_str")
file_name = d.get("filename")
eta = d.get('_eta_str', "N/A")
percent = d.get("_percent_str", "N/A")
speed = d.get("_speed_str", "N/A")
to_edit = f"<b><u>Downloading File</b></u> \n<b>File Name :</b> <code>{file_name}</code> \n<b>File Size :</b> <code>{total}</code> \n<b>Speed :</b> <code>{speed}</code> \n<b>ETA :</b> <code>{eta}</code> \n<i>Download {current} out of {total}</i> (__{percent}__)"
threading.Thread(target=edit_msg, args=(client, message, to_edit)).start()
@run_in_exc
def yt_dl(url, client, message, start):
opts = {
"format": "bestaudio",
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
"progress_hooks": [lambda d: download_progress_hook(d, message, client, start)],
"nocheckcertificate": True,
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3"
}
],
"outtmpl": "%(id)s.mp3",
"quiet": True,
"logtostderr": False,
}
with YoutubeDL(opts) as ytdl:
ytdl_data = ytdl.extract_info(url, download=True)
return str(ytdl_data['id']) + ".mp3"
RD_ = {}
FFMPEG_PROCESSES = {}
@friday_on_cmd(
["pradio"],
is_official=False,
cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"},
)
async def radio_s(client, message):
g_s_ = GPC.get((message.chat.id, client.me.id))
if g_s_:
if g_s_.is_connected:
await g_s_.stop()
del GPC[(message.chat.id, client.me.id)]
s = await edit_or_reply(message, "`Please Wait.`")
input_filename = f"radio_{message.chat.id}.raw"
radio_url = get_text(message)
if not radio_url:
return await s.edit("`Invalid Radio URL...`")
group_call = RD_.get((message.chat.id, client.me.id))
if not group_call:
group_call = GroupCallFactory(client, input_filename, path_to_log_file='').get_file_group_call()
RD_[(message.chat.id, client.me.id)] = group_call
process = FFMPEG_PROCESSES.get((message.chat.id, client.me.id))
if process:
process.send_signal(signal.SIGTERM)
await group_call.start(message.chat.id)
process = ffmpeg.input(radio_url).output(
input_filename,
format='s16le',
acodec='pcm_s16le',
ac=2,
ar='48k',
loglevel='error'
).overwrite_output().run_async()
FFMPEG_PROCESSES[(message.chat.id, client.me.id)] = process
await s.edit(f"**📻 Playing :** `{radio_url}`")
@friday_on_cmd(
["sradio"],
is_official=False,
cmd_help={"help": "Stop Radio.", "example": "{ch}stop_radio"},
)
async def stop_radio(client, message):
msg = await edit_or_reply(message, "`Please Wait.`")
group_call = RD_.get((message.chat.id, client.me.id))
if group_call and group_call.is_connected:
await group_call.stop()
else:
return await msg.edit("`Is Vc is Connected?`")
process = FFMPEG_PROCESSES.get((message.chat.id, client.me.id))
await msg.edit("`Radio Stopped : 📻`")
if process:
process.send_signal(signal.SIGTERM)
@friday_on_cmd(
["pause"],
is_official=False,
cmd_help={"help": "Pause Currently Playing Song.", "example": "{ch}pause"},
)
async def no_song_play(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
await edit_or_reply(message, f"`⏸ Paused {str(group_call.input_filename).replace('.raw', '')}.`")
group_call.pause_playout()
@friday_on_cmd(
["resume"],
is_official=False,
cmd_help={"help": "Resume Paused Song.", "example": "{ch}resume"},
)
async def wow_dont_stop_songs(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
group_call.resume_playout()
await edit_or_reply(message, f"`▶️ Resumed.`")
@friday_on_cmd(
["stopvc"],
is_official=False,
cmd_help={"help": "Stop VoiceChat!", "example": "{ch}stopvc"},
)
async def kill_vc_(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if os.path.exists(group_call.input_filename):
os.remove(group_call.input_filename)
group_call.stop_playout()
await edit_or_reply(message, "`Stopped Playing Songs!`")
del GPC[(message.chat.id, client.me.id)]
@friday_on_cmd(
["rvc"],
is_official=False,
cmd_help={"help": "Replay Song In VC!", "example": "{ch}rvc"},
)
async def replay(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
group_call.restart_playout()
await edit_or_reply(message, f"`Re-Playing : {group_call.input_filename}`")
@friday_on_cmd(
["rjvc"],
is_official=False,
cmd_help={"help": "Rejoin Voice Chat!", "example": "{ch}rjvc"},
)
async def rejoinvcpls(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
await group_call.reconnect()
await edit_or_reply(message, f"`Rejoined! - Vc`")
@friday_on_cmd(
["leavevc"],
is_official=False,
cmd_help={"help": "Leave Voice Call!", "example": "{ch}leavevc"},
)
async def leave_vc_test(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if os.path.exists(group_call.input_filename):
os.remove(group_call.input_filename)
await group_call.stop()
await edit_or_reply(message, f"`Left : {message.chat.title} - Vc`")
del GPC[(message.chat.id, client.me.id)]
@friday_on_cmd(
["setvolvc"],
is_official=False,
cmd_help={
"help": "Set Voice Call Volume!",
"example": "{ch}setvolvc (Specifically Volume Between 2-100)",
},
)
async def set_vol(client, message):
group_call = GPC.get((message.chat.id, client.me.id))
if not group_call:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
if not group_call.is_connected:
await edit_or_reply(message, "`Is Group Call Even Connected?`")
return
volume = get_text(message)
if not volume:
await edit_or_reply(message, "Volume Should Be Integer!")
return
if not volume.isdigit():
await edit_or_reply(message, "Volume Should Be Integer!")
return
if int(volume) < 2:
await edit_or_reply(message, "Volume Should Be Above 2")
return
if int(volume) >= 100:
await edit_or_reply(message, "Volume Should Be Below 100")
return
await group_call.set_my_volume(volume)
await edit_or_reply(message, f"**Volume :** `{volume}`")