Отключение времени ожидания в некоторых частях: setTimeout - PullRequest
0 голосов
/ 27 мая 2020

Я установил время ожидания для команды! Corona, она работает нормально, но я хочу убрать время ожидания, когда пользователь неправильно вводит аббревиатуру страны. Все мои коды указаны ниже.

Короче говоря, когда введена неправильная команда страны, например "! Corona US" должна запрашивать новую без ожидания времени.

const Discord = require("discord.js");
const fetch = require("node-fetch");
const hereTimeOut = new Set();

exports.run = async (bot, message, args) => {
    if (waitsetTimeOut.has(message.author.id)) {

        const waitsetTimeOut = new Discord.RichEmbed()
        waitsetTimeOut.setColor(0x00AE86)
        waitsetTimeOut.setTimestamp()
        waitsetTimeOut.setAuthor(message.author.username, message.author.avatarURL)
        waitsetTimeOut.setTitle("[wait a while]")
        waitsetTimeOut.setDescription('please wait 1 minute')
        return message.channel.sendEmbed(waitsetTimeOut);
    }else {


    let country = args.slice(0).join(' ');

    if(!country){

        fetch("https://covid19.mathdro.id/api/").then(res => res.json()).then(json => {

            const embed = new Discord.RichEmbed();
                embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                embed.setColor(15962634)
                embed.setTitle('Worldwide COVID-19 Statistics')
            message.channel.send({embed: embed});

        });

    }else{

        fetch(`https://covid19.mathdro.id/api/countries/${country}`).then(res => res.json()).then(json => {

                const embed = new Discord.RichEmbed();
                    embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                    embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                    embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                    embed.setColor(15962634)
                    embed.setTitle(`COVID-19 Statistics (${country})`)
                message.channel.send({embed: embed});

        }).catch(() => {

            message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");

        });

    }

    hereTimeOut.add(message.author.id);
        setTimeout(() => {
          // Removes the user from the set after a minute
          hereTimeOut.delete(message.author.id);
        }, 60000);
    }

};

exports.conf = {
  enabled: true,
  guildOnly: true,
  aliases: ['corona'],
  permLevel: 0
};

exports.help = {
  name: "corona",
  description: "covid19",
  usage: "coronavirus"
};

часть ошибки, полученной при использовании неправильной команды страны;

.catch(() => {
    message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");
});

1 Ответ

1 голос
/ 27 мая 2020

Вы можете превратить свой код тайм-аута в функцию многократного использования:

function startTimeout(authorId) {
    hereTimeOut.add(authorId);
    setTimeout(() => {
        hereTimeOut.delete(authorId);
    }, 60000);
}

, а затем вызывать его всякий раз, когда вы хотите, чтобы пользователь ждал, прежде чем использовать команду:

fetch("https://covid19.mathdro.id/api/").then(res => res.json()).then(json => {
            const embed = new Discord.RichEmbed();
                embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                embed.setColor(15962634)
                embed.setTitle('Worldwide COVID-19 Statistics')
            message.channel.send({embed: embed});
            startTimeout(message.author.id) // Add this after every successfull run
        });
...