简体   繁体   中英

How do I make a discord js bot that DM's a mentioned user?

I'm making a discord bot that lets you use a ".dm" command, I'm trying to make it so whenever someone uses the ",dm" command, puts a user ID/mention of a user. and puts a message: it DMs the user/user ID mentioned. This is my code:

const { Client } = require('discord.js');
const bot = new Client();

const TOKEN = process.env.TOKEN;

const PREFIX = '!';

bot.on('ready', () => {
 console.log('This bot is active!');
});

bot.on('message', (message) => {
 if (message.content === '!dm') {
  const taggedUser = message.mentions.users.first();
  const user = client.users.cache.get(taggedUser.username);
  user.send('test');
 }
});

bot.login(TOKEN);

The collection client.users.cache.get() is mapped by id, so it should be client.users.cache.get(taggedUser.id); . However, a much bigger issue, you called your client bot not client , so that's why client.users.cache.get() isn't working. The full code should look like:

bot.on('message', (message) => {
 if (message.content === '!dm') {
  const taggedUser = message.mentions.users.first();
  const user = bot.users.cache.get(taggedUser.id);
  user.send('test');
 }
});

Make sure you remember what you called your variables!

const target = message.mentions.users.first()
if(!target) return message.reply('You Didnt State the User you want to send the dm to')

const msgs = args[1]
if(!msgs) return message.reply('You Didnt State the Message you want to send the user')

if(message.attachments.size > 0){
    var Attachment = message.attachments.array();
    var OurAttachment = Attachment[0];
    const attachment = new MessageAttachment(OurAttachment.url);

    target.send(msgs);
    target.send(attachment);
    message.channel.send('Sent a Dm to ' + target.username)

  } else {
     target.send(msgs);
     message.reply('Sent a Dm to ' + target.username)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM