Marcus
Marcus

Reputation: 11

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

I'm trying to dm all users in my private server with all my friends however some of them don't want to be dmed so they turn off their dms. Because of this, I get an error which stops the bot from continuing on to the other users. How can I skip over that user when the error is found and tell my bot to continue to dm the next user after.

heres my code

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;

I understand I am not handling any errors but I am not sure how to go about this and could really use some help

Also here is my bot.js code

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

Upvotes: 0

Views: 7058

Answers (3)

American Pie
American Pie

Reputation: 41

Anywhere in your code use an error event listener

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

Upvotes: 1

Cipher
Cipher

Reputation: 2722

You can use .catch() block, member.send('Message') return a promise with succes sended message or error. So you can use

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

Upvotes: 0

Nothing
Nothing

Reputation: 1

You'll want to catch the error, basically, if that error happens, you want it to just pass by and ignore the error. In Javascript this is known as try and catch. Read about it below then apply it to wherever the error is being identified.

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

Upvotes: 0

Related Questions