You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Bot已在线,但前缀与命令无响应问题求助

Discord Bot命令无响应问题修复

核心问题及修复步骤:

  • 事件监听错误:discord.js v14及以上版本已弃用message事件,必须改用messageCreate事件监听消息。
  • 变量大小写不匹配:定义的前缀变量是小写prefix,代码中误用大写PREFIX,导致无法正确截取命令内容。
  • Embed类错误:discord.js v14中没有RichEmbed,需使用导入的EmbedBuilder。
  • 未定义的ping函数:代码中调用了ping函数但未实现,需确保引入对应的MC服务器 ping 库(比如minecraft-server-util)。
  • 拼写错误:导入的Permsision应为Permission(不影响当前命令,但建议修正)。

修正后的完整代码:

const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permission } = require('discord.js');
const { ping } = require('minecraft-server-util'); // 先执行安装:npm install minecraft-server-util

const prefix = '>';

const client = new Client({ 
    intents: [
        GatewayIntentBits.Guilds, 
        GatewayIntentBits.GuildMessages, 
        GatewayIntentBits.MessageContent
    ] 
});

client.on('ready', () => {
    console.log('Bot has come online.')
})

client.on('messageCreate', message => {
    // 忽略机器人自身发送的消息
    if (message.author.bot) return;
    // 检查消息是否以设定前缀开头
    if (!message.content.startsWith(prefix)) return;

    let args = message.content.substring(prefix.length).split(' ');

    switch(args[0]){
        case 'mc':
            if(!args[1]) return message.channel.send('You must type a minecraft server ip');
            if(!args[2]) return message.channel.send('You must type a minecraft server port');

            ping(args[1], parseInt(args[2]), (error, response) => {
                if(error) {
                    console.error(error);
                    return message.channel.send('Failed to ping the server.');
                }
                const embed = new EmbedBuilder()
                    .setTitle('Server Status')
                    .addFields(
                        { name: 'Server IP', value: response.host },
                        { name: 'Server Version', value: response.version.name },
                        { name: 'Online Players', value: response.players.online.toString() },
                        { name: 'Max Players', value: response.players.max.toString() }
                    );
                
                message.channel.send({ embeds: [embed] });
            });
            break;
    }
});

// 替换为你的机器人令牌
client.login('YOUR_BOT_TOKEN');

额外注意事项:

  1. 确保在Discord开发者门户的Bot页面中,开启Message Content Intent权限(Privileged Gateway Intents板块)。
  2. 执行npm install discord.js minecraft-server-util安装所需依赖。
  3. 将代码中的YOUR_BOT_TOKEN替换为实际的机器人令牌。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:45:38