python - 如何检查机器人连接的语音通道 ID?(discord.py)
问题描述
我有一个机器人,只有当调用它的用户在同一个语音通道中时,我才想听命令。这是我的代码。
@bot.command(name='leave', help='Disconnects the bot.')
async def leave(ctx):
user_channel = ctx.message.author.voice.channel
bot_channel = ctx.guild.voice_client
print(user_channel)
print(bot_channel)
if user_channel == bot_channel:
client = ctx.guild.voice_client
await client.disconnect()
else:
await ctx.send('You have to be connected to the same voice channel to disconnect me.')
但是,我的问题是那些打印行返回不同的字符串。用户通道:vc 2,机器人通道:<\discord.voice_client.VoiceClient object at 0x000001D4E168FB20> 如何让它们都读取语音通道的 ID,以便比较它们?
解决方案
您的代码的唯一问题是您将用户当前的语音通道对象与语音客户端对象进行比较。您可以添加.channel
到ctx.guild.voice_client
.
比较两个通道对象的作用与比较通道的 ID 相同。如果您真的想通过它们的 ID 比较它们,那么只需添加.id
到它们中的每一个。
例子:
@bot.command(help='Disconnects the bot.')
async def leave(ctx):
if ctx.author.voice.channel and ctx.author.voice.channel == ctx.voice_client.channel:
# comparing channel objects ^
await ctx.voice_client.disconnect()
else:
await ctx.send('You have to be connected to the same voice channel to disconnect me.')
请注意,ctx.author.voice.channel and
如果命令执行器和机器人都不在通道中,我添加了这样您就不会遇到属性错误。
如果您不检查其中一个对象是否不是None
,那么您会收到一条错误消息,指出NoneType
没有disconnect()
像表达式None == None
那样的属性True
并运行该语句。
参考:
推荐阅读
- linux - 在数组的 --data-binary 参数中使用 curl 进行迭代
- google-bigquery - 使用 Apache Beam/Dataflow 从 BigQuery 读取数据时使用 fastavro
- operating-system - 从内核 BSS 部分的虚拟地址中查找物理页号
- javascript - 如何共享正确编码的网址?
- css - 边框重叠时如何消除间隙
- c# - 用于应用角色映射的 Active Directory 集成
- excel - 创建一个宏,该宏在定义的变量范围内选择/取消选择所有复选框
- jquery - 使用 ajax/json 返回带有模型的部分视图标记
- c - 输出自定义扫描码的键盘中断处理程序不起作用 - linux
- c# - 使用 xamarin 表单查看图像