[英]Javascript: (Discord.js) - TypeError: SlashCommandBuilder is not a constructor
[英]Discord.js SlashCommandBuilder() : get option choices from a list in an async function
我正在嘗試創建一個帶有選項input
的斜杠命令/test3
。 但是,我想從異步 function 中獲得這些選擇,但我嘗試這樣做的方式不起作用。
這是在tools.js
中生成我的參數列表的簡化版本的代碼
module.exports = {
getArgumentList: () => getArgumentList()
}
async function getArgumentList(){
return [
{name: '1', value:'One'},
{name: '2', value:'Two'},
{name: '3', value:'Three'},
{name: '4', value:'Four'},
{name: '5', value:'Five'}
]
}
以及命令的代碼,在test3.js
中
const { SlashCommandBuilder } = require("discord.js");
const { getArgumentList } = require("../tools.js")
module.exports = {
data: new SlashCommandBuilder()
.setName('test3')
.setDescription('Test command for commands with options.')
.addStringOption(option =>
getArgumentList()
.then(list => option.setName('input')
.setDescription('The input to echo back.')
.setChoices(...list) )),
async execute(interaction){
console.log('Testing')
}
}
在這里我得到這個錯誤:
ExpectedValidationError: Expected
at InstanceValidator.handle
...
at Module._load (node:internal/modules/cjs/loader:922:12) {
validator: 's.instance(V)',
given: Promise { <pending> },
expected: [Function: SlashCommandStringOption]
}
Node.js v18.13.0
會有這樣做的好方法嗎?
.then .then()
function 始終返回 promise,因此您不能將其設置為.addStringOption()
的返回值。 使用 async/await 會讓這一切變得更清晰、更容易。
data: new SlashCommandBuilder()
.setName('test3')
.setDescription('Test command for commands with options.')
.addStringOption(async option => {
let list = await getArgumentList()
return option.setName('input')
.setDescription('The input to echo back.')
.setChoices(...list)
})
重構您的命令系統,使數據成為 function,並在您的斜杠命令部署腳本(或您之前使用數據屬性的任何地方)等待它,這樣您就可以將數據更改為:
module.exports = {
data: async () => {
// The list is fetched here (where we can use promises and async-await) before the SlashCommandBuilder gets made.
const list = await getArgumentList();
return new SlashCommandBuilder()
.setName("test3")
.setDescription("Test command for commands with options.")
.addStringOption((option) =>
option
.setName("input")
.setDescription("The input to echo back.")
.setChoices(...list)
);
};
}
示例斜杠命令部署腳本:
const commands = await Promise.all(
client.commandRegistry.map((command) => (await command.data()).toJSON())
);
如果需要,您現在還可以將默認的 SlashCommandBuilder 傳遞給數據 function:
module.exports = {
data: async (b) => {
// The list is fetched here (where we can use promises and async-await) before the SlashCommandBuilder gets made.
const list = await getArgumentList();
// no .setName() required anymore! Deploy script set it for us.
return b
.setDescription("Test command for commands with options.")
.addStringOption((option) =>
option
.setName("input")
.setDescription("The input to echo back.")
.setChoices(...list)
);
};
}
const commands = await Promise.all(
client.commandRegistry.map((command, key) =>
(await command.data(new SlashCommandBuilder().setName(key))).toJSON()
)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.