命令超时|Discord.js
目前我有以下内容:
const Discord = require("discord.js");
const PREFIX = ",";
const token = "my token";
var bot = new Discord.Client();
bot.on('ready', () => {
bot.on('message', message => {
if (!message.content.startsWith(PREFIX)) return; //if not command ignore message
var args = message.content.substring(PREFIX.length).split(" "); //splits commands so each word = pos in array
switch (args[0].toLowerCase()) { //not case-sensitive anymore
case "hello":
message.channel.send("hello");
break;
//rest of the commands
我想限制命令",hello"的使用。我希望用户每次输入"你好"时都有10秒的超时。如果用户在此冷却之前输入命令,它将发送一条消息,说明谁上次使用了该命令,以及冷却时间保持了多长时间。
我希望结果是这样的:
User1: ,hello
Bot: hello
(After 1 second)
User2: ,hello
Bot: User1 has already used this command, please wait another 9 seconds to use it again
(After 9 seconds)
User 2: ,hello
Bot: hello
感谢所有的帮助。 谢谢,
解决方案
您需要存储上次使用该命令的日期,然后相应地分叉该流。若要同时显示上次使用该命令的用户,您需要将该信息与时间戳一起存储。
这里有一个基于您的示例:
const Discord = require("discord.js");
const PREFIX = ",";
const token = "my token";
const bot = new Discord.Client();
let lastHelloCommandDate, lastHelloCommandUser;
bot.on('ready', () => {
bot.on('message', message => {
if (!message.content.startsWith(PREFIX)) return; //if not command ignore message
var args = message.content.substring(PREFIX.length).split(" "); //splits commands so each word = pos in array
switch (args[0].toLowerCase()) { //not case-sensitive anymore
case "hello":
hello(message);
break;
//rest of the commands
}}})
})
function hello(message) {
const now = new Date();
if (now - lastHelloCommandDate > 10 * 60 * 1000) {
// It's been more than 10 mins
message.channel.send("hello");
lastHelloCommandDate = now;
lastHelloCommandUser = message.sender;
} else {
// It's been less than 10 mins
// send a direct message to the user
// i don't know if message.sender exists, check the api
message.sender.send(`Command last used by ${lastHelloCommandUser}`);
}
}
对此示例进行了修改,以便将命令存储在单个对象中并对其进行动态检查。这样就不需要SWITCH语句。
const Discord = require("discord.js");
const PREFIX = ",";
const token = "my token";
const bot = new Discord.Client();
let lastHelloCommandDate, lastHelloCommandUser;
bot.on('ready', () => {
bot.on('message', message => {
if (!message.content.startsWith(PREFIX)) return; //if not command ignore message
var args = message.content.substring(PREFIX.length).split(" "); //splits commands so each word = pos in array
const command = args[0].toLowerCase();
if (!commands[command]) {
throw new Error(`Unknown command supplied: ${command}`);
}
commands[command](message);
}}})
})
const commands = {
hello: message => {
const now = new Date();
if (now - lastHelloCommandDate > 10 * 60 * 1000) {
// It's been more than 10 mins
message.channel.send("hello");
lastHelloCommandDate = now;
lastHelloCommandUser = message.sender;
} else {
// It's been less than 10 mins
// send a direct message to the user
// i don't know if message.sender exists, check the api
message.sender.send(`Command last used by ${lastHelloCommandUser}`);
}
}
};
相关文章