Проблема с кодом Бот Дискорд

Рейтинг: 1Ответов: 1Опубликовано: 01.04.2023
Такая проблема, нужна помощь чтобы музыкальный бот проигрывал любую песню через ссылку на видео ютуба, или другую платформу, а то бот только из директория берет скачанную песню и воспроизводит в голосовом канале, помогите пожалуйста изменить код либо исправить чтоб любую песню мог воспроизводить.

Сам код

# Параметры для проигрывания музыки
ydl_opts = {
    'format': 'bestaudio/best',
    'quiet': True,
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

class MusicPlayer:
    def __init__(self, ctx):
        self.ctx = ctx
        self.voice_client = get(bot.voice_clients, guild=ctx.guild)
        self.queue = []

    async def join(self):
        if not self.voice_client:
            self.voice_client = await self.ctx.author.voice.channel.connect()

    async def leave(self):
        if self.voice_client:
            await self.voice_client.disconnect()
            self.voice_client = None

    async def play(self):
        while len(self.queue) > 0:
            url = self.queue.pop(0)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)
                filename = ydl.prepare_filename(info)
                source = discord.FFmpegPCMAudio(filename)
                self.voice_client.play(source)
                embed = discord.Embed(title="Проигрывание музыки", description=f"Проигрывается {info['title']} ({info['duration']//60}:{info['duration']%60})", color=0x00ff00)
                await self.ctx.send(embed=embed)
                while self.voice_client.is_playing():
                    await asyncio.sleep(1)

    def add_to_queue(self, url):
        self.queue.append(url)


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')


@bot.command(name='join', aliases=['j'])
async def join(ctx):
    player = MusicPlayer(ctx)
    await player.join()


@bot.command(name='leave', aliases=['l'])
async def leave(ctx):
    player = MusicPlayer(ctx)
    await player.leave()


@bot.command(name='play', aliases=['p'])
async def play(ctx, url):
    player = MusicPlayer(ctx)
    player.add_to_queue(url)
    await player.play()

Ответы

▲ 0

Для того чтобы бот мог проигрывать музыку из любой платформы, а не только из локальной директории, вам нужно использовать библиотеку youtube_dl для загрузки аудио-стрима с YouTube, а затем передавать этот стрим в объект discord.FFmpegPCMAudio для воспроизведения в голосовом канале.

Вот как может выглядеть исправленный код:

import youtube_dl

class MusicPlayer:
    def __init__(self, ctx):
        self.ctx = ctx
        self.voice_client = None
        self.queue = []

    async def join(self):
        if not self.voice_client:
            self.voice_client = await self.ctx.author.voice.channel.connect()

    async def leave(self):
        if self.voice_client:
            await self.voice_client.disconnect()
            self.voice_client = None

    async def play(self):
        while len(self.queue) > 0:
            url = self.queue.pop(0)
            ydl_opts = {
                'format': 'bestaudio/best',
                'quiet': True,
            }
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)
                url = info['url']
                source = await discord.FFmpegOpusAudio.from_probe(url)
                self.voice_client.play(source)
                embed = discord.Embed(title="Проигрывание музыки", description=f"Проигрывается {info['title']} ({info['duration']//60}:{info['duration']%60})", color=0x00ff00)
                await self.ctx.send(embed=embed)
                while self.voice_client.is_playing():
                    await asyncio.sleep(1)

    def add_to_queue(self, url):
        self.queue.append(url)

@bot.command(name='play', aliases=['p'])
async def play(ctx, url):
    player = MusicPlayer(ctx)
    await player.join()
    player.add_to_queue(url)
    await player.play()

В этом коде мы использовали метод discord.FFmpegOpusAudio.from_probe для получения аудио-стрима с YouTube, и затем передали его в метод play объекта discord.VoiceClient для воспроизведения в голосовом канале. Также мы убрали параметр preferredcodec из ydl_opts, потому что он не нужен при использовании discord.FFmpegOpusAudio.

Надеюсь, мой ответ вам поможет.