Search code examples
javascriptdiscorddiscord.js

Type Error: Cannot read properties of undefined send


So this code I'm using isn't really working and I would really appreciate it if someone helped me the details are under the code.

  name: "randompassword",
  aliases: ["randompass", "password", "pass"],
  description: "Sends a random password",
  async execute(client, message) {
    let password = [];
let possible ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+'
let passString
let passWordLength = 20;
for (let i = 0; i < passWordLength; i++) {
    password.push(possible.charAt(Math.floor(Math.random() * possible.length)));
}
passString = password.join('') 
    return message.author
        .send(passString)

        .then(() => {
          if (message.channel.type === 'dm') return
          message.reply({
            content: "I've sent you a DM with the randomized password!",
          })
  })
 }
}```

It's not really working and its saying `Type Error: Cannot read properties of undefined (reading 'send') I would appreciate it if you guys can help :)) (I'm new to coding pls go easy on me xD). I'm a new discord.js developer soooooo yeah. Thanks in Advanced! Have a great day uwuw. Anyways do you guys like nuggets?

Solution

  • You trying to send data directly to the author property without any checks. First of all, author property is nullable inside Message. You should check, if author is exist at all on this object and then try to send the message. Secondly, I have suspicion, that you'll be unable to send anything if user do not accept DMs from anyone. I suggest you to look at User#createDM method, which will return a DMChannel for you to deal with.

    {
      async execute(client, message) {
        const author = message.author;
        
        if (!author) {
          // Maybe tell user that something went wrong 
          // and you can't get the author
    
          return;
        }
        
        // Trying to send the message to the user with the password.
        try {
          const dmChannel = await author.createDM();
    
          await dmChannel.send({content: "Your password here!"});
        } catch (error) {
          // Probably should tell that you can't send the DM
          // message. User should check if he opened his DM for
          // anyone.
        }
        
      }
    }
    

    Also, as an additional note: if you using latest versions of discord.js, you should probably start using new format for send methods as described in the guide here.