如果某个成员上线,Discord 机器人会发送消息

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

过去几天我一直在做研究,但我几乎找不到任何东西。在 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('***')

如果我添加 GUILD_PRESENCES 意图,我会收到以下错误:

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

首先,如果您想使用 presenceUpdate 事件,您需要

第二,client.guilds.cache.get("person_id") 不是 return 会员。 guilds.cache是公会的集合,不是会员。

最后,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。您可以在下面找到代码,我添加了一些注释以使其更加清晰。

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('***');