Discord.js-不使用客户端EventEmitter无法获取频道属性 [英] Discord.js - Without using Client EventEmitter cannot get channels property

查看:52
本文介绍了Discord.js-不使用客户端EventEmitter无法获取频道属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有更好地了解Node.js,但是当我修改Discord机器人时,我似乎找不到不把它放入的渠道清单的方法.在EventEmitter中.我对为什么这种方法行不通感到困惑,我缺少什么了吗?

I still have yet to get a better grasp of Node.js, but as I was tinkering around with my Discord bot, I couldn't seem to find a way to get the list of channels the bot was in without putting it in an EventEmitter. I'm rather confused as to why this wouldn't work, is there something that I'm missing?

代码:

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(),这就是客户端拥有上下文的时候.所有事件监听器(就绪,消息等.)都绑定到客户端.

This is because the client is not logged in at that point of your code. At the compile stage of your file, the compiler runs through your code and compiles everything outside of event listeners. Once Client#login() is called, this is when the client has it's context. All of it's event listeners (ready, message ect.) are binded to the client.

换句话说,编译事件外的代码 时,Discord客户端未登录.客户端登录后,便会执行代码内部事件.事件本身就发出了.

In other words, the Discord client is not logged in when code outside of events being is compiled. Code inside events are executed once the client is logged in & the event itself is emitted.

这篇关于Discord.js-不使用客户端EventEmitter无法获取频道属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆