【问题标题】:Count how many times a message has been sent with discord.js计算使用 discord.js 发送消息的次数
【发布时间】:2019-11-28 21:53:55
【问题描述】:

我只是想知道是否有一种方法可以计算在我的 Discord 服务器中发送了多少次消息,以便机器人可以发送消息。我是编码新手,所以我不知道很多事情。提前谢谢!

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    说明

    要存储在公会中发送的消息量,您必须以某种方式跟踪计数。每次发送消息时,您可以将其增加 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);
    

    【讨论】:

    • @Kikkiu 该命令的代码需要访问事件中的message 参数。它应该在message 事件侦听器中设置,或者在command handler 的命令文件中设置。
    【解决方案2】:

    如果未创建队列系统以确保不会同时对文件进行多次读取和写入,JSON 很容易损坏。出于您想要的目的,我会使用 SQLite 之类的东西,它需要最少的设置,易于学习,并且具有帮助框架使其更易于使用,例如 Keyv 和 Sequelize。

    Here 是关于如何在 nodejs 运行时环境中使用 sqlite 的一个很好的指南。

    【讨论】:

    猜你喜欢
    • 2020-06-13
    • 2020-08-04
    • 2020-07-19
    • 2018-08-25
    • 2018-04-12
    • 1970-01-01
    • 2020-12-15
    • 2020-11-25
    相关资源
    最近更新 更多