Search code examples
javascriptnode.jsdiscord.jsargs

"Cannot read property 'send' of undefined" while trying to send a direct message by ID from arg


I'm trying to make a command which allows you to send a DM by ID but when I'm trying to use it, it gives me this error:

(node:3148) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
    at Client.<anonymous> (d:\Images\Discord\Bots\tired-bot\index.js:333:50)
    at Client.emit (events.js:376:20)
    at MessageCreateAction.handle (d:\Images\Discord\Bots\tired-bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (d:\Images\Discord\Bots\tired-bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (d:\Images\Discord\Bots\tired-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (d:\Images\Discord\Bots\tired-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (d:\Images\Discord\Bots\tired-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (d:\Images\Discord\Bots\tired-bot\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:376:20)
    at Receiver.receiverOnMessage (d:\Images\Discord\Bots\tired-bot\node_modules\ws\lib\websocket.js:797:20)

My code:

if(command === "replydm"){
    let idArg = args[0];
    let messageArgs = args.slice(1).join(" ");

    if(args[0]){
        if(!messageArgs){
            return message.reply("please specifiy a message to reply.");
        }

            return bot.users.cache.get(idArg).send(`**Message from developer ${message.author.tag}**\n${messageArgs}`)
                       .then(message.reply("message sent to the user."));  
    } else {
        message.reply("please specifiy an ID to respond to.");
    }
}

Solution

  • Assuming idArg is a valid User Snowflake, the user is not cached, it's best to fetch than to rely on the cache

    if(command === "replydm"){
        let idArg = args[0];
        let messageArgs = args.slice(1).join(" ");
    
        if(args[0]){
            if(!messageArgs){
                return message.reply("please specifiy a message to reply.");
            }
    
            // Fetch the user, will always check the cache first
            return bot.users.fetch(idArg)
               .then(user => {
                  user.send(`**Message from developer ${message.author.tag}**\n${messageArgs}`);
                  message.reply('message sent to the user');
               })
               .catch(console.error);
        } else {
            message.reply("please specifiy an ID to respond to.");
        }
    }