【问题标题】:Discord.js display the number of bans in statusDiscord.js 显示状态中的禁令数量
【发布时间】:2021-05-05 11:41:17
【问题描述】:

我有一个用于特定服务器的机器人,我想将状态设置为服务器的封禁数。

我有以下代码,但我无法获得banned.size

client.on("ready", () => {
  message.guild.fetchBans().then(banned => {
    let sizee = banned.size
  })

  setInterval(function() {
    let lol = ['status 1', `status 2`, `Status 3`, `status 4`, `this guild has ${sizee} banned users `];
    let f = ['LISTENING', 'WATCHING', 'LISTENING', 'PLAYING', 'WATCHING'];
    let status = lol[Math.floor(Math.random()*lol.length)];
    client.user.setActivity(status, {type: f[Math.floor(Math.random()*f.length)]})
  }, 15000) 
  
  client.user.setPresence({ status: 'online' })

  console.log(`Logged in as ${client.user.tag}!`);
});

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    您在ready 事件中没有或没有收到message 对象,因此您无法从中获得公会。您将需要通过其 ID 找到公会。 client.guilds.cache.get() 应该可以解决问题。

    一旦你有了公会,你需要将fetchBans() 移动到setInterval 的回调中,所以它每次都会获取它。如果你在它之外获取它,它只会在你启动机器人时获取一次,并且除非你重新启动你的机器人,否则它不会被更新。

    您可以使用异步函数而不是与thens 纠缠不清,而只需await 结果。

    如果您添加公会 ID,以下示例将起作用。我也添加了一些 cmets:

    client.on('ready', () => {
      // get the guild once the bot is ready
      // make sure you add the guild id
      const guild = client.guilds.cache.get('ADD GUILD ID HERE');
    
      client.user.setPresence({ status: 'online' });
    
      // run the updateStatus function every 15s
      // we need to pass the client and guild
      setInterval(updateStatus, 15000, client, guild);
    
      console.log(`Logged in as ${client.user.tag}!`);
    });
    
    // helper function to pick a random element from an array
    function pickOne(arr) {
      return arr[Math.floor(Math.random() * arr.length)];
    }
    
    // async function that fetches the current number of bans
    // and updates the status
    async function updateStatus(client, guild) {
      const bans = await guild.fetchBans();
      const statuses = [
        'status 1',
        'status 2',
        'status 3',
        'status 4',
        `this guild has ${bans.size} banned users`,
      ];
      const activities = [
        'LISTENING',
        'WATCHING',
        'LISTENING',
        'PLAYING',
        'WATCHING',
      ];
    
      client.user.setActivity(pickOne(statuses), {
        type: pickOne(activities),
      });
    }
    

    PS:一项改进是仅在您想在状态中显示禁令时才获取禁令。

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2020-12-08
      • 2018-01-28
      • 2022-10-22
      • 2021-04-18
      • 2021-07-27
      • 1970-01-01
      • 2021-02-22
      • 2021-01-18
      相关资源
      最近更新 更多