I made a command for DM the role.
You can see my code here:
const { Client, Message, MessageEmbed } = require('discord.js');
// const { join } = require('path');
module.exports = {
name: 'dm-role',
/**
* @param {Client} client
* @param {Message} message
* @param {String[]} args
*/
run: async(client, message, args) => {
if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")
if (!args[0]) return message.channel.send("where's the role?")
const role = message.mentions.roles.first()
message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))
if(!role) return message.channel.send("where's the role?")
const reason = args.slice(1).join(" ")
if(!reason) return message.channel.send("the message ?");
try {
await role.send(reason);
return message.channel.send("done");
} catch {
return message.channel.send("failed");
}
}
}
Someone in the role has blocked my bot, so I got an error like this
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Cannot send messages to this user
I just want to know how I can get past the error, and the bot still keeps sending DMs to people who haven't blocked the bot.
You can use the .catch(...) method on the .send(...) function.
Example:
role.send(reason).catch((error) => console.log(error));
Full Example:
run: async(client, message, args) => {
if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")
if (!args[0]) return message.channel.send("where's the role?")
const role = message.mentions.roles.first()
message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))
if (!role) return message.channel.send("where's the role?")
const reason = args.slice(1).join(" ")
if (!reason) return message.channel.send("the message ?");
try {
// Attempt to send the message, if failed log the error and continue
await role.send(reason).catch(error => console.log(error))
return message.channel.send("done");
} catch {
return message.channel.send("failed");
}
}