javascriptdiscorddiscord.js

How can I make a bot command to perform an action with another user?


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] });
    }
}

Solution

  • 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] });
        }
    };