使用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
相关产品推荐
相关产品推荐

