2
关注
1349
浏览

命令超时| Discord.js

为什么被折叠? 0 个回复被折叠
hotlu 未验证用户 用户来自于: 广东省
2020-09-16 14:06

您需要存储该命令的最后日期,然后相应地分流。为了显示最后一次使用该命令的人员,您需要将该信息与时间戳一起存储。

下面是一个例子基于你:

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}`); 
    } 
    } 
}; 

关于作者

y 未验证用户

这家伙很懒,还没有设置简介

问题动态

发布时间
2020-09-15 15:51
更新时间
2022-09-15 15:52
关注人数
2 人关注

相关问题

个人工作笔记 Powered BY WeCenter V4.1.0 © 2024 粤ICP备2020123311号