You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Discord.js Slash命令实现提及发送者与接收者及添加用户选择交互的技术求助

Fixing Your /hug Slash Command in Discord.js

Let's get your /hug command working exactly how you want it—here's what you need to adjust:

1. Add a Required User Option (Built into Slash Commands!)

You were right to suspect slash commands have built-in support for selecting targets before running the command. We'll use the addUserOption method on the SlashCommandBuilder to add this functionality. This will force the user to pick a recipient when they trigger /hug, which is exactly what you're looking for.

2. Fetch the Sender and Recipient in the Execute Function

Once the option is set up, you can grab the command sender directly from interaction.user and the selected recipient using interaction.options.getUser(). Using the toString() method on these user objects will automatically format them as valid Discord mentions (so the users get notified when they're hugged!).

Here's the updated code with both changes implemented:

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('hug')
        .setDescription('Hug someone!')
        // Add the mandatory user selection option
        .addUserOption(option =>
            option.setName('target')
                .setDescription('The person you want to hug')
                .setRequired(true)
        ),
    async execute(interaction) {
        // Retrieve the sender and selected target user objects
        const sender = interaction.user;
        const target = interaction.options.getUser('target');

        // Reply with a message that mentions both users
        return interaction.reply(`${sender.toString()} hugs ${target.toString()} 🤗`);
    },
};

Quick Breakdown of Changes:

  • setRequired(true) makes sure the user can't run /hug without picking a target—no empty hugs allowed!
  • toString() converts user objects into Discord's mention format (like <@123456789>) so the tagged users get notifications.
  • This keeps everything strictly within slash commands, no text commands or embeds needed as you requested.

Just replace your existing code with this, redeploy your slash commands to Discord, and you're all set!

内容的提问来源于stack exchange,提问作者CalebOWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 12:42:30