Pilar
Pilar

Reputation: 13

Discord bot to send a message if a certain member goes online

I have been doing my research in the past few days but I couldn't find literally anything. Same in python.

const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })

const member = client.guilds.cache.get("person_id") // person I want to check

client.on("ready", () => {
   console.log(`Logged in as ${client.user.tag}!`)
})

client.on("message", msg => {
   if (msg.content === "ping") {
      msg.reply("pong");
   }
}) // everything worked to this moment

client.on("presenceUpdate", () => {
   if (member.presence.status === 'online') {
      client.channels.cache.get("channel_id").send("HELLO"); // message i want bot send to the channel if member goes online
   }
});

client.login('***')

If I add the GUILD_PRESENCES intent, I receive the following error:

if (member.presence.status === 'online') { 
           ^ TypeError: Cannot read properties of undefined (reading 'presence')

Upvotes: 1

Views: 1552

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23161

First, you'll need to enable the GUILD_PRESENCES intent if you want to use the presenceUpdate event.

Second, client.guilds.cache.get("person_id") doesn't return a member. guilds.cache is a collection of guilds, not members.

And last, presenceUpdate fires whenever a member's presence (e.g. status, activity) is changed. It means that their presence can be the same (e.g. online), yet the event still fires, so checking if (member.presence.status === 'online') won't work. What you can do instead is to compare the old and new presences. You can find the code below and I've added some comments to make it a bit clearer.

const Discord = require('discord.js');
const client = new Discord.Client({
  intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_PRESENCES'],
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('presenceUpdate', (oldPresence, newPresence) => {
  // if someone else has updated their status, just return
  if (newPresence.userId !== 'person_id') return;
  // if it's not the status that has changed, just return
  if (oldPresence.status === newPresence.status) return;
  // of if the new status is not online, again, just return
  if (newPresence.status !== 'online') return;

  try {
    client.channels.cache.get('channel_id').send('HELLO');
  } catch (error) {
    console.log(error);
  }
});

client.login('***');

Upvotes: 1

Related Questions