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

如何编写discord.js状态列表JSON文件并导入主JavaScript文件

解决Discord.js机器人状态列表移至JSON文件并导入的问题

1. 修正statuses.json文件格式

你之前写的JSON存在语法错误,且无法直接使用Discord.js的ActivityType枚举值,需改成标准JSON格式。以下提供两种可行方案:

方案A:存储对应枚举的数值

[
  {
    "name": "ABC",
    "type": 1
  },
  {
    "name": "DEF",
    "type": 3
  },
  {
    "name": "GHI",
    "type": 2
  },
  {
    "name": "JKL",
    "type": 0
  }
]

数值对应关系:

  • 0 = ActivityType.Playing
  • 1 = ActivityType.Streaming
  • 2 = ActivityType.Listening
  • 3 = ActivityType.Watching

方案B:存储类型字符串(可读性更强)

[
  {
    "name": "ABC",
    "type": "Streaming"
  },
  {
    "name": "DEF",
    "type": "Watching"
  },
  {
    "name": "GHI",
    "type": "Listening"
  },
  {
    "name": "JKL",
    "type": "Playing"
  }
]

2. 在index.js中导入并使用JSON文件

对应方案A的代码实现

直接导入JSON,利用数值匹配ActivityType:

const { Client, ActivityType } = require('discord.js');
const statuses = require('./statuses.json'); // 导入JSON文件

// 初始化客户端,记得配置所需intents
const client = new Client({ intents: ['Guilds'] });

client.on('ready', (c) => {
  console.log(`✅ ${c.user.tag} is online!`);
  setInterval(() => {
    const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
    client.user.setActivity({
      name: randomStatus.name,
      type: randomStatus.type
    });
  }, 10000);
});

client.login('你的机器人Token');

对应方案B的代码实现

先创建字符串到ActivityType的映射,再使用:

const { Client, ActivityType } = require('discord.js');
const statuses = require('./statuses.json');

// 建立类型字符串与枚举的映射
const typeMap = {
  'Playing': ActivityType.Playing,
  'Streaming': ActivityType.Streaming,
  'Listening': ActivityType.Listening,
  'Watching': ActivityType.Watching
};

const client = new Client({ intents: ['Guilds'] });

client.on('ready', (c) => {
  console.log(`✅ ${c.user.tag} is online!`);
  setInterval(() => {
    const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
    client.user.setActivity({
      name: randomStatus.name,
      type: typeMap[randomStatus.type]
    });
  }, 10000);
});

client.login('你的机器人Token');

注意事项

  • 确保statuses.json与index.js在同一目录,若不在需调整require路径(如./config/statuses.json)
  • Discord.js v14+版本必须配置正确的intents,否则机器人无法正常启动
  • JSON文件需严格遵循语法:键名必须用双引号,对象/数组末尾不能留多余逗号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:10:25