首页 > 解决方案 > 尝试发送消息时出现 UnhandledPromiseRejectionWarning

问题描述

我正在尝试通过 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,因为我不知道该输入什么。 在此处输入图像描述


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

标签: node.jsdiscorddiscord.js

解决方案


问题是这一行:

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')


推荐阅读