How to make a discord js bot send direct/private message not to author?

ricola picture ricola · Aug 5, 2017 · Viewed 7k times · Source

I am using node.js for discord.

After I make a command, I want my bot to send a direct/private message to a specific person, not the author who makes the command (me).

Right now I have the person's <@000000000000000000> (I think this is called an ID), which is in String format.

For instance, this code client.sendMessage(message.author, "Hello!"); sends the author the message Hello. But I want one like client.sendMessage(message.user("<@000000000000000000>"), "Hello!");

Does a function like that exist?

For background information, I'm making a werewolf game bot where players are randomly assigned a role, and after I command w!play I want the players to receive their roles in the DM.

Answer

Wright picture Wright · Aug 6, 2017

Yes just get the user object and send to that. You will need their id, so parse out the id part of the string "<@0000>". Also, sendMessage is deprecated. Use channel.send(). In the case of a user:

let str = "<@123456789>"; //Just assuming some random tag.

//removing any sign of < @ ! >... 
//the exclamation symbol comes if the user has a nickname on the server.
let id = str.replace(/[<@!>]/g, '');

client.fetchUser(id)
    .then(user => {user.send("Hello I dmed you!")})