Discord.js – Message all members of a guild – code snippet

Discord.js – Message all members of a guild – code snippet

Sometimes it might be necessary to message all users in a guild, but instead of messaging one after the other; why not include a function to message all “at once”? In order to not be rate-limited, I have included a timeout/delay after each message, and as always replace LOG_CHANNEL_ID with your channels ID, if applicable.

    async execute(message, args) {
        const dato = new Date();
        dato.setHours(dato.getHours() + 2);
        const logchannel = 'LOG_CHANNEL_ID';
        if (!message.member.hasPermission(`ADMINISTRATOR`)) {
            message.channel.send(`You don't have permission to use this command!`);
            message.client.channels.cache.get(logchannel).send(`${message.author} tried using DMALL! ` + dato.toLocaleTimeString() + dato.toLocaleDateString());
        } else {
            const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
            const sendMessage = args.join(" ");
            await delay(1000);
            let interval = 500; // how much time should the delay between two iterations be (in milliseconds)?
            let promise = Promise.resolve();
            message.guild.members.cache.forEach(function (user) {
                promise = promise.then(function () {
                    if (user.id != message.client.user.id) {
                        return new Promise(function (resolve) {
                            setTimeout(resolve, interval);
            message.client.channels.cache.get(logchannel).send(`${message.author} sent a DM to all members of: **${message.guild.name}**!` + dato.toLocaleTimeString() + dato.toLocaleDateString());

Since I’m using Discord.js v12, there are some differences from v11. The main difference is you have to include .cache where before you didn’t.
This code sends a message to all users in the current guild. The message sent is everything after: PREFIXdmall (prefix is defined in index.js), but will not send a message to itself, and the code also checks for ADMINISTRATOR privileges (others are interchangeable, see Discord.js Documentation. I suggest using either ADMINISTRATOR or MANAGE_GUILD!

Comments and suggestions are, as always, most appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *