Home > OS >  Discord bot failing to call username of person who calls it
Discord bot failing to call username of person who calls it

Time:03-06

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').

CodePudding user response:

If You want to mention a user you can do ${message.author}. But if you want to say for 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 might 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.

  • Related