-1

I want to perform an action using a slash command, for example /hug @dean and then have it mention this user and send a message in an embed that should be random.

What I tried either doesn't get a response or gives me an error for an invalid string format, probably with the user thing.

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName("Hug")
    .setDescription ('Give a friend a hug!'),
    async execute(interaction) {
        const embed = new EmbedBuilder()
            .setTitle("ProtoOwner throws a stick!")
            .setColor(0x0099ff)
            .addFields([
                { name: "[{User} hugs {user}!]", value: reply[randomNum] }
            ]);
        await interaction.reply({ embeds: [embed] });
    }
}

1 Answer 1

2

You are on the right track I believe with using SlashCommandBuilder. The main parts you're missing are telling the command to accept a user as an argument and then retrieving that user from the interaction. You can do this by using .addUserOption() when building the command, and then interaction.options.getUser() inside the execute function to get the user who was mentioned.

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName("hug")
        .setDescription('Give a friend a hug!')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('The user to hug')
                .setRequired(true)), // This makes the option mandatory.

    async execute(interaction) {
        // This gets the user who was mentioned in the 'target' option.
        const target = interaction.options.getUser('target');
        // This gets the user who ran the command.
        const user = interaction.user;

        const embed = new EmbedBuilder()
            .setColor(0x0099ff)
            .setDescription(`${user} gives ${target} a big hug!`);

        await interaction.reply({ embeds: [embed] });
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! This worked perfectly, I got a lot closer using some code I found on reddit but it always referred to the other user as 'null' which I figured meant that it wasn't referencing them properly but this works much better, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.