I need help making a discord bot direct message someone on typing a command

David J picture David J · Nov 15, 2017 · Viewed 10.7k times · Source

I am currently trying to create a discord bot and am stumped on a command i am trying to make it do. The command is supposed to be a secret DM message sent by the bot. I was wondering if there was anyway to do this? the command is supposed to look like this:

/dm @PLAYER#000 [message_goes_here]

Pleas help!!

Answer

LW001 picture LW001 · Nov 16, 2017

Let's do this step by step:

If the @Player#0000 is a mention, you can get Player#0000's User Object using msg.mentions[0]. Now on to sending that User a message:

Firstly you'll need to separate the message from the command: Using msg.toString() you'll be able to grab the message with the mention being turned into <@ID>, which will also account for spaces in usernames. Now split the message using msg.toString().split(' '), shift() it twice, join(' ') it and you'll have the message.

Using User.send() you will be able to message that user.

Here's how the final result will look:

bot.on('message', message => {
    if (message.content.startsWith('/dm ') && message.mentions.users.size) {
        var v=message.toString().split(' ').shift().shift().join(' ') // Takes the DM content from the message
        var member=message.mentions.users[0] // The mentioned user
        member.send(v) // send that user a DM
    }
})

Note that this example doesn't really cover errors (in case the message doesn't send, etc.)