不和谐.js |类型错误: 无法读取 null 的属性"ban"



目的:在创建通道时删除通道,然后禁止创建通道的成员。

代码:

bot.on('channelCreate', async (channel, member) => {
if (!channel.guild)
return;
const audit = (await channel.guild.fetchAuditLogs()).entries.first();
if (audit.action === 'CHANNEL_CREATE')
if (audit.executor.id === '833382653779509288')
return;
channel.delete();
channel.guild.member(executor).ban({reason: 'aaaaaa'})
})`

结果:频道被删除,但用户未被禁止。

错误如下:

(node:8388) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ban' of null
at Client.<anonymous> (C:UsersUtilisateurDesktopdiscordbot4main.js:30:49)
at processTicksAndRejections (internal/process/task_queues.js:82:5)
(node:8388) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by 
rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8388) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

有人能帮我纠正这个错误吗?

很少有东西:

  1. 您正在删除频道,然后尝试访问其guild.member。按相反的顺序做
  2. User.ban()返回一个Promise对象,因此您应该await它的结果。(文档(
  3. bot.on('channelCreate',没有任何member参数,只有channel(文档(
  4. 使用fetchAuditLogs()可以使用options,例如将options.limit设置为1。这样,您就不需要.first()方法(而且它应该会快一点(。(文档(

您的代码,但(大部分(来自@Gaben的建议。

bot.on('channelCreate', async (channel) => {
if (!channel.guild) return;
const audit =
( await channel.guild.fetchAuditLogs() ).entries.first();
if (
audit.action === 'CHANNEL_CREATE' &&
audit.executor.id === '833382653779509288'
) return;
channel.guild.member(executor).ban({
reason: 'aaaaaa'
});
await channel.delete();
});

我从未使用过Discord.js,这就是为什么我不愿意过多地更改代码。


我刚刚注意到与代码相比,您的错误看起来如何,我想我知道问题所在
错误显示Cannot read property "ban" of null,,我认为这意味着channel.guild.member(executor)正在返回null。查看discord.js文档,我可以看到,如果找到.member(user)函数,它将返回一个GuildMember,否则它将返回null
根据我的判断,channel.guild.member(executor)为空。。。看起来executor实际上并不是你想象的那样。

最新更新