Home > Back-end >  how can I send a direct message to the user mentioned in a message? Discord JS
how can I send a direct message to the user mentioned in a message? Discord JS

Time:05-31

I'm using the discord.js library and node.js to create a Discord bot. Right now I need to code the bot such that when you send a message ie: "!send @ hello" it would send a DM to the user mentioned in the message, in this case the string: "hello"

Right now I'm trying to do that by doing the following (code is flawed and definitely will not work but I hope you can understand what I am trying to accomplish):

//get the user mentioned in the message
user = message.mentions[0]
//sending the message to said user
user.send("message")

Is there any way to do this?

this is the error it returns when I try the above code:

console.log((message.mentions)[0])

^ TypeError: Cannot read properties of undefined (reading '0')

CodePudding user response:

Message.mentions returns MessageMentions object, which is not an array.

You should be able to get the users by using MessageMentions.users

let user = message.mentions.users.first();

// You need to check whether user exists, because the message could mention noone.
if (user) {
  user.send("message")
}

You wil also probably need to check whether User.dmChannel exists, and if it doesn't, you should create it using User.createDM

CodePudding user response:

Try this:

message.mentions.members.first().send("message");
  • Related