【问题标题】:Making discord.js send a message to channel on command让 discord.js 根据命令向频道发送消息
【发布时间】:2021-05-17 08:41:35
【问题描述】:

我试图让我的机器人在更新时向它所在的所有服务器中的频道发送消息。我的想法是,每当我更新我的机器人时,我都会手动触发它。例如,我想让它发送一条消息,例如“将机器人更新到 2.03 版。更新日志:(更新中所做的更改)”。这是我目前拥有的代码:

const Discord = require('discord.js');
const client = new Discord.Client();
var Long = require("long");

const getChannel = (guild) => {
    // get "original" default channel
    if(guild.channels.cache.has(guild.id))
      return guild.channels.cache.get(guild.id)
  
const jimmyChannel = guild.channels.cache.find(channel => channel.name === "jimmybot");
if (jimmyChannel)
  return jimmyChannel;
return guild.channels.cache
 .filter(c => c.type === "text" &&
   c.permissionsFor(guild.client.user).has("SEND_MESSAGES"))
 .sort((a, b) => a.position - b.position ||
   Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber())
 .first();
 }
  
  // I found this as an example but I'm not sure if it will work
  client.on("guildMemberAdd", member => {
    const channel = getChannel(member.guild);
    channel.send(`text`);
  });

client.login('token');

我的问题是如何手动调用它而不是在用户加入服务器时发送消息?

【问题讨论】:

  • 您可能想为此使用message 事件。检查作者是否是您,然后通过服务器映射并找到您要发送消息的频道。老实说,我不会这样做,因为您的机器人很容易受到速率限制(如果在很多服务器中)也可以发送许多可能导致您的机器人被禁止使用 Discord 的消息。您可以做些什么来刺激您的用户是在您的服务器中添加一个公告频道并要求他们订阅该频道。

标签: discord discord.js


【解决方案1】:

如果我理解正确的话......

Client 实际上只是 Node.js EventEmitter 的一种变体,如 here 所述。

这意味着您可以自行触发事件,因此您可以在此处创建自己的“自定义”EventEmitter 并自行触发。

Ex 代码与消息事件发射器配对。我知道将事件发射器放在另一个事件发射器中通常是不受欢迎的,但这是我能找到的唯一解决方案。

const Discord = require('discord.js');
const client = new Discord.Client();
token = 'XXX'

client.once('ready', () => {
    console.log('Fully functional and initialized!');
});

// Attach a listener function
client.on('test', console.log);

client.on('message', msg => {
    if (msg.author.bot) return;
    if (msg.content === 'emit event') {
        // Emit the event
        client.emit('test', 'This will be printed on the console');
    }
})

client.login(token);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 2020-04-04
    • 2021-02-06
    • 2021-03-24
    • 2021-08-09
    • 2021-07-27
    • 2020-05-22
    相关资源
    最近更新 更多