我正在開發一個 Discord 機器人,我試圖讓按鈕只對使用該命令的用戶起作用。
如果我聽起來很愚蠢,我很抱歉,但我不知道如何正確解釋。
到目前為止,我所擁有的是在通道中發送訊息的命令測驗,并附有 2 個按鈕,而我想要的是將用戶 ID 附加到按鈕上。
.setCustomId( button1-${message.author.id})
如果所有代碼都在一個檔案中,這實際上是有效的。但是,如果我拆分按鈕的代碼,它就不起作用。
我嘗試將 -${interaction.user.id} 添加到按鈕名稱中,但它不起作用,因為它給了我“未定義互動”。
module.exports = {
data: {
name: `button1`
},
async execute (interaction, client) {
interaction.channel.send({ content: "This button works!"})
}
}
有沒有辦法將用戶的 id 添加到按鈕名稱中?
uj5u.com熱心網友回復:
這應該可以幫助你。任何時候使用應用程式命令時,該訊息都有一個元素來識別發送interaction.message.interaction.user.id者,即發送命令者的用戶 ID。
但是,在您的使用中,您正在使用一條訊息,這很好,并且它仍然可以作業,因為訊息具有指定要回復誰的元素,interaction.message.mentions.users因此要為您使用它,請嘗試以下代碼。您無需將用戶 ID 添加到按鈕代碼中。
if (message.content.startsWith(PREFIX "test")) {
const row = new MessageActionRow().addComponents(
new MessageButton()
.setLabel("?")
.setStyle("PRIMARY")
.setCustomId(`button1`),
new MessageButton()
.setLabel("?")
.setStyle("SECONDARY")
.setCustomId(`button2`),
);
message.reply({
content: "Hello",
components: [row],
});
}
interactionCreate如果是主 bot.js 檔案的一部分,則以下部分是您的代碼的一部分
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId;
if (buttonID === 'button1') {
if (interaction.message.mentions.users.get(interaction.user.id)) {
interaction.channel.send({
content: "This button works!",
});
// This is the sender of the command
console.log(true);
} else {
// This is not the sender
console.log(false);
return;
}
} else if (buttonID === 'button2') {
if (interaction.message.mentions.users.get(interaction.user.id)) {
interaction.channel.send({
content: "This button works!",
});
console.log(true);
} else {
// This is not the sender
console.log(false);
return;
}
}
}
});
如果您將interactionCreate命令作為單獨的檔案,代碼將如下所示
module.exports = {
data: {
name: `interactionCreate`,
},
async execute(interaction, client) {
const buttonID = interaction.customId;
if (buttonID === 'button1') {
if (interaction.message.mentions.users.get(interaction.user.id)) {
interaction.channel.send({
content: "This button works!",
});
// This is the sender of the command
console.log(true);
} else {
// This is not the sender
console.log(false);
return;
}
} else if (buttonID === 'button2') {
if (interaction.message.mentions.users.get(interaction.user.id)) {
interaction.channel.send({
content: "This button works!",
});
console.log(true);
} else {
// This is not the sender
console.log(false);
return;
}
}
},
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476817.html
標籤:javascript 节点.js 不和谐 不和谐.js
