有没有一种方法可以将选项存储在变量中?

3

我目前对Discord.JS还很陌生,不知道如何使得这个"echo"命令通过机器人进行回复。

我的现有代码:

package.json

{
  "name": "bot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

index.js

const fs = require('node:fs');
const path = require('node:path');
const {Client,GatewayIntentBits, Collection} = require('discord.js');
const {token} = require('./config.json');
const { execute } = require('./commands/ping');
const ping = require('./commands/ping');

const client = new Client({intents: [GatewayIntentBits.Guilds]});

client.commands = new Collection();
const commandPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandPath, file);
    const command = require(filePath);

    client.commands.set(command.data.name, command);
}

client.once('ready',()=> {
    console.log("ready");
});

client.on('interactionCreate', async interaction => {
    if(!interaction.isChatInputCommand()) return;
    
    const command = client.commands.get(interaction.commandName)

    if(!command) return;
    try {
        await command.execute(interaction);
    } catch(error) {
        console.error(error);
        await interaction.reply({content: "there was an error while executing this command", ephemeral: true});
    }
});

client.login(token);

echo.js

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

module.exports = {
    data: new SlashCommandBuilder()
        .setName('echo')
        .setDescription('returns input')
        .addStringOption(option =>
            option.setName('input')
                .setDescription("the option to echo back")
                .setRequired(true)),
            
    async execute(interaction) {
        await interaction.reply();
    }
}

ping.js

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

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('replies with pong'),
    async execute(interaction) {
        await interaction.reply("pong!")
    }
}

deploy-commands.js

const {REST} = require("@discordjs/rest");
const {Routes} = require("discord.js");
const {clientId, guildId, token} = require("./config.json");
const path = require("node:path");
const fs = require("node:fs");

const commands = [];
const commandPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandPath, file);
    const command = require(filePath);
    commands.push(command.data.toJSON());
}

const rest = new REST({version: 10}).setToken(token);

rest.put(Routes.applicationGuildCommands(clientId, guildId), {body:commands})
    .then(() => console.log("registered commands"))
    .catch(console.error);

config.json

{
    "token": "hidden",
    "clientId": "1009394510117212162",
    "guildId": "1009401102929768479"
}

错误日志

C:\Users\perry\Desktop\bot>node . ready TypeError: Cannot read properties of undefined (reading 'ephemeral') at ChatInputCommandInteraction.reply (C:\Users\perry\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:102:30) at Object.execute (C:\Users\perry\Desktop\bot\commands\echo.js:14:27) at Client. (C:\Users\perry\Desktop\bot\index.js:32:23) at Client.emit (node:events:527:28) at InteractionCreateAction.handle (C:\Users\perry\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12) at Object.module.exports [as INTERACTION_CREATE] (C:\Users\perry\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36) at WebSocketManager.handlePacket (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31) at WebSocketShard.onPacket (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketShard.js:481:22) at WebSocketShard.onMessage (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketShard.js:321:10) at WebSocket.onMessage (C:\Users\perry\node_modules\ws\lib\event-target.js:199:18)


这个回答解决了你的问题吗?https://stackoverflow.com/questions/73351536/how-do-i-get-the-question-someone-says-in-a-string-option/73352652#73352652 - Zsolt Meszaros
2个回答

2

您可以使用从用户获得的<CommandInteraction>#option,使用getString()方法并像下面这样发送:

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

module.exports = {
    data: new SlashCommandBuilder()
        .setName('echo')
        .setDescription('returns input')
        .addStringOption(option =>
            option.setName('input')
            .setDescription("the option to echo back")
            .setRequired(true)),


    async execute(interaction) {
        let input = interaction.options.getString("input")
        await interaction.reply({
            content: input
        });
    }
}

2
为了获取由.addStringOption(option => option.setName('input'))设置的命令选项的用户输入,您可以使用interaction.options.getString('input')
module.exports = {
  data: new SlashCommandBuilder()
    .setName('echo')
    .setDescription('returns input')
    .addStringOption((option) =>
      option
        .setName('input')
        .setDescription('the option to echo back')
        .setRequired(true),
    ),

  async execute(interaction) {
    const userInput = interaction.options.getString('input');
    await interaction.reply({ content: userInput });
  },
};

您可以查看有关CommandInteractionOptionResolver的文档,其中包含您可能需要的所有方法:
// .addStringOption((option) =>
//   option.setName('string').setDescription('Enter a string'),
// )
const string = interaction.options.getString('string');

// .addIntegerOption((option) =>
//   option.setName('integer').setDescription('Enter an integer'),
// )
const integer = interaction.options.getInteger('integer');

// .addNumberOption((option) =>
//   option.setName('number').setDescription('Enter a number'),
// )
const number = interaction.options.getNumber('number');

// .addBooleanOption((option) =>
//   option.setName('boolean').setDescription('Select a boolean'),
// )
const boolean = interaction.options.getBoolean('boolean');

// .addUserOption((option) =>
//   option.setName('target').setDescription('Select a user'),
// )
const user = interaction.options.getUser('target');
const member = interaction.options.getMember('target');

// .addChannelOption((option) =>
//   option.setName('channel').setDescription('Select a channel'),
// )
const channel = interaction.options.getChannel('channel');

// .addRoleOption((option) =>
//   option.setName('role').setDescription('Select a role'),
// )
const role = interaction.options.getRole('role');

// .addAttachmentOption((option) =>
//   option.setName('attachment').setDescription('Attach something'),
// );
const attachment = interaction.options.getAttachment('attachment');

// .addMentionableOption((option) =>
//   option.setName('mentionable').setDescription('Mention something'),
// )
const mentionable = interaction.options.getMentionable('mentionable');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接