尝试发送消息时出现UnhandledPromiseRejectionWarning

时间:2020-08-16 16:53:51

标签: node.js discord discord.js

我正在尝试通过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。 enter image description here


最初,我在“文本权限”下为它提供了所有权限,但我也尝试为他提供admin privs。它仍然没有用。我在做什么错了?

2 个答案:

答案 0 :(得分:3)

问题是这一行:

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

答案 1 :(得分:-1)

const通道在此处为空。您需要确保在其中分配值。

channel.send("Test");

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

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

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