Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

90
Views
Discord js bot: Cannot send DM to users with specific role

I seem to be having serious trouble sending DM's to all users with a specific role.

Here is my bot code:

bot.on('message', async message => {
    members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
    
    members.forEach(member_id => {
        
        sleep(5000).then(() => {
            message.users.fetch(member_id, false).then((user) => {
                user.send("some message");
             });
        });
       
    });
});

This code gives me the error:

Cannot read properties of null (reading 'roles')

on this line:

members = message.guild.roles.cache.find(role => role.id === ....

However that is not the issue. When I comment out the sleep command to send the message and output the member roles using:

members.forEach(member_id => {

        console.log(member_id)

        //sleep(5000).then(() => {
        //    bot.users.fetch(member_id, false).then((user) => {
        //        user.send("some message");
        //     });
        //});
       
    });

I get a list returned in the console of all the user ID's.. So it must be returning the roles.

How do I send a message to all users with a specific role ID ?? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

To fix your first issue, message.guild will be null in DM. Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id").

bot.on("message", async message => {
    let { guild } = message
    if (!guild) guild = bot.guilds.cache.get("id")
    //...
})

To fix your other issue, you can run GuildMember#send() rather than getting the IDs and fetching the users

bot.on("message", async message => {
    let { guild } = message
    if (!guild) guild = bot.guilds.cache.get("id")
    let members = guild.roles.cache.get("12345678998765").members 
    // I used .get here because it's getting by ID
    
    members.forEach(member => {
        sleep(5000).then(() => member.send("some message"));
    });
})

The above code will get all the GuildMembers and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs