Private messaging a user

风格不统一 提交于 2019-12-11 18:01:44

问题


I am currently using the discord.js library and node.js to make a discord bot with one function - private messaging people.

I would like it so that when a user says something like "/talkto @bob#2301" in a channel, the bot PMs @bob#2301 with a message.

So what I would like to know is... how do I make the bot message a specific user (all I know currently is how to message the author of '/talkto'), and how do I make it so that the bot can find the user it needs to message within the command. (So that /talkto @ryan messages ryan, and /talkto @daniel messages daniel, etc.)

My current (incorrect code) is this:

client.on('message', (message) => {
    if(message.content == '/talkto') {
        if(messagementions.users) { //It needs to find a user mention in the message
            message.author.send('Hello!'); //It needs to send this message to the mentioned user
    }
}

I've read the documentation but I find it hard to understand, I would appreciate any help!


回答1:


The send method can be found in a User object.. hence why you can use message.author.send... message.author refers to the user object of the person sending the message. All you need to do is instead, send to the specified user. Also, using if(message.content == "/talkto") means that its only going to run IF the whole message is /talkto. Meaning, you can't have /talkto @me. Use message.content.startsWith().

client.on('message', (message) => {
    if(message.content.startsWith("/talkto")) {
        let messageToSend = message.content.split(" ").slice(2).join(" ");
        let userToSend = message.mentions.users.first();

        //sending the message
        userToSend.send(messagToSend);
    }
}

Example use:

/talkto @wright Hello there this is a dm!



来源:https://stackoverflow.com/questions/45724141/private-messaging-a-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!