#python #discord.py
#питон #discord.py #python
Вопрос:
import discord
import youtube_dl
from discord.ext import commands
-----------------------------------------------
@cat.command(pass_context=True)
async def play(ctx):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice.client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop = client.loop)
voice_channel.play(player)
await ctx.send(f'**Music:**{player.title}')
Есть ли какой-нибудь способ исправить эту ошибку?
AttributeError: 'Guild' object has no attribute 'voice'
Ответ №1:
Проверьте этот рабочий пример.
import discord
import youtube_dl
from discord.ext import commands
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
def endSong(guild, path):
os.remove(path)
@cat.command(pass_context=True)
async def play(ctx, url):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
voice_client = await channel.connect()
guild = ctx.message.guild
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
file = ydl.extract_info(url, download=True)
path = str(file['title']) "-" str(file['id'] ".mp3")
voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
await ctx.send(f'**Music: **{url}')
Необязательная, полезная функция
Если вы хотите, вы можете заставить своего бота покинуть голосовой канал после того, как песня перестанет воспроизводиться. Добавьте это в конец вашего кода:
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
Ответ №2:
Попробуйте заменить if not ctx.message.author.voice:
на if 'voice' not in ctx.message.author:
Комментарии:
1. ошибка: voice_channel = server.voice.client AttributeError: объект ‘Guild’ не имеет атрибута ‘voice’
2. @return2749 выполните аналогичную проверку на
voice_channel = server.voice.client
, чтобы увидеть, есть ли у негоvoice
ключ:if 'voice' not in server:
…