【问题标题】:UnhandledPromiseRejectionWarning when trying to send message尝试发送消息时出现 UnhandledPromiseRejectionWarning
【发布时间】:2020-12-05 22:12:17
【问题描述】:

我正在尝试通过 discord.js 发送消息,但出现以下错误:
(node:10328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined

这是我的代码:

// Init
const Discord = require("discord.js");
const bot = new Discord.Client();
const channel = bot.users.cache.get('4257');

// Vars

// Code
bot.on("ready", () => {
    console.log("The Bot is ready!");

    channel.send("Test");
});


// Login
bot.login(" "); // I will hide this.

怎么了?是通道变量上的 id 吗?我只是输入了我的机器人的 id,因为我不知道该输入什么。


起初我在“文本权限”下给了它所有权限,但我也尝试给他管理员权限。它仍然没有工作。我做错了什么?

【问题讨论】:

  • 问题出在const channel = bot.users.cache.get('4257'); 行中,似乎返回未定义。
  • 是的,但是为什么呢?我的语法不正确吗?
  • 您很可能需要深入研究文档,看看您是否正确使用了这些功能。

标签: node.js discord discord.js


【解决方案1】:

问题出在这一行:

const channel = bot.users.cache.get('4257');

这里有什么问题:

const channel = bot.users.cache // this returns a collection of users, you want channels.
.get('4257'); // this is a user discriminator, you want a channel ID

解决方法如下:

const id = <ID of channel you want to send the message to>
const channel = bot.channels.cache.get(id)

// ...

channel.send('Test')

这是一个例子:

const channel = bot.channels.cache.get('699220239698886679')
channel.send('This is the #general channel in my personal Discord')

【讨论】:

  • 另外,'4257',你最初说的是你的机器人的 ID,实际上是鉴别器。用户 ID 看起来更像这样:713102337908015227。要查找您的机器人 ID,您可以运行 console.log(bot.user.id)Learn all the properties of user here
  • 我试过了,但仍然出现同样的错误。让我在不同的脚本和服务器上试试这个。
  • 您为频道 ID 输入了什么?
  • 我和你一样在bot.channels.cache.get(); 函数中传递了它。然后我调用了发送函数。
  • 但是您使用的频道 ID 是什么?如果您使用的是我在示例中提供的那个,它将不起作用。见kb.statbot.net/faq/how-do-i-find-my-server-user-channel-id/…。了解如何查找频道 ID
【解决方案2】:

这里的常量通道是空的。您需要确保应该在其中分配值。

channel.send("Test");

如果该值不是强制性的,则使用 try-catch。

try {
 channel.send("Test");
} catch(e) {
 console.log(e)
}

如果有帮助,请投票支持或回答,谢谢。

【讨论】:

  • try-catch 没有帮助。我也尝试直接运行命令:bot.users.cache.get('4257').send("Test");
  • 你不懂try catch是为了解决异常。你的问题是下面的代码没有给出任何价值。你需要解决这个问题。 .send("Test") 不是问题。 bot.users.cache.get('4257')
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2018-05-12
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
相关资源
最近更新 更多