用户离开后如何断开不和谐机器人与语音通道的连接?
How to disconnect a discord bot from voice channel after user left?
我想添加一个事件,如果用户在歌曲仍在播放时离开,我的音乐机器人会立即离开语音频道。如果频道中有多个用户,机器人当然应该留在频道中。我在那里只有一种方法,但需要帮助。我会尝试以下操作:
async def check_member(self, ctx):
channel = ctx.author.voice.channel
member_count = len(voice_channel.members)
if member_count == 1:
await channel.disconnect
但不知何故这似乎不起作用。
我确实知道有一个 但这对我也不起作用,因为我定义了一些不同的东西。
我的第二次尝试是:
async def check_member(self, ctx):
channel = ctx.author.voice.channel
member_count = len(channel.members)
client = ctx.guild.voice_client
if member_count == 1:
await client.disconnect()
(也没用。)
定义does not work
:我现在以不同的方式构建函数:
@tasks.loop(seconds=2)
async def check(self, ctx):
voice_channel = ctx.author.voice.channel
member_count = len(voice_channel.members)
client = ctx.guild.voice_client
if member_count == 1:
await client.disconnect()
现在这是一个完全不同的计数。我想要做的是每 2 秒循环一次 commands.Cog.listener()
函数。为了进行测试,我播放了一首歌,并在机器人开始播放后立即离开。我以为机器人也会离开频道,但它没有。我的日志中没有输出表明我定义了错误。
循环有点低效,你可以简单地使用on_voice_state_update
事件
async def on_voice_state_update(member, before, after):
voice_state = member.guild.voice_client
# Checking if the bot is connected to a channel and if there is only 1 member connected to it (the bot itself)
if voice_state is not None and len(voice_state.channel.members) == 1:
# You should also check if the song is still playing
await voice_state.disconnect()
参考:
我想添加一个事件,如果用户在歌曲仍在播放时离开,我的音乐机器人会立即离开语音频道。如果频道中有多个用户,机器人当然应该留在频道中。我在那里只有一种方法,但需要帮助。我会尝试以下操作:
async def check_member(self, ctx):
channel = ctx.author.voice.channel
member_count = len(voice_channel.members)
if member_count == 1:
await channel.disconnect
但不知何故这似乎不起作用。
我确实知道有一个
我的第二次尝试是:
async def check_member(self, ctx):
channel = ctx.author.voice.channel
member_count = len(channel.members)
client = ctx.guild.voice_client
if member_count == 1:
await client.disconnect()
(也没用。)
定义does not work
:我现在以不同的方式构建函数:
@tasks.loop(seconds=2)
async def check(self, ctx):
voice_channel = ctx.author.voice.channel
member_count = len(voice_channel.members)
client = ctx.guild.voice_client
if member_count == 1:
await client.disconnect()
现在这是一个完全不同的计数。我想要做的是每 2 秒循环一次 commands.Cog.listener()
函数。为了进行测试,我播放了一首歌,并在机器人开始播放后立即离开。我以为机器人也会离开频道,但它没有。我的日志中没有输出表明我定义了错误。
循环有点低效,你可以简单地使用on_voice_state_update
事件
async def on_voice_state_update(member, before, after):
voice_state = member.guild.voice_client
# Checking if the bot is connected to a channel and if there is only 1 member connected to it (the bot itself)
if voice_state is not None and len(voice_state.channel.members) == 1:
# You should also check if the song is still playing
await voice_state.disconnect()
参考: