bots - 计数游戏不和谐js
问题描述
呵呵大家。我创建了自己的机器人,我有很多很棒的东西,比如游戏等。但是,我想做一个计算游戏。我有一个名为“计数”的频道,我想设置我的机器人:
用户 1:456
用户 2:457
机器人:458
我的问题是,当没有其他人在计数时,我怎样才能让机器人计数?但只有一次。(看例子^^)
如果可以的话,你能给我一个示例代码吗?谢谢!!
解决方案
尝试这个:
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
因为它已经增加了。
推荐阅读
- java - 用于 JUnit 测试功能的 CodeLens 不会出现在 VSCode 中
- c# - IO 设备(如 HDD 示例)是否可以在没有 CPU 的情况下工作?
- android - 在 Android 10 上从 contentProvider 加载所有图像
- c - 需要帮助将 char* 扫描到具有结构的函数中
- html - 显示带有选中复选框的选项无法统一工作
- python - Python中基于字符串/整数序列的聚类和距离/相异矩阵
- android - 为什么 DJI Mobile SDK 需要 Android 物理设备,而不能与 Android 虚拟机配合使用?
- haskell - 将 Haskell 函数“分解”为具有各种中间类型的两个函数时如何避免重复?
- xquery - Xquery 无法将 XML HTTP 内容作为 XML 文档访问
- uwp - UWP:退出UWP-App并启动Win IoT core App