使用JDA开发Discord Bot:无法检测机器人是否已加入语音频道
解决JDA机器人Join命令重复提示问题
你的核心问题是搞混了机器人自身的语音状态和命令发起用户的语音状态的判断对象。现在的代码里,你用guild.getSelfMember().getVoiceState()来检查用户是否在频道,这完全搞反了,而且漏掉了对机器人自身状态的检查。
修正后的完整代码如下:
public static void joinVoiceChannel(TextChannel channel, Member commandSender, Guild guild) { // 检查命令发起者是否在语音频道 GuildVoiceState userVoiceState = commandSender.getVoiceState(); if (userVoiceState == null || !userVoiceState.inAudioChannel()) { channel.sendMessage("You must be in a voice channel to use this command.").queue(); return; } // 检查机器人是否已经在语音频道 GuildVoiceState botVoiceState = guild.getSelfMember().getVoiceState(); if (botVoiceState != null && botVoiceState.inAudioChannel()) { channel.sendMessage("I'm already in a voice channel!").queue(); return; } AudioChannel audioChannel = userVoiceState.getChannel(); if (audioChannel == null) { channel.sendMessage("Failed to join voice channel.").queue(); return; } net.dv8tion.jda.api.managers.AudioManager audioManager = guild.getAudioManager(); audioManager.openAudioConnection(audioChannel); channel.sendMessage("Joined voice channel: " + audioChannel.getName()).queue(); }
关键改动说明:
- 新增
commandSender参数,用来获取发起命令的用户成员对象,从而拿到用户的语音状态,这才是判断用户是否在频道的正确对象 - 单独获取机器人自身的
VoiceState,提前判断机器人是否已经在语音频道,如果是则直接返回提示,避免重复执行连接操作 - 修正了原代码中用机器人状态判断用户是否在频道的逻辑错误
内容的提问来源于stack exchange,提问作者Yago Andrade
相关产品推荐
相关产品推荐

