Discord.js v13实现用户进出语音频道时Bot播音频后离开
解决方案
核心思路
把播放音频后自动离开的逻辑封装成通用函数,避免重复代码;在voiceStateUpdate事件中准确判断用户的加入/离开行为,调用对应音频的播放逻辑。
完整代码
const { Client, GatewayIntentBits, joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); // 封装播放音频后自动离开的通用函数 async function playAudioAndLeave(channelId, guildId, adapterCreator, audioPath) { try { // 连接到语音频道 const connection = joinVoiceChannel({ channelId, guildId, adapterCreator }); const player = createAudioPlayer(); connection.subscribe(player); // 创建音频资源 const resource = createAudioResource(audioPath); player.play(resource); // 监听音频播放结束事件,播放完就断开连接 player.on(AudioPlayerStatus.Idle, () => { connection.destroy(); }); // 处理播放错误 player.on('error', error => { console.error(`音频播放出错: ${error.message}`); connection.destroy(); }); } catch (error) { console.error(`连接语音频道失败: ${error.message}`); } } client.on('voiceStateUpdate', (oldState, newState) => { // 排除Bot自身的状态变化 if (newState.member.user.bot) return; // 用户加入语音频道(从无频道到有频道) if (oldState.channelId === null && newState.channelId !== null) { console.log("用户加入语音频道"); playAudioAndLeave( newState.channelId, newState.guild.id, newState.guild.voiceAdapterCreator, './files/riff.mp3' ); } // 用户离开语音频道(从有频道到无频道) else if (oldState.channelId !== null && newState.channelId === null) { console.log("用户离开语音频道"); playAudioAndLeave( oldState.channelId, oldState.guild.id, oldState.guild.voiceAdapterCreator, './files/leave-audio.mp3' // 替换成你的离开音频路径 ); } }); client.login('你的Bot令牌');
关键细节说明
- 通用函数封装:
playAudioAndLeave函数把连接频道、播放音频、断开连接的逻辑整合,让代码更简洁,后续修改音频路径或播放逻辑只需改一处。 - 排除Bot自身:判断
newState.member.user.bot避免Bot自己触发事件导致循环操作。 - 播放结束自动断开:监听
AudioPlayerStatus.Idle事件,音频播放完成后立即销毁连接,确保Bot自动离开频道。 - 错误处理:添加播放错误和连接错误的捕获,避免程序崩溃。
内容的提问来源于stack exchange,提问作者iPad
相关产品推荐
相关产品推荐

