Darshan B
Darshan B

Reputation: 807

discord.js Unhandled Promise Rejection Warning : TypeError: Cannot read property 'includes' of null

I made an auto role code for my bot recently, which reads the status of every user and gives them a role if they have our server vanity invite link in their status. The code works perfectly, the bot adds the role, and removes it, but the problem here is it loops through an error without crashing the bot :

(node:38) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of null
(node:38) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 345)

I'm pretty sure it's because the bot isn't able to read the status of such users who are offline and don't have a status. I'd be thankful for a help since I couldn't figure out the fix to this. This is my code :

client.on('presenceUpdate', async (oldPresence, newPresence) => {

    const role = newPresence.guild.roles.cache.get("832132526302035992");
    const member = newPresence.member
    const activities = member.user.presence.activities[0];
  
    if (activities && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
      return newPresence.member.roles.add(role)
      .catch(err => {
      console.log(err)
      return;
      })

    } else {
    if(member.roles.cache.get(role.id)) {
      newPresence.member.roles.remove(role)
      .catch(err => {
      console.log(err)
      return;

      })
      }
    }
});

Upvotes: 0

Views: 745

Answers (2)

HellCatVN
HellCatVN

Reputation: 876

With some people when they change from exist state to none it will not having data so the checking should be


    if (activities &&  activities.state && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
      return newPresence.member.roles.add(role)
      .catch(err => {
      console.log(err)
      return;
      })

    }

Upvotes: 1

user15517071
user15517071

Reputation: 614

Check for activities first, then check for activities.state and finally include .include()

Upvotes: 0

Related Questions