Discord.py 机器人未连接到 VC



我正试图将我的机器人连接到命令作者所在的同一语音通道,并播放他们选择的视频。

但是,当运行以下代码时:

async def join(ctx, search: str):
vc = discord.utils.get(ctx.guild.channels, name=ctx.author.voice)
voice = await vc.connect()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
if not voice.is_playing():
await vc.connect()
author = ctx.message.author
query_string = urllib.parse.urlencode({'search_query': search})
html_content = urllib.request.urlopen('http://www.youtube.com/results?' + query_string)
search_content = html_content.read().decode()
search_results = re.findall(r'/watch?v=w+', search_content)
vid_url = f'https://www.youtube.com{search_results[0]}'
voice.play(FFmpegPCMAudio(vid_url, **FFMPEG_OPTIONS))
voice.is_playing() 

我得到这个错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'connect'

错误是说变量"vc"等于None,但我不知道为什么。我确实怀疑vc = discord.utils.get(ctx.guild.channels, name=ctx.author.voice)语句有问题

事实上,问题出在行

vc = discord.utils.get(ctx.guild.channels, name=ctx.author.voice)

具体来说,name=ctx.author.voicechannel.name上过滤,等于作者的VoiceStatus,这是完全不同的类型,永远不会匹配,所以你当然会得到None

相反,您可能希望在ctx.author.voice.channel上匹配,特别是在通道id上,而不是在name上匹配,以避免潜在的冲突。

总之,你想要:

vc = discord.utils.get(ctx.guild.channels, id=ctx.author.voice.channel.id)

我还加入了一个if语句来检查用户/作者是否确实在语音通道中,否则ctx.author.voice.channel.id本身将引发AttributeError,因为如果他们发送命令时不在语音通道,channel将是None