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

Discord.js v14班次记录机器人报错求助:Intents.FLAGS.GUILDS问题

Discord.js v14 班次记录机器人修复与实现方案

初始化报错修复

Discord.js v14 已彻底移除Intents.FLAGS枚举,改用GatewayIntentBits替代。你需要修改Client初始化代码,正确导入并使用GatewayIntentBits:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds, // 必备的服务器意图
    GatewayIntentBits.MessageContent // 如需处理消息内容,需开启此意图并在开发者门户启用特权网关意图
  ]
});

完整功能实现代码

以下是实现start(启动计时)、stop(停止计时并显示时长)、times(展示所有记录)功能的完整代码:

const { Client, GatewayIntentBits, SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.MessageContent
  ]
});

// 存储用户活跃计时:key为用户ID,value为开始时间戳
const activeTimers = new Map();
// 存储用户历史记录:key为用户ID,value为时长数组(单位:毫秒)
const timeRecords = new Map();

// 注册Slash命令(首次运行或更新命令时执行,完成后可注释)
client.on('ready', async () => {
  console.log(`已登录为 ${client.user.tag}`);

  const commands = [
    new SlashCommandBuilder()
      .setName('start')
      .setDescription('启动班次计时'),
    new SlashCommandBuilder()
      .setName('stop')
      .setDescription('停止计时并显示本次时长'),
    new SlashCommandBuilder()
      .setName('times')
      .setDescription('查看所有班次记录及总时长')
  ];

  try {
    await client.application.commands.set(commands);
    console.log('Slash命令注册成功');
  } catch (err) {
    console.error('命令注册失败:', err);
  }
});

// 处理交互命令
client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  const { commandName, user } = interaction;

  switch (commandName) {
    case 'start':
      if (activeTimers.has(user.id)) {
        return interaction.reply({ content: '你已经在计时中了!', ephemeral: true });
      }
      activeTimers.set(user.id, Date.now());
      await interaction.reply({ content: '班次计时已启动!', ephemeral: true });
      break;

    case 'stop':
      if (!activeTimers.has(user.id)) {
        return interaction.reply({ content: '你还没启动计时!', ephemeral: true });
      }
      const startTime = activeTimers.get(user.id);
      const duration = Date.now() - startTime;
      activeTimers.delete(user.id);

      // 转换为易读的时分秒格式
      const hours = Math.floor(duration / 3600000);
      const minutes = Math.floor((duration % 3600000) / 60000);
      const seconds = Math.floor((duration % 60000) / 1000);

      // 保存记录到历史
      if (!timeRecords.has(user.id)) timeRecords.set(user.id, []);
      timeRecords.get(user.id).push(duration);

      await interaction.reply({
        content: `计时已停止!本次时长:${hours}小时 ${minutes}分钟 ${seconds}秒`,
        ephemeral: false
      });
      break;

    case 'times':
      const userRecords = timeRecords.get(user.id);
      if (!userRecords || userRecords.length === 0) {
        return interaction.reply({ content: '你还没有任何班次记录!', ephemeral: true });
      }

      // 计算总时长并格式化每条记录
      let total = 0;
      const recordList = userRecords.map((ms, index) => {
        total += ms;
        const h = Math.floor(ms / 3600000);
        const m = Math.floor((ms % 3600000) / 60000);
        const s = Math.floor((ms % 60000) / 1000);
        return `第${index + 1}次:${h}h ${m}m ${s}s`;
      }).join('\n');

      const totalH = Math.floor(total / 3600000);
      const totalM = Math.floor((total % 3600000) / 60000);
      const totalS = Math.floor((total % 60000) / 1000);

      // 用Embed展示记录
      const embed = new EmbedBuilder()
        .setTitle('你的班次记录')
        .setDescription(recordList)
        .addFields({ name: '总时长', value: `${totalH}h ${totalM}m ${totalS}s` })
        .setColor('#2ecc71');

      await interaction.reply({ embeds: [embed], ephemeral: false });
      break;
  }
});

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

使用说明

  1. 确保已安装Discord.js v14:执行npm install discord.js
  2. 在Discord开发者门户为机器人开启Message Content Intent特权网关意图
  3. 替换代码中的你的机器人Token为实际令牌
  4. 首次运行代码会自动注册Slash命令,注册完成后可注释掉client.application.commands.set部分,避免重复注册

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:48:18