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'
答案 0 :(得分:0)
尝试将if not ctx.message.author.voice:
替换为if 'voice' not in ctx.message.author:
答案 1 :(得分:0)
youtube_dl 和 FFmpeg 进行了一些更改,因此应该可以使用。
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")
如果您在理解代码方面有任何问题,或者无法解决问题,请在我的答案下进行评论,我会尽力帮助您。顺便说一句,如果您正在考虑将机器人托管在Heroku上,那么我可以为您提供帮助,因为要使音乐机器人在那里运行,您需要做一些事情。