将ctx命令转换为Interaction命令:音乐Bot语音播放方法缺失问题
解决方案
针对斜杠命令下语音播放的问题,按以下步骤处理(基于interactions.py库):
- 先确保Bot已成功加入目标语音频道,只有连接后
ctx.guild.voice_client才会返回有效的VoiceClient实例,否则会是None。 - interactions.py中
VoiceClient的play方法是存在的,若Pylance提示找不到方法,大概率是类型推断错误,可通过类型断言强制指定类型,解决提示问题。 - 注意interactions.py中创建FFmpeg播放器的方法是异步的,需要用
await调用。
完整代码示例
from interactions import Client, Intents, slash_command, SlashContext, VoiceClient # 初始化Bot,需开启语音状态意图 bot = Client(intents=Intents.DEFAULT | Intents.GUILD_VOICE_STATES) @slash_command(name="join", description="加入当前用户的语音频道") async def join_channel(ctx: SlashContext): if not ctx.author.voice: await ctx.send("你需要先加入一个语音频道!") return # 连接到用户所在的语音频道 await ctx.author.voice.channel.connect() await ctx.send(f"已加入频道:{ctx.author.voice.channel.name}") @slash_command(name="play", description="播放指定音频文件") async def play_audio(ctx: SlashContext): voice_client = ctx.guild.voice_client if not voice_client: await ctx.send("我还没加入任何语音频道,请先使用/join命令!") return # 类型断言,解决Pylance的类型提示问题 assert isinstance(voice_client, VoiceClient) # 创建FFmpeg播放器(异步方法,需加await) player = await voice_client.create_ffmpeg_player("test.mp3") # 调用play方法播放,传入错误回调 voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None) await ctx.send("音乐开始播放!") bot.start("你的Bot令牌")
额外注意事项
- 确保已安装最新版interactions.py:
pip install -U interactions.py - 若使用外部音频源(如YouTube链接),需额外安装
yt-dlp,并在创建播放器时直接传入链接地址。
内容的提问来源于stack exchange,提问作者Artemis Fox
相关产品推荐
相关产品推荐

