我正在为我的discord.py机器人的音乐模块编写一个离开命令。我想让机器人在有人使用>leave时说出一条消息,而机器人不是在VC中。我试着在下面写出来,但每当机器人在VC中,当我输入>leave时,它会显示下面的两个消息,但当机器人不在VC中时,这不会发生。我根本没有得到任何错误。我的问题是,我怎样才能让我的机器人说,“我甚至不在你这个怪胎的VC里。”当有人只使用>leave而机器人不是VC的时候?
@bot.command()
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
await ctx.send("I have left the VC.")
if not voice.is_connected():
await ctx.send("I'm not even in a VC you weirdo.")发布于 2021-05-13 12:04:43
问题是,当执行await voice.disconnect()时,voice.is_connected()将输出false,因为机器人确实与您之前的命令断开了连接,因此将执行第一个if语句下面的if语句。有两种方法可以修复它,一种是推荐的方法是使用elif,另一种是交换if语句:
elif示例
@bot.command()
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
await ctx.send("I have left the VC.")
elif not voice.is_connected():
await ctx.send("I'm not even in a VC you weirdo.")切换到示例
@bot.command()
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if not voice.is_connected():
await ctx.send("I'm not even in a VC you weirdo.")
if voice.is_connected():
await voice.disconnect()
await ctx.send("I have left the VC.")正如knosmos在评论中指出的那样,你也可以只使用else语句:
@bot.command()
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
await ctx.send("I have left the VC.")
else:
await ctx.send("I'm not even in a VC you weirdo.")发布于 2021-05-13 12:07:32
您还可以使用else语句而不是elif来使代码更简洁:
@bot.command()
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
await ctx.send("I have left the VC.")
else:
await ctx.send("I'm not even in a VC you weirdo.")发布于 2021-05-13 12:08:36
许多人已经在前面的答案中解释了该做什么。我下面的代码可以帮助你更好地理解你当前的逻辑。
x = True
if x:
print('True')
x = False
if not x:
print('False')首先,我们将x设置为True。然后我们检查x是否为真。如果是这样,我们可以打印出来,并将x设置为false。最后,我们将检查x是否为false,并且确定无疑。所以我们打印false。
同样的事情也发生在你身上。您检查是否已连接,如果已连接,则离开。然后,你要检查自己是否在风投公司。
因此,就像很多人所说的,你可以使用elif语句来检查你是否不在vc中,或者你可以使用else语句。
对,是这样
x = True
if x:
print('True')
x = False
elif not x:
print('False')
`https://stackoverflow.com/questions/67513716
复制相似问题