我正在尝试使用 discord.js 向特定频道发送消息:
const Discord = require("discord.js");
const client = new Discord.Client();
client.login(process.env.DISCORD_TOKEN);
const channel = client.channels.cache.get("831148754181816351");
channel.send("working");
错误信息:
home/fahd/Desktop/Dev/DiscordBot/main.js:7
channel.send("working");
^
TypeError: Cannot read property 'send' of undefined
at Object.<anonymous> (/home/fahd/Desktop/Dev/DiscordBot/main.js:7:9)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
我尝试将 client.login() 的位置更改为文件末尾。
我尝试改用 channels.cache.find(c => c.id === "831148754181816351");
但它仍然不起作用。
答案 0 :(得分:2)
我按原样测试了您的代码,这意味着它试图检索的 channels
集合是空的。
您需要做的是将其放入客户端事件侦听器中。从 here 中,我了解到编译器将始终先在客户端 EventEmitters 之外运行代码,然后机器人才能登录。最方便的选项(因为看起来您希望在bot 开启)是使用 ready
事件侦听器。
示例代码:
const Discord = require("discord.js");
const client = new Discord.Client();
require('dotenv').config();
client.on('ready', () => {
const channelID = '831148754181816351'; //this is your channelID
const channel = client.channels.cache.get(channelID);
channel.send('working'); //this works :)
});
client.login(process.env.DISCORD_TOKEN);
答案 1 :(得分:0)
您似乎没有获得想要的频道。尝试使用 .fetch()
方法。由于它返回 promise
,您还需要 await
它。
它应该是这样的:
const channelID = '831148754181816351';
const targetChannel = await message.client.channels.fetch(channelID);
// work with 'targetChannel'