簡體   English   中英

我該如何處理錯誤、忽略它並繼續使用該函數? 不和諧.js

[英]How can I go about handling an error, ignoring it and continuing with the function? discord.js

我正在嘗試與我所有的朋友一起向我的私人服務器中的所有用戶發送消息,但是他們中的一些人不想被發送消息,因此他們關閉了他們的 dms。 因此,我收到一個錯誤,該錯誤阻止機器人繼續向其他用戶發送。 發現錯誤時如何跳過該用戶並告訴我的機器人在之后繼續 dm 下一個用戶。

繼承人我的代碼

const commando = require('discord.js-commando');
const app = require('../../app.js');
const config = require('../../config.json');
const Discord = require('discord.js');

class DMallCommand extends commando.Command {
    constructor(client){
        super(client, {
            name: `dmall`,
            group: 'dms',
            memberName: 'dmall',
            description: 'Sends message provided to all members of the guild.',
            examples: [ `${config.prefix}dmall Hey everyone! This might reach more people than a mass ping...` ]
        });
    }

    async run(message, args){
        let dmGuild = message.guild;
        let role = message.mentions.roles.first();
        var msg = message.content;


        try {
            msg = msg.substring(msg.indexOf("dmall") + 5);
        } catch(error) {
            console.log(error);
            return;
        }

        if(!msg || msg.length <= 1) {
            const embed = new Discord.RichEmbed()
                .addField(":x: Failed to send", "Message not specified")
                .addField(":eyes: Listen up!", "Every character past the command will be sent,\nand apparently there was nothing to send.");
            message.channel.send({ embed: embed });
            return;
        }

        let memberarray = dmGuild.members.array();
        let membercount = memberarray.length;
        let botcount = 0;
        let successcount = 0;
        console.log(`Responding to ${message.author.username} :  Sending message to all ${membercount} members of ${dmGuild.name}.`)
        for (var i = 0; i < membercount; i++) {
            let member = memberarray[i];
            if (member.user.bot) {
                console.log(`Skipping bot with name ${member.user.username}`)
                botcount++;
                continue
            }
            let timeout = Math.floor((Math.random() * (config.wait - 0.01)) * 1000) + 10;
            await sleep(timeout);
            if(i == (membercount-1)) {
                console.log(`Waited ${timeout}ms.\t\\/\tDMing ${member.user.username}`);
            } else {
                console.log(`Waited ${timeout}ms.\t|${i + 1}|\tDMing ${member.user.username}`);
            }
            try {
                member.send(`${msg} \n #${timeout}`);
                successcount++;
            } catch (error) {
                console.log(`Failed to send DM! ` + error)

            }
        }
        console.log(`Sent ${successcount} ${(successcount != 1 ? `messages` : `message`)} successfully, ` +
            `${botcount} ${(botcount != 1 ? `bots were` : `bot was`)} skipped.`);
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

module.exports = DMallCommand;

我知道我沒有處理任何錯誤,但我不確定如何解決這個問題,並且真的可以使用一些幫助

另外這里是我的 bot.js 代碼

  const Discord = require('discord.js');
const figlet = require('figlet');
const colors = require('colors');
const readline = require('readline');
const commando = require(`discord.js-commando`);

const config = require('./config.json');
const bot = new commando.Client({
    commandPrefix:'£',
    owner: config.id
});

const cmdsArray = [
    "dmall <message>",
    "dmrole <role> <message>"
];

bot.on("ready", () => {
    clear();
    console.log('______')
    bot.user.setActivity('PRDX');
});


bot.on("error", (error) => {
    bot.login(config.token);
});

bot.registry.registerGroup('dms', 'help');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands");

if (process.env.BOT_TOKEN) bot.login(process.env.BOT_TOKEN);
else bot.login(config.token);
}

代碼中的任何地方都使用錯誤事件偵聽器

client.on("error", () => { client.login(token) });

您會想要捕獲錯誤,基本上,如果發生該錯誤,您希望它只是通過並忽略該錯誤。 在 Javascript 中,這稱為嘗試和捕獲。 閱讀下面的內容,然后將其應用於發現錯誤的任何地方。

https://www.w3schools.com/js/js_errors.asp

您可以使用.catch()塊, member.send('Message')返回一個成功發送消息或錯誤的承諾。 所以你可以使用

member.send('message').catch(console.error)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM