Discord.py机器人$stop命令问题:仅停音频不退出语音频道
Discord.py 机器人$stop命令仅停播放不退出语音频道的处理方案
你的核心需求是触发$stop命令时只终止音频播放,让机器人留在语音频道内。先看你的原代码:
@app.command() async def stop(ctx): voice = discord.utils.get(app.voice_clients, guild=ctx.guild) if voice == None: await ctx.send(f"hey {ctx.author.mention} first bot need to join a voice channel!") elif (ctx.author.voice) == None: await ctx.send(f"hey {ctx.author.mention} first you need join to a voice channel!") else: # voice_1 = ctx.message.author.voice.channel await voice.stop()
其实await voice.stop()本身就只会停止音频播放,不会让机器人退出语音频道,但你的代码可以优化得更严谨,同时给用户更清晰的反馈:
@app.command() async def stop(ctx): voice = discord.utils.get(app.voice_clients, guild=ctx.guild) # 检查机器人是否在语音频道 if not voice: await ctx.send(f"嘿 {ctx.author.mention} 机器人还没加入语音频道呢!") return # 检查用户是否在语音频道 if not ctx.author.voice: await ctx.send(f"嘿 {ctx.author.mention} 你得先加入语音频道才行!") return # 检查是否正在播放音频,避免无效操作 if voice.is_playing(): voice.stop() await ctx.send(f"{ctx.author.mention} 已停止音频播放") else: await ctx.send(f"{ctx.author.mention} 当前没有正在播放的音频哦")
关键说明:
voice.stop()仅终止当前的音频播放任务,不会触发机器人退出语音频道的逻辑,完全符合你的需求- 新增的
voice.is_playing()检查可以避免无意义的操作,同时给用户明确的状态反馈 - 用
not voice替代voice == None,是更简洁的Python写法
内容的提问来源于stack exchange,提问作者user20310213
相关产品推荐
相关产品推荐

