我还没有更好地掌握Node.js,但是当我在修补我的Discord bot时,我似乎无法找到一种方法,不将它放入EventEmitter中就可以获得bot所在的频道列表。我很困惑为什么这不起作用,是不是我遗漏了什么?
代码:
const Discord = require("discord.js");
const client = new Discord.Client();
require('dotenv').config();
//this works
client.on('ready', ()=> {
const channelID = '803359668054786118';
const channel = client.channels.cache.get(channelID);
channel.send('working'); //this works
});
//this doesn't work
//intially tried using a wait function to see if the reason was because bot didn't have enough time to log on properly
setTimeout(function() {
const channelID = '803359668054786118';
const channel = client.channels.cache.get(channelID);
console.log(client.channels); //this is telling me that there's no channels in the collection...
//channel.send('working');
}, 500);
这是因为客户端没有在您的代码的那一点登录。在文件的编译阶段,编译器运行您的代码并编译事件侦听器之外的所有内容。调用client#login()
之后,客户端就有了它的上下文。所有的事件监听器(就绪、消息等)绑定到客户端。
换句话说,当编译事件外部的代码时,不登录Discord客户端。一旦客户端登录,事件内部的代码就会执行&事件本身就会发出。