Попробуйте это:
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
client.on('message', ({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').keyArray().includes(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) client.clearTimeout(timeout)
// Add a new timeout
timeout = client.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) client.clearTimeout(timeout)
}
}
})
client.login('your token')
Объяснение
Когда пользователь (не бот) отправляет сообщение в канале подсчета, бот проверяет, является ли пользователь считает правильно (if (Number(content) === count + 1
)).
Если они есть, он увеличивает count
, удаляет таймаут, если он существует (if (timeout) client.clearTimeout(timeout)
), и назначает боту подсчитывать через 30 секунд (client.setTimeout(() => channel.send(++count), 30000)
).
Если это не так, бот отправляет сообщение, сбрасывает count
и сбрасывает время ожидания (если оно существует).
Когда бот отправляет сообщение, он не вызывает который. Когда бот подсчитывает, Number(content) === count
, потому что он уже увеличен.
Я использовал client.setTimeout
вместо просто setTimeout
, потому что client.setTimeout
автоматически удалит тайм-аут, если клиент уничтожены.