I'm trying to make a vanity bot for Discord, but I'm not sure if I'm using the correct event. Here is my code:
client.on("presenceUpdate", newPresence => {
let vanityRole = newPresence.guild.roles.cache.find(role => role.id === "940679835456536596");
const activity = newPresence.member.user.presence.activities[0].state
if (activity === null) return;
if (activity.includes("gg/pm")) {
let memberTarget = newPresence.guild.members.cache.get(newPresence.member.id);
memberTarget.roles.add(vanityRole);
const vanity = new Discord.MessageEmbed()
.setColor(color)
.setDescription(`<@${memberTarget.id}>, thanks for putting us in your status <3`);
message.channel.send(vanity)
}
else return;
});
Here is the error I'm receiving:
On this line: const activity = newPresence.member.user.presence.activities[0].state
Error: [TypeError: Cannot read property 'state' of undefined]
repl process died unexpectedly: exit status 1
Thanks
One of your items at newPresence.member.user.presence.activities is equal to an empty array or undefined, therefore newPresence.member.user.presence.activities[0] === undefined.
You can try: const activity = newPresence.member.user.presence.activities[0]?.state
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.