如何使用discord.js v12开发统计用户特定单词发送次数的bot
基于discord.js v12实现用户特定单词发送次数统计方案
实现逻辑
- 监听服务器内所有消息事件,过滤bot自身发送的消息
- 对每条消息内容做目标单词匹配,统计单次消息内的命中次数
- 以用户ID为唯一标识存储计数,写入本地文件做持久化避免重启丢失
代码实现
首先你需要在项目根目录创建wordCount.json文件作为数据存储载体,初始内容填入{}即可。
核心代码如下:
const Discord = require('discord.js'); const client = new Discord.Client(); const fs = require('fs'); // 替换为你需要统计的特定单词 const TARGET_WORD = 'hello'; // 读取已有计数数据 let wordCount = {}; if (fs.existsSync('./wordCount.json')) { wordCount = JSON.parse(fs.readFileSync('./wordCount.json', 'utf8')); } // v12版本消息监听事件为message,v13及以上版本需替换为messageCreate client.on('message', message => { // 忽略所有bot发送的消息 if (message.author.bot) return; // 转小写实现不区分大小写匹配,需要区分大小写可删除toLowerCase() const msgContent = message.content.toLowerCase(); const targetWord = TARGET_WORD.toLowerCase(); // 正则匹配完整独立单词,\b为单词边界符,不需要匹配完整单词可删除\\b const matchList = msgContent.match(new RegExp(`\\b${targetWord}\\b`, 'g')); const hitCount = matchList ? matchList.length : 0; if (hitCount > 0) { const userId = message.author.id; // 初始化新用户的计数 if (!wordCount[userId]) wordCount[userId] = 0; wordCount[userId] += hitCount; // 写入文件持久化存储 fs.writeFileSync('./wordCount.json', JSON.stringify(wordCount, null, 2)); } // 可选功能:用户输入!count查询自己的统计次数 if (message.content === '!count') { const userTotal = wordCount[message.author.id] || 0; message.channel.send(`你累计发送了${userTotal}次单词\`${TARGET_WORD}\``); } }); client.login('你的Bot授权Token');
拓展说明
- 如果需要统计多个特定单词,可将
TARGET_WORD修改为数组,循环遍历每个单词做匹配计数即可 - 服务器用户量大、消息多的场景,建议将JSON存储替换为SQLite等轻量数据库,提升读写性能
- 如果需要按服务器维度分别统计,可以在存储计数时增加服务器ID作为父级键
内容的提问来源于stack exchange,提问作者giggleshotter
相关产品推荐
相关产品推荐

