63 lines
2.1 KiB
Python
63 lines
2.1 KiB
Python
import discord
|
||
from discord.ext import commands
|
||
import yt_dlp
|
||
|
||
ytdl = yt_dlp.YoutubeDL({
|
||
'format': 'm4a/bestaudio/best',
|
||
# ℹ️ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
|
||
'postprocessors': [{ # Extract audio using ffmpeg
|
||
'key': 'FFmpegExtractAudio',
|
||
'preferredcodec': 'm4a',
|
||
}]
|
||
})
|
||
ytdl.params.update({
|
||
'noplaylist': True, # Avoid downloading playlists
|
||
'quiet': True, # Suppress output
|
||
'skip_download': True, # Avoid downloading files
|
||
})
|
||
|
||
class YoutubePlayer(commands.Cog):
|
||
def __init__(self, url):
|
||
infos = ytdl.extract_info(url, download=False)
|
||
self.title = infos["title"]
|
||
self.url = infos["webpage_url"]
|
||
self.duration = infos["duration"]
|
||
formats = [elem for elem in infos["formats"] if elem["audio_ext"] != "none"]
|
||
if( len(formats) == 0):
|
||
raise Exception("No audio format found")
|
||
self.audio_url = formats[0]["url"]
|
||
|
||
class Audio_Player():
|
||
def __init__(self):
|
||
self.playlist = [] # List of songs to play
|
||
self.current_song = None # Currently playing song
|
||
pass
|
||
|
||
async def play(self, ctx, url: str):
|
||
"""Play a song from a URL."""
|
||
voice_channel = ctx.author.voice.channel
|
||
|
||
await ctx.message.delete()
|
||
|
||
if ctx.voice_client is None:
|
||
await voice_channel.connect()
|
||
else:
|
||
await ctx.voice_client.move_to(voice_channel)
|
||
|
||
if ctx.voice_client.is_playing():
|
||
ctx.voice_client.stop()
|
||
|
||
audio_source = discord.FFmpegPCMAudio(YoutubePlayer(url).audio_url)
|
||
audio_transformer = discord.PCMVolumeTransformer(audio_source, 0.40)
|
||
ctx.voice_client.play(audio_transformer, after=lambda _: print(f"Finished playing: {url}"))
|
||
|
||
await ctx.send(f"Now playing: {url}")
|
||
|
||
async def stop(self, ctx):
|
||
"""Stop the current song."""
|
||
if ctx.voice_client.is_playing():
|
||
ctx.voice_client.stop()
|
||
await ctx.send("Stopped playing.")
|
||
else:
|
||
await ctx.send("Not currently playing any song.")
|
||
await ctx.voice_client.disconnect() |