首页 > 解决方案 > 如何避免在 discord.py 中触发事件?

问题描述

我希望我的机器人在断开连接时重新连接到语音通道,所以我使用以下代码:

@bot.event
async def on_voice_state_update(member, before, after):
    if member.id == bot.id and after.channel == None and before.channel != None:
        voiceChannel = before.channel #get the channel to reconnect to
        await voiceChannel.connect()  #reconnect to that voice channel

效果很好,但是当我尝试断开机器人与代码的连接时: await voiceChannel.disconnect(),机器人重新加入语音通道。那么有什么办法可以避免触发on_voice_state_update吗?

我试过的:

由此我没有得到有用的结果。

标签: pythoneventsdiscord.py

解决方案


做一个布尔值来检查它是有意断开还是需要重新连接。
我假设断开连接的部分是一个命令:

# Put this variable at the top of the entire code
disconnecting = False # You can also make this as an attribute of the bot instance

@bot.command()
async def disconnect(ctx):
    # ... Code before
    disconnecting = True
    await ctx.voice_client.disconnect()

@bot.event
async def on_voice_state_update(member, before, after):
    if disconnecting:
        disconnecting = False  # Reset the variable for future use.
        return # Do not let the following occur
    if member.id == bot.id and after.channel == None and before.channel != None:
        voiceChannel = before.channel #get the channel to reconnect to
        await voiceChannel.connect()  #reconnect to that voice channel

推荐阅读