【问题标题】:TypeError: Cannot read property 'includes' of nullTypeError:无法读取 null 的属性“包含”
【发布时间】:2021-03-02 11:32:12
【问题描述】:

我的 discord 机器人运行良好,并且完全按照我的意愿运行。但是现在当我运行机器人时,它会运行几分钟,然后崩溃并出现此错误

if (embed.title.includes("Raid") && embed.fields[1].value.includes("5 minutes left")) {

TypeError: Cannot read property 'includes' of null

这是我当前正在运行的代码!

const Discord = require("discord.js")
const client = new Discord.Client()
client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on('message', (message) => {
  if (message.author.id === '432616859263827988') {
    if (message.embeds.length == 1) {
      const embed = message.embeds[0]
      if (embed.title.includes("Raid") && embed.fields[1].value.includes("5 minutes left")) {
        return  message.channel.send('<@&777249060293443595> Raid Time!')
      }
    }
  }
})

我曾尝试查找类似的问题,但我无法让我的机器人保持在线和稳定。如果我需要添加更多信息,请告诉我! 谢谢!

【问题讨论】:

  • 错误表明embed.titlenullembed.fields[1].valuenull。你能console.log 两个值并检查哪一个是null 吗?这将帮助我们帮助您
  • 是的,我绝对可以!我会尝试查找如何做到这一点,除非你先看到这个并让我知道如何做,对不起,我是一个试图弄清楚事情的新手。我会尽快回复!谢谢!
  • 好的!所以看起来embed.titlenull 的形式返回,当发送来自相同ID 的另一条不包含标题字段的消息时会发生这种情况。那么有没有办法编辑我的代码来解决这个问题?
  • 你可以检查它是否存在于前面的if 语句中。 if (message.embeds.length === 1 &amp;&amp; message.embeds[0].title &amp;&amp; message.embeds[0].fields[1])
  • 我做出了改变,效果很好!谢谢两位的帮助!

标签: null discord.js embed


【解决方案1】:

这是一个简短的解决方案。只需添加?

const Discord = require("discord.js")
const client = new Discord.Client()
client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on('message', (message) => {
  if (message.author.id === '432616859263827988') {
    if (message.embeds.length == 1) {
      const embed = message.embeds[0]
      if (embed.title?.includes("Raid") && embed.fields[1]?.value?.includes("5 minutes left")) {
        return  message.channel.send('<@&777249060293443595> Raid Time!')
      }
    }
  }
})

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多