基于discord.js实现JSON文件查询与指定频道回复功能
Discord.js 实现姓名查询指令功能
步骤1:准备工作
- 确保已安装
discord.js,执行命令安装:npm install discord.js - 修正JSON文件格式(原文件中的中文引号会触发解析错误,需替换为英文引号),保存为
users.json:
[ { "name": "jack", "age": "18", "id": "1500" } ]
步骤2:核心代码实现
创建机器人主文件(如 index.js),写入以下代码:
const { Client, GatewayIntentBits } = require('discord.js'); const fs = require('fs'); // 初始化客户端,开启必要权限意图 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); // 读取本地JSON用户数据 const usersData = JSON.parse(fs.readFileSync('./users.json', 'utf8')); // 机器人就绪提示 client.once('ready', () => { console.log(`已登录:${client.user.tag}`); }); // 监听消息事件 client.on('messageCreate', (message) => { // 忽略机器人自身发送的消息 if (message.author.bot) return; // 匹配!name指令格式 const commandMatch = message.content.match(/^!name (\w+)$/); if (!commandMatch) return; const targetName = commandMatch[1].toLowerCase(); // 查询对应姓名的用户 const matchedUser = usersData.find(item => item.name.toLowerCase() === targetName); if (matchedUser) { // 按预期格式拼接回复内容 const reply = `name: ${matchedUser.name}\nage: ${matchedUser.age}\nid: ${matchedUser.id}`; // 发送到当前频道,若需指定固定频道,替换为client.channels.cache.get('目标频道ID').send(reply) message.channel.send(reply); } else { message.channel.send(`未找到姓名为${targetName}的用户`); } }); // 替换为你的机器人Token后启动 client.login('你的Bot Token');
关键说明
- 权限配置:必须在Discord开发者门户的机器人设置中开启
Message Content Intent,否则无法读取消息内容 - 指令匹配:用正则表达式精准匹配
!name开头的指令,提取姓名参数 - 查询逻辑:使用
Array.find()查找匹配条目,忽略大小写提升交互友好度 - 频道选择:示例默认回复到消息所在频道,如需固定频道,替换为目标频道ID即可
测试验证
启动机器人后,在Discord频道发送!name jack,即可得到预期格式的用户信息回复。
内容的提问来源于stack exchange,提问作者Kaya
相关产品推荐
相关产品推荐

