嗨,我想创建一个 Discord.JS-Commando 命令,如果您选择一个 channel ,机器人会删除它在那里拥有的一个 Webhook,如果它的名称为 Marker
,并且它会检测是否没有 Webhook它拥有名为 Marker
的东西,它只是 return message.channel.send("Hey! There's no webhook I own in this Channel!")
机器人会删除网络钩子(Hook),即使它没有成功,而且它不在我提到的 channel 中。我该如何解决这个问题?
用谷歌搜索了一下,什么也没有。 除了discord.js 文档之外,没有任何关于删除 webhook 的内容。
const hooks1 = await message.guild.fetchWebhooks();
await hooks1.forEach(async webhook => {
if (!watchChannel.id == webhook.channelID) return
if (!webhook.owner.id == `595840576386236437`) return
if (!webhook.name == `Marker`) return message.channel.send(`**${message.author.username}**, Nothing was found. You or someone else may have renamed the webhook. Please delete the webhook manually. Sorry for the inconvenience`);
else
message.channel.send(`Deleted successfully.`).then(msg => {message.delete(4000)}).catch(error => console.log(error))
webhook.delete(`Requested per ${message.author.username}#${message.author.discriminator}`);
});
我希望机器人知道如何删除它在提到的 channel 中创建的 Webhook,但机器人不知道要删除哪个 Webhook。
最佳答案
if (!watchChannel.id == webhook.channelID) return if (!webhook.owner.id == `595840576386236437`) return if (!webhook.name == `Marker`) return
这些行都没有按照您的预期工作。
const id = '189855563893571595';
console.log(id === '189855563893571595');
console.log(id !== '1234'); // id is not equal to '1234': true
console.log(!id === '1234'); // false is equal to '1234' : false
!
充当逻辑 NOT 运算符。
Returns
false
if its single operand can be converted totrue
; otherwise, returnstrue
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
!watchChannel.id
是 Boolean ;它永远不会等于webhook.channelID
,除非后者为false
。代码中的所有三个条件也是如此。因此,您的机器人将删除不属于自己的 Webhook,因为 if
语句在您预期的情况下不为真。
!==
被称为非同一/严格不等运算符。
...[R]eturns
true
if the operands are not equal and/or not of the same type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
这个(或与双胞胎一起使用的不等运算符!=
)是您想要使用的运算符。它将正确比较属性。
改进您当前的代码,我们可以...
- 仅从指定 channel 获取 Webhook。
- 过滤 Collection在循环之前。
- 使用现代
for...of
循环将与异步代码一起正常工作。 - 确保捕获所有被拒绝的 promise 。
- 养成使用恒等运算符
===
而不是相等运算符==
的习惯。请参阅here用于推理。
const webhooks = await watchChannel.fetchWebhooks();
const myWebhooks = webhooks.filter(webhook => webhook.owner.id === client.user.id && webhook.name === 'Marker');
try {
if (myWebhooks.size === 0) return await message.channel.send('I don\'t own any Webhooks there...');
for (let [id, webhook] of myWebhooks) await webhook.delete(`Requested by ${message.author.tag}`);
await message.channel.send('Successfully deleted all of my Webhooks from that channel.');
} catch(err) {
console.error(err);
await message.channel.send('Something went wrong.')
.catch(console.error);
}
关于javascript - 如何让机器人知道如何删除它创建的网络钩子(Hook)以及按 channel 提及的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56895217/