【问题标题】:Discord bot to send a message if a certain member goes online如果某个成员上线,Discord bot 会发送消息
【发布时间】:2022-02-01 20:46:19
【问题描述】:

过去几天我一直在进行研究,但实际上找不到任何东西。在 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')

【问题讨论】:

  • 代码看起来不错,但我认为需要GUILD_PRESENCES 意图。
  • 好吧,现在机器人理论上可以工作,但是当状态改变时我得到一个错误:if (member.presence.status === 'online') { ^ TypeError: Cannot read properties of undefined (reading '存在')

标签: javascript discord discord.js bots


【解决方案1】:

首先,如果您想使用presenceUpdate 事件,您需要enable the GUILD_PRESENCES intent

其次,client.guilds.cache.get("person_id") 不返回成员。 guilds.cache 是公会的集合,而不是成员。

最后,presenceUpdate 会在成员的状态(例如状态、活动)发生变化时触发。这意味着他们的presence 可以相同(例如在线),但事件仍然会触发,因此检查if (member.presence.status === 'online') 将不起作用。您可以做的是比较新旧presences。您可以在下面找到代码,我添加了一些 cmets 使其更清晰。

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

【讨论】:

  • 非常感谢,一切正常
  • 不客气 :)
  • ofc 我现在就这么做! (我不知道我以前可以做这样的事情)
猜你喜欢
  • 2019-01-16
  • 2021-06-06
  • 2020-12-01
  • 2021-03-02
  • 2021-01-12
  • 2021-06-05
  • 2022-01-05
  • 2020-12-03
  • 2021-09-17
相关资源
最近更新 更多