javascript - 计算使用 discord.js 发送消息的次数
问题描述
我只是想知道是否有一种方法可以计算在我的 Discord 服务器中发送了多少次消息,以便机器人可以发送消息。我是编码新手,所以我不知道很多事情。先感谢您!
解决方案
解释
要存储在公会中发送的消息量,您必须以某种方式跟踪计数。每次发送消息时,您可以将其增加 1。然后,根据用户的请求,您可以显示该数字。
一个简单的选择是将每个公会的“消息计数”存储在 JSON 文件中。但是,这会极大地影响性能。考虑一个数据库以获得更好的速度和可靠性。
示例设置
在使用此系统之前,请创建一个guilds.json
带有空白对象 ( {}
) 的文件。
声明必要的变量...
const fs = require('fs'); // fs is the built-in Node.js file system module.
const guilds = require('./guilds.json'); // This path may vary.
将系统添加到message
事件侦听器...
client.on('message', message => {
// If the author is NOT a bot...
if (!message.author.bot) {
// If the guild isn't in the JSON file yet, set it up.
if (!guilds[message.guild.id]) guilds[message.guild.id] = { messageCount: 1 };
// Otherwise, add one to the guild's message count.
else guilds[message.guild.id].messageCount++;
// Write the data back to the JSON file, logging any errors to the console.
try {
fs.writeFileSync('./guilds.json', JSON.stringify(guilds)); // Again, path may vary.
} catch(err) {
console.error(err);
}
}
});
在命令中使用系统...
// Grab the message count.
const messageCount = guilds[message.guild.id].messageCount;
// Send the message count in a message. The template literal (${}) adds an 's' if needed.
message.channel.send(`**${messageCount}** message${messageCount !== 1 ? 's' : ''} sent.`)
.catch(console.error);
推荐阅读
- typescript - 这是一个有效的打字稿声明文件吗?
- sql - 如何查看我在 sql 中创建的表的列表
- django - Django 注释和 GROUP BY
- ios - IOS启动时如何区分通知是本地通知还是远程通知
- excel - Excel - 如何在每行中创建不同数量的列?
- ios - Swift 4 数组内置方法“min()”和“max()”是否适用于字符串数组?
- excel - 在 VBA 中执行脚本后退出 Cmd 窗口
- apache - Apache 服务器未在 webmin 上启动
- delphi - CreateProcess , WaitForSingleObject , 在调用应用程序时禁用输入
- php - 一旦表单的值在php的数据库中,如何使表单消失