Discord.js |类型错误:无法读取 null

时间:2021-04-27 00:28:17

标签: javascript discord discord.js

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

代码:

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:\Users\Utilisateur\Desktop\discordbot4\main.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. 

有人可以帮我解决这个错误吗?

2 个答案:

答案 0 :(得分:1)

一些事情:

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

答案 1 :(得分:0)

您的代码,但包含@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 documentation,我可以看到 .member(user) 函数如果找到则返回 GuildMember,否则返回 null
因此,据我所知,channel.guild.member(executor) 为空...看来 executor 实际上并不是您认为的那样。