H
H
hoojpop2020-03-13 13:30:08
Python
hoojpop, 2020-03-13 13:30:08

How to fix music playback error for Discord bot?

Hello. I am writing a bot for my own server. I decided to implement the command to play music by link with a simple .play url command. I use the discord.py library, and youtube_dl for music. I found a way how to do it, but the main library is already more improved and that way is not suitable at all, so errors occur. There are few mistakes left, two mistakes have already been solved. The bottom line is that discord.py with youtube_dl does not seem to want to work, or I don’t understand the essence of the error, or I’m just doing something wrong. I even had to import the VoiceClient function from discord.py.

Mistake:

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'


The code:

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()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JiMoon, 2021-12-26
@Jimoon

have you read the documentation? VoiceChannel does not have such a function,
I want to offer you my code, which I have to
try, maybe it will work

@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}')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question