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

求Discord V14版!mc指令Minecraft服务器查询Bot示例

Discord.js V14 实现MC服务器信息查询指令示例

所需依赖

先安装必要的npm包:

npm install discord.js minecraft-server-util

完整代码示例

const { Client, EmbedBuilder, GatewayIntentBits } = require('discord.js');
const { status } = require('minecraft-server-util');

// 初始化Discord客户端,开启必要意图
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent // 必须开启此意图才能读取消息内容
  ]
});

// 机器人登录成功后触发
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// 监听消息事件,处理前缀指令
client.on('messageCreate', async (message) => {
  // 忽略机器人自身消息和非!mc开头的消息
  if (message.author.bot || !message.content.startsWith('!mc')) return;

  // 提取服务器IP参数
  const args = message.content.split(' ');
  if (args.length < 2) {
    return message.reply('请提供MC服务器IP,格式:`!mc 服务器IP`');
  }
  const serverIp = args[1];
  // 拆分主机和端口,默认端口25565
  const [host, port = 25565] = serverIp.split(':');

  try {
    // 查询MC服务器状态
    const response = await status(host, parseInt(port), { timeout: 5000 });

    // 构建Embed回复
    const embed = new EmbedBuilder()
      .setColor('#57F287')
      .setTitle('MC服务器状态查询结果')
      .setThumbnail(`https://api.mineatar.io/face/${response.favicon.split(',')[1]}`)
      .addFields(
        { name: '服务器IP', value: `${host}:${port}`, inline: true },
        { name: '在线玩家', value: `${response.players.online}/${response.players.max}`, inline: true },
        { name: '服务器版本', value: response.version.name, inline: true },
        { name: '服务器描述', value: response.description.text || '无描述' }
      )
      .setTimestamp();

    // 若有在线玩家列表,追加到Embed
    if (response.players.sample && response.players.sample.length > 0) {
      const playerList = response.players.sample.map(p => `- ${p.name}`).join('\n');
      embed.addFields({ name: '在线玩家列表', value: playerList });
    }

    message.channel.send({ embeds: [embed] });
  } catch (error) {
    // 处理查询失败情况
    const errorEmbed = new EmbedBuilder()
      .setColor('#ED4245')
      .setTitle('查询失败')
      .setDescription(`无法连接到服务器:${error.message}`)
      .setTimestamp();

    message.channel.send({ embeds: [errorEmbed] });
  }
});

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

关键说明

  • 权限配置:需要在Discord开发者门户的机器人页面开启Message Content Intent特权意图,否则无法读取用户消息内容。
  • 服务器查询:通过minecraft-server-util库的status方法获取服务器核心信息,支持自定义超时时间。
  • Embed构建:使用Discord.js V14新增的EmbedBuilder类创建结构化消息,优化展示效果。
  • 异常处理:捕获服务器连接失败、IP无效等异常,返回明确的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:55:24