D
D
Denis Kulikov2021-11-14 14:31:24
Python
Denis Kulikov, 2021-11-14 14:31:24

Why does the music bot not include audio downloaded from YouTube in the voice channel of the discord?

When using the play command, *link to YouTube video* constantly gives this error: discord.ext.commands.errors.CommandInvokeError
: Command raised an exception: UnboundLocalError: local variable 'voice' referenced before assignment
ffmpeg, I downloaded it, installed it on drive C and specified the path to it in the command, but then I realized that I don’t know what arguments the .play() function takes.
Here is the code

#-*- coding: utf-8 -*-
import discord 
from discord import FFmpegPCMAudio
from discord.ext import commands 
from configMusic import token
import youtube_dl
import os

bot = commands.Bot(command_prefix='')

@bot.event
async def on_ready():
  print("Бот готов!")

#@bot.event
#async def on_message():
#	print("Пришло новое сообщение!")
server, server_id, name_channel = None, None, None
domains = ['https://www.youtube.com/', 'http://www.youtube.com/', 'https://youtube.be/', 'http://youtube.be/']
async def check_domains(link):
  for x in domains:
    if link.startswith(x):
      return True
  return False


@bot.command()
async def play(ctx, *, command = None):
  """Воспроизводит музыку"""
  global server, server_id, name_channel
  author = ctx.author
  FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
  if command == None:
    server = ctx.guild
    name_channel = ctx.author.voice.channel.name_channel
    voice_channel = discord.utils.get(server.voice_channels, name = name_channel)
    params = command.split(' ')
    if len(params) == 1:
      sourse = params[0]
      server = ctx.guild
      name_channel = ctx.author.voice.channel.name_channel
      voice_channel = discord.utils.get(server.voice_channels, name = name_channel)
      print("param 1")
    elif len(params) == 3:
      server_id = params[0]
      voice_id = params[1]
      sourse = params[2]
      try:
        server_id = int(server_id)
        voice_id = int(voice_id)
      except:
        await ctx.channel.send("{0}, id сервера или войса должно быть целочисленным".format(author.mention))
        return
      print('param 3')
      server = bot.get_guild(server_id)
      voice_channel = discord.utils.get(server.voice_channel, id=voice_id)
    else:
      await ctx.channel.send("{0}, команда не корректна!".format(author.mention))
      return
    voice = discord.utils.get(bot.voice_clients, guild = server)
    if voice is None:
      await voice_channel.connect()
      voice = discord.utils.get(bot.voice_clients, guild = server)

    if sourse == None:
      pass
    elif sourse.startswith('http'):
      if not check_domains(sourse):
        await ctx.channel.send("{0}, ссылка не является разрешенной!".format(author.mention))
        return
      song_there = os.path.isfile('C:/Users/Людмила/Desktop/Программирование/ДС Бот для музыки/music/song.mp3')
      try:
        if song_there:
          os.remove('song.mp3')
      except PermissionError:
        await ctx.channel.send('Недостаточно прав для удаления файла!')
        return
      ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessers': [
          {
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquallity': '192',
          }
        ],
      }
      with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([sourse])
      for file in os.listdir('C:/Users/Людмила/Desktop/Программирование/ДС Бот для музыки/music'):
        if file.endswith('.mp3'):
          os.rename(file, 'song.mp3')
      voice.play(discord.FFmpegPCMAudio(executable='C:/ffmpeg/bin/ffmpeg.exe',sourse = 'C:/Users/Людмила/Desktop/Программирование/ДС Бот для музыки/music/song.mp3', **FFMPEG_OPTIONS))
  else:
    voice.play(discord.FFmpegPCMAudio(executable='C:/ffmpeg/bin/ffmpeg.exe',sourse = 'C:/Users/Людмила/Desktop/Программирование/ДС Бот для музыки/music/{0}', **FFMPEG_OPTIONS).format(sourse))




bot.run(token)

I understand that the arguments are crooked (do not scold pzh), and I beg you to help the negligent.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-11-14
@Artin24

they write that the matter is in ffmpeg

The point is an attempt to use a variable that has not been declared, and this is written in the error. Namely, you voiceonly create a variable when the condition is met , if the condition fails, the block falls into a , which has only one line:if command == None:else
voice.play(discord.FFmpegPCMAudio(executable='C:/ffmpeg/bin/ffmpeg.exe',sourse = 'C:/Users/Людмила/Desktop/Программирование/ДС Бот для музыки/music/{0}', **FFMPEG_OPTIONS).format(sourse))

Which uses voice, which is not declared anywhere. The IDE should have highlighted this line. So it's worth adding the same variable creation as in the block ifabove
voice = discord.utils.get(bot.voice_clients, guild = server)
if voice is None:
    await voice_channel.connect()
    voice = discord.utils.get(bot.voice_clients, guild = server)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question