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

使用Node.js实现Discord !info命令:从JSON筛选用户分类

实现Discord !info 命令:从JSON文件获取用户信息

1. 前期准备

  • 安装Node.js环境,通过npm install discord.js安装Discord.js库
  • 拥有Discord机器人账号,获取机器人TOKEN,并将机器人邀请到目标服务器

2. 修正JSON文件格式

你提供的JSON存在语法错误(键值对末尾缺逗号),修正后的示例如下(注意顶级对象的key需替换为用户真实Discord ID,才能实现匹配):

[
    {
        "123456789012345678": {
            "Name": "User1",
            "Tag": "#5432",
            "Account-Created": "11-04-2017"
        }
    },
    {
        "987654321098765432": {
            "Name": "User2",
            "Tag": "#9742",
            "Account-Created": "19-01-2019"
        }
    }
]

3. 编写机器人核心代码

创建index.js文件,代码如下:

const { Client, GatewayIntentBits } = require('discord.js');
const fs = require('fs');
const path = require('path');

// 初始化机器人客户端
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
});

// 从JSON文件读取并匹配用户信息
function getUserInfo(userId) {
    const jsonFilePath = path.join(__dirname, 'userinfo.json'); // 替换为你的JSON文件路径
    const rawData = fs.readFileSync(jsonFilePath);
    const userList = JSON.parse(rawData);

    // 遍历JSON数组查找对应用户ID的信息
    for (const userObj of userList) {
        if (userObj.hasOwnProperty(userId)) {
            return userObj[userId];
        }
    }
    return null;
}

// 机器人就绪提示
client.once('ready', () => {
    console.log(`已登录:${client.user.tag}`);
});

// 监听消息,处理!info命令
client.on('messageCreate', async message => {
    if (message.author.bot) return; // 忽略机器人自身消息

    if (message.content === '!info') {
        const userId = message.author.id;
        const userInfo = getUserInfo(userId);

        if (userInfo) {
            const replyMsg = `**你的账户信息:**\n` +
                           `- 用户名:${userInfo.Name}\n` +
                           `- 标签:${userInfo.Tag}\n` +
                           `- 创建日期:${userInfo['Account-Created']}`;
            await message.reply(replyMsg);
        } else {
            await message.reply('未找到你的账户信息,请联系管理员添加。');
        }
    }
});

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

4. 运行与测试

在终端执行node index.js启动机器人,用户在服务器发送!info命令后,即可收到匹配的个人信息回复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:15:27