Home > Software design >  I can't send a private message to a user in discord with node.js
I can't send a private message to a user in discord with node.js

Time:08-03

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);

    client.users.fetch('266862837308063745').then((user) => {
        user.send('hello world');
    });

});


client.login('token');

Hello, I am trying to send a private message to a user as above but I get the following error. I am using node.js discord.js v10. I need to code a bot that sends bulk private messages. I can get the id value of the user, but I can't send a private message to that user in any way. I tested it on users I am on the same server, but I get the following error. Do you have any idea how to fix my code? Thank you.

C:\Users\mderv\Desktop\discord-test\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:287
        throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[50007]: Cannot send messages to this user
    at SequentialHandler.runRequest (C:\Users\mderv\Desktop\discord-test\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:287:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SequentialHandler.queueRequest (C:\Users\mderv\Desktop\discord-test\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
    at async REST.request (C:\Users\mderv\Desktop\discord-test\node_modules\@discordjs\rest\dist\lib\REST.cjs:52:22)
    at async DMChannel.send (C:\Users\mderv\Desktop\discord-test\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15) {
  rawError: { message: 'Cannot send messages to this user', code: 50007 },
  code: 50007,
  status: 403,
  method: 'POST',
  url: 'https://discord.com/api/v10/channels/1004006390626516992/messages',
  requestBody: {
    files: [],
    json: {
      content: 'hello world',
      tts: false,
      nonce: undefined,
      embeds: undefined,
      components: undefined,
      username: undefined,
      avatar_url: undefined,
      allowed_mentions: undefined,
      flags: undefined,
      message_reference: undefined,
      attachments: undefined,
      sticker_ids: undefined
    }
  }
}

New Code

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

var lists = [
    "790187748891033600",
    "1003969194301337640",
    "447799169629945868",
    "749349915087470683",
    "702149244370419712",
    "615717190574014489",
    "497489241597542400",
    "702149244370419712",
    "844163655578157067",
    "959938516966584440",
    "836861060262264862",
    "771763703145562202",
    "891470731752390657",
    "844848027453095937",
    "975804040665522176",
    "980404278961270824",
    "349084844128600064",
    "860491154079612958",
    "914841215344717854",
    "863728231031111700",
    "949841043338190878",
    "928289387475771433",
    "759069671873577001",
    "558293214768136217",
    "915012095806939147"
]
const sleep = (ms)=>{
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
            resolve()
        }, ms);
    })
}
client.on('ready', async () => {
    console.log(`Logged in as ${client.user.tag}!`);

    for (var el of lists) {
        try{
            client.users.fetch(el).then((user) => {
                // console.log(user)
                user.send('hello world').then(reso=>{
                    console.log('başarılı!')

                }).catch(err => {console.log("başarısız!")});
        
            }).catch(err=>{
                console.log('başarısız!')
            })
        }catch(err){
            console.log('başarısız!')

        }
        await sleep(2000)
    }

     
       

     
  
   

});

client.login('token');

CodePudding user response:

EDIT:

It appears that the Bot and the users were not sharing a server, thus this error was thrown.

BEFORE EDIT:

That happens because the user either has its DMs closed or the user blocked your bot.

You can't do anything to bypass this and still send the message. If you plan on sending DMs to multiple members, and want to avoid the error you can add a .catch() to handle it.

user.send('hello world').catch(err => {console.log(err)});
// leave empty if you dont want to do anything
  • Related