You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Discord音乐机器人无法加入频道播放音乐求助

解决Discord音乐机器人!play命令无响应的问题

看起来你遇到的核心问题是机器人没有处理!play命令的逻辑,再加上一些潜在的语法/配置问题,导致命令触发后没有任何反应。我帮你一步步排查并解决:

1. 先修正代码中的语法错误

你代码里的这一行有明显问题:

const { prefix } = ('./config.json');

这是错误的配置文件导入方式,应该使用require来加载本地JSON文件,改成:

const { prefix } = require('./config.json');

如果不修正这一步,prefix变量可能无法正确获取,虽然你说其他命令正常,但这是基础语法问题必须解决。

2. 添加消息监听与!play命令处理逻辑

你的现有代码只监听了ready事件,完全没有处理用户发送的消息!机器人根本不知道要响应!play命令。你需要添加message事件监听,并写入play命令的核心逻辑:

首先,更新Client的创建(如果用的是discord.js v13+,必须声明intents,否则收不到消息):

const { Client, Intents } = require('discord.js');
// 声明需要的核心权限:服务器、消息、语音状态
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });

然后添加消息处理逻辑和播放函数:

client.on('message', async message => {
  // 忽略机器人自己的消息,以及不是前缀开头的消息
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  // 拆分命令和参数
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  // 处理!play命令
  if (command === 'play') {
    // 检查用户是否在语音频道
    const voiceChannel = message.member.voice.channel;
    if (!voiceChannel) {
      return message.reply('你得先加入一个语音频道才能让我播放音乐呀!');
    }

    // 检查机器人权限
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
      return message.reply('我需要「连接语音频道」和「发言」的权限才能工作哦!');
    }

    // 获取YouTube歌曲信息
    try {
      const songInfo = await ytdl.getInfo(args[0]);
      const song = {
        title: songInfo.videoDetails.title,
        url: songInfo.videoDetails.video_url,
      };

      // 处理队列逻辑
      let serverQueue = queue.get(message.guild.id);
      if (!serverQueue) {
        const queueConstruct = {
          textChannel: message.channel,
          voiceChannel: voiceChannel,
          connection: null,
          songs: [],
          volume: 5,
          playing: true,
        };
        queue.set(message.guild.id, queueConstruct);
        queueConstruct.songs.push(song);

        // 连接语音频道并开始播放
        try {
          const connection = await voiceChannel.join();
          queueConstruct.connection = connection;
          play(message.guild, queueConstruct.songs[0]);
        } catch (err) {
          console.error(err);
          queue.delete(message.guild.id);
          return message.reply(`连接失败:${err}`);
        }
      } else {
        // 歌曲加入队列
        serverQueue.songs.push(song);
        return message.reply(`${song.title} 已经添加到播放队列啦!`);
      }
    } catch (err) {
      console.error(err);
      return message.reply('无法获取歌曲信息,请检查链接是否有效!');
    }
  }

  // 这里可以添加其他命令(比如!stop、!skip)的处理逻辑
});

// 播放歌曲的核心函数
function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if (!song) {
    // 队列空了就离开语音频道
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }

  // 创建音频流并播放
  const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on('finish', () => {
      // 歌曲结束后播放下一首
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on('error', err => console.error(`播放出错:${err}`));
  
  dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  serverQueue.textChannel.send(`正在播放:**${song.title}**`);
}

3. 检查依赖与版本适配

确保你已经正确安装了所有依赖:

npm install discord.js ytdl-core dotenv

如果你的discord.js版本是v14+,intents的写法会略有不同,需要改成:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds, 
    GatewayIntentBits.GuildMessages, 
    GatewayIntentBits.GuildVoiceStates,
    GatewayIntentBits.MessageContent // 这个需要在Discord开发者面板启用消息内容特权
  ] 
});

同时要去Discord开发者面板的机器人设置里,开启「Message Content Intent」特权,否则无法读取消息内容。

4. 最后验证

  • 再次确认机器人的权限配置(「连接」「发言」「读取消息」这些权限必须勾选)
  • 重启机器人,然后在频道发送!play [YouTube链接]测试

内容的提问来源于stack exchange,提问作者MHV

火山引擎 最新活动