首页 > 解决方案 > 计数游戏不和谐js

问题描述

呵呵大家。我创建了自己的机器人,我有很多很棒的东西,比如游戏等。但是,我想做一个计算游戏。我有一个名为“计数”的频道,我想设置我的机器人:

用户 1:456

用户 2:457

机器人:458

我的问题是,当没有其他人在计数时,我怎样才能让机器人计数?但只有一次。(看例子^^)

如果可以的话,你能给我一个示例代码吗?谢谢!!

标签: botsdiscorddiscord.jscounting

解决方案


尝试这个:

const {Client} = require('discord.js')

const client = new Client()

// Stores the current count.
let count = 0
// Stores the timeout used to make the bot count if nobody else counts for a set period of
// time.
let timeout

// Discord.js v12:
// client.on('message', ({channel, content, member}) => {
// Discord.js v13:
client.on('messageCreate', ({channel, content, member}) => {
  // Only do this for the counting channel of course
  // If you want to simply make this work for all channels called 'counting', you
  // could use this line:
  // if (client.channels.cache.filter(c => c.name === 'counting').has(channel.id))
  if (channel.id === 'counting channel id') {
    // You can ignore all bot messages like this
    if (member.user.bot) return
    // If the message is the current count + 1...
    if (Number(content) === count + 1) {
      // ...increase the count
      count++
      // Remove any existing timeout to count
      if (timeout) clearTimeout(timeout)
      // Add a new timeout
      timeout = setTimeout(
        // This will make the bot count and log all errors
        () => channel.send(++count).catch(console.error),
        // after 30 seconds
        30000
      )
    // If the message wasn't sent by the bot...
    } else if (member.id !== client.user.id) {
      // ...send a message because the person stuffed up the counting (and log all errors)
      channel.send(`${member} messed up!`).catch(console.error)
      // Reset the count
      count = 0
      // Reset any existing timeout because the bot has counted so it doesn't need to
      // count again
      if (timeout) clearTimeout(timeout)
    }
  }
})

client.login('your token')

解释

当用户(不是机器人)在计数通道中发送消息时,机器人会检查用户是否正确计数(if (Number(content) === count + 1))。
如果是,它会增加count,如果存在则删除超时 ( if (timeout) clearTimeout(timeout)),并安排机器人在 30 秒后计数 ( setTimeout(() => channel.send(++count), 30000))。
如果不是,机器人会发送一条消息,重置count并清除超时(如果存在)。

当机器人发送消息时,它不会触发任何消息。当机器人计数时,Number(content) === count因为它已经增加了。


推荐阅读