Я пишу музыкального бота для Discorda, но выводит ошибки. Не могу понять в чем именно проблема?

import discord
from discord.ext import commands
from Config import settings

import youtube_dl
import os

intents=discord.Intents.all()
intents.message_content = True

bot = commands.Bot(command_prefix=settings['prefix'],intents=intents)

@bot.event
async def on_ready():
    print(f'Бот {bot.user.name} онлайн!')


@bot.command()
async def hello(ctx):
    author = ctx.message.author
    await ctx.send(f'Привет,{author.mention}! Я Диджей-Енот')

server, server_id, name_channel = None, None, None

domains = ['https://www.youtube.com/','http://www.youtube.com/','https://www.youtu.be/','http://www.youtu.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
    if command == None:
        server = ctx.guild
        name_channel = author.voice.channel.name
        voice_channel = discord.utils.get(server.voice.channels, name=name_channel)
    params = command.split(' ')
    if len(params) == 1:
        url = params[0]
        server = ctx.guild
        name_channel = author.voice.channel.name
        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]
        url = params[2]
        try:
            server_id = int(server_id)
            voice_id = int(voice_id)
        except:
            await ctx.channel.send(f'{author.mention}, id сервера или войса должно быть целочисленным!')
            return
        print('param 3')
        server = bot.get_guild(server_id)
        voice_channel = discord.utils.get(server.voice_channels, id=voice_id)
    else:
        await ctx.channrl.send(f'{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 url == None:
        pass
    elif url.startswith('http'):
        if not check_domains(url):
            await ctx.channel.send(f'{author.mention}, ссылка не является разрешенной!')
            return
        song_there = os.path.isfile('song.mp3')
        try:
            if song_there:
                os.remove('song.mp3')
        except PermissionError:
            await ctx.channel.send('Системная ошибка!')
            return

        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [
                {
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }
            ],
        }

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
        for file in os.listdir('music/'):
            if file.endswith('mp3'):
                os.rename(file, 'song.mp3')
        voice.play(discord.FFmpegPCMAudio('music/song.mp3'))
    else:
        voice.play(discord.FFmpegPCMAudio(f'music/{url}'))


bot.run(settings['token'])


Ошибка:

[2023-09-22 00:08:55] [ERROR   ] discord.ext.commands.bot: Ignoring exception in command play
Traceback (most recent call last):
  File "C:\Users\TukTik\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\TukTik\PycharmProjects\Music_Discord_Bot\bot.py", line 45, in play
    voice_channel = discord.utils.get(server.voice.channels, name=name_channel)
                                      ^^^^^^^^^^^^
AttributeError: 'Guild' object has no attribute 'voice'

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

Traceback (most recent call last):
  File "C:\Users\TukTik\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\TukTik\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\TukTik\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'voice'
  • Вопрос задан
  • 110 просмотров
Решения вопроса 1
Vindicar
@Vindicar
RTFM!
Ну тебе же прямым английским текстом написано: ты обращаешься к объекту, описывающему сервер(гильду), и пытаешься у него добыть свойство voice, а такого свойства нет.
server.voice.channels - получить у объекта сервер свойство voice, а у объекта в этом свойстве - свойство channels.
И в документации свойства voice у объектов класса Guild тоже нет. Зато есть voice_channels.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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