Discord bot failing to call username of person who calls it

Advertisements

I’m trying to make my bot say a simple message whenever someone tells it ‘hello’. Currently, the code of the command itself looks like this:

const { SlashCommandBuilder } = require('@discordjs/builders');
const greeter = "default";
const greetOptions = [
    `Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
    data: new SlashCommandBuilder()
        .setName('hello')
        .setDescription('say hi to Hal!'),
    execute(message, args) {
        let greeter = message.user.username;
        msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
    },
};

The code I am using to manage when commands are typed looks as follows:

let prefix = "hal, ";
client.on('messageCreate', message => {
    if (!message.content.startsWith(prefix)) return;

    const args = message.content.slice(prefix.length);
    const command = args.toLowerCase();
    console.log(`${message.author.tag} called ${command}`);

    if (!client.commands.has(command)) return;

    try {
        client.commands.get(command).execute(message, args);
    } catch (error) {
        console.error(error);
        message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

When I run it, it throws the error, "Cannot read properties of undefined (reading ‘username’).

>Solution :

If You Want To Mention A User You Can Do ${message.author} But If You Want To Say Ex. Hello, Brandon Then You Need To Do ${message.author.username} The Message ${message.author.tag} Does Not Always Function And Also I Recommend You const user = message.mentions.users.first() || message.author Or Just const user = message.author For Short So Then You Can Do ${user.username} Maybe This May Fix The Bot Failing To Respond Otherwise If It Doesn’t Tell me.
Fix the first code and change msg.channel.send to message.channel.send bruh.

Leave a ReplyCancel reply