Discord.js Slash命令生成密钥时result显示undefined求助
问题分析与修复
你的key命令输出undefined,核心是两个代码错误导致:
1. 错误的参数与未定义的变量
Discord.js的Slash命令execute方法默认仅接收interaction参数,你额外添加的length没有被传入,值为undefined。循环条件i < length等同于i < undefined,循环完全不会执行,同时后续修改result的逻辑也会因为报错中断。
2. 常量无法被修改
用const result = ""声明的常量不能通过result += ...修改,这会直接抛出运行时错误,导致代码终止,最终回复内容异常显示undefined。
修复后的完整代码
const { SlashCommandBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("key") .setDescription("Gives a key"), async execute(interaction) { // 将const改为let,允许修改result的值 let result = ""; const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charactersLength = characters.length; // 自定义密钥长度,可根据需求调整 const length = 16; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } console.log("Command starting - key"); await interaction.deferReply({ fetchReply: true }); const newMessage = `**Here is your key:** ${result}`; await interaction.editReply({ content: newMessage }); }, };
可选优化:让用户自定义密钥长度
如果需要让用户指定密钥长度,可以给命令添加整数选项:
data: new SlashCommandBuilder() .setName("key") .setDescription("Gives a key") .addIntegerOption(option => option.setName("length") .setDescription("Set the length of your key") .setMinValue(8) .setMaxValue(32) .setRequired(true) ),
然后在execute方法中获取用户输入的长度:
const length = interaction.options.getInteger("length");
内容的提问来源于stack exchange,提问作者ace
相关产品推荐
相关产品推荐

