如何让不和谐机器人在断开连接后向频道发送消息?



对于我的discord bot,我希望它在离开语音通道后仅向使用命令的文本通道发送消息。我试过通过一个事件来做这件事,但是它向每个通道发送了一条消息。

下面是我的代码:
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot  


@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if not member.id == self.bot.user.id:                       
return
elif before.channel is None:                                
voice = after.channel.guild.voice_client
time = 0
while True:
await asyncio.sleep(1)                              
time += 1
if voice.is_playing() and not voice.is_paused():
time = 0
if time == 10:
await voice.disconnect()
if not voice.is_connected:                          
break



@commands.command(pass_context = True)
async def play(self, ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()

是否有一种方法来检测当机器人离开内播放命令?

on_voice_state_update事件处理程序应该处理任何类型的VoiceState变化,beforeafter保存VoiceState变化前后的数据。特别是,如果memberbefore.channel断开连接,after.channel就是None。您可以简单地在函数的开头添加这一行。

VOICE_CHANNELS = {}
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
# Make sure the member is the bot
if not member.id == self.bot.user.id:                       
return
# Bot got disconnected
if after.channel is None:
text_channel = VOICE_CHANNELS.pop(before.channel.id)
if text_channel:
await text_channel.send("Disconnected!")
# Bot got connected
elif before.channel is None:                                
voice = after.channel.guild.voice_client
time = 0
while True:
await asyncio.sleep(1)                              
time += 1
if voice.is_playing() and not voice.is_paused():
time = 0
if time == 10:
await voice.disconnect()
if not voice.is_connected:                          
break
@commands.command(pass_context = True)
async def play(self, ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
VOICE_CHANNELS[channel.id] = ctx.channel

最新更新