hoojpop
@hoojpop

Как исправить ошибку воспроизведения музыки для Discord бота?

Привет. Пишу бота для собственного сервера. Решил реализовать команду воспроизведения музыки по ссылке простой командой .play url. Использую библиотеку discord.py, а для музыки youtube_dl. Нашёл способ как сделать, но основная библиотека уже более улучшенная и тот способ совсем не подходит, поэтому возникают ошибки. Ошибок осталось мало, две ошибки уже решил. Суть в том, что discord.py с youtube_dl не хочет видимо работать, либо я не понимаю суть ошибки, либо я что-то просто делаю не так. Даже пришлось из discord.py импортировать функцию VoiceClient.

Ошибка:

Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\Степан\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/Степан/Desktop/Clown/main.py", line 57, in play
    player = await voice_client.create_ytdl_player(url)
AttributeError: 'VoiceClient' object has no attribute 'create_ytdl_player'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Степан\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Степан\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Степан\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceClient' object has no attribute 'create_ytdl_player'


Код:

import discord
import config
import random
import variables
import youtube_dl
from discord import utils
from discord.ext import commands
from discord.voice_client import VoiceClient

client = commands.Bot(command_prefix='.')
players = {}


@client.command(pass_context=True)
async def play(ctx, url):
    channel = ctx.author.voice.channel
    await channel.connect()
    server = ctx.message.guild 
    voice_client = discord.utils.find(lambda c: c.guild.id == server.id, client.voice_clients)
    player = await voice_client.create_ytdl_player(url) # < Ошибка возникает тут
    players[server.id] = player
    player.start()
  • Вопрос задан
  • 1014 просмотров
Пригласить эксперта
Ответы на вопрос 1
JiMoon
@JiMoon
меня тут ненавидят, потому что я говнокодер.
документацию читали? нет такой функции у VoiceChannel
я хочу вам предложить свой код, который у меня
попробуйте, может быть сработает
@client.command()
	async def play(self, ctx, url: str):
		song_there = os.path.isfile('song.mp3')
		try:
			if song_there:
				os.remove('song.mp3')
				print('[Voice] Удаляю старый файл...')
		except PermissionError:
			print('[Voice] Не удалось удалить старый файл')

		await ctx.send('Пожалуйста, ожидайте...')

		voice = discord.utils.get(self.client.voice_clients, guild = ctx.guild)


		with youtube_dl.YoutubeDL(ydl_opts) as ydl:
			print('[Voice] Загружаю музыку...')
			ydl.download([url])

		for file in os.listdir('./'):
			if file.endswith('.mp3'):
				name = file
				print(f'[Voice] Переименовываю файл: {name}')
				os.rename(file, 'song.mp3')

		voice.play(discord.FFmpegPCMAudio('song.mp3'), after = lambda e: print(f'[Voice] {name} закончила свое проигрывание'))
		voice.source = discord.PCMVolumeTransformer(voice.source)
		voice.source.volume = 0.07

		await ctx.send(f'Сейчас играет: {url}')
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы