discord.js 发现返回未定义

时间:2021-01-02 12:26:37

标签: discord.js sendmessage

我正在尝试向我的机器人添加一个小功能,以便在机器人在线时通知人们。

我做了以下事情:

//BOT connexion actions
client.on("ready", function () {
    console.log("BOT connected");
    client.channels.cache.find(channel => channel.name === 'ID').send("text");
});

我什至尝试使用我拥有的常量,因为所有机器人消息都在特定通道中返回,但它仍然不起作用

const channel01 = client.channels.cache.find(channel => channel.id === "ID");
...
client.channel01.send("text");

当然,ID是具体的频道ID。

我得到的错误是:(node:22000) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined

我不确定这里出了什么问题,因为 .send 在命令输入时得到了正确处理。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果您已经有了频道 ID,可以试试这个。

client.channels.fetch('ID').then(chan => {
    chan.send('The bot is now online!');
});

至于为什么您的代码不起作用,您要使用 ID 来检查名称“general”等,这是等效的。 Does "12383929184" equal "general"?

答案 1 :(得分:0)

这里有一个解决您问题的小方法:

在您的第一个函数中,您尝试按名称查找频道,尽管您似乎在尝试查找 id。 如果您尝试按名称获取频道:

const channelObject = client.channels.cache.find(ch => ch.name === 'channel name');

否则,如果您想通过 ID 找到它,您可以使用:

const channelObject = client.channels.fetch('Channel ID');

从那里,我们可以简单地输入:

channelObject.send('text')

当机器人在线时,我们会收到一点通知!