【问题标题】:Discord.js - Without using Client EventEmitter cannot get channels propertyDiscord.js - 不使用客户端 EventEmitter 无法获取通道属性
【发布时间】:2021-07-07 15:59:09
【问题描述】:

我还没有更好地掌握 Node.js,但是当我在修改我的 Discord 机器人时,我似乎无法找到一种方法来获取机器人所在的频道列表而不放置它在 EventEmitter 中。我很困惑为什么这不起作用,有什么我遗漏的吗?

代码:

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

【问题讨论】:

    标签: node.js discord discord.js


    【解决方案1】:

    这是因为客户端在您的代码中没有登录。在文件的编译阶段,编译器会运行您的代码并编译事件侦听器之外的所有内容。一旦Client#login() 被调用,这就是客户端拥有它的上下文的时候。它的所有事件监听器(ready、message ect.)都绑定到客户端。

    换句话说,当代码在事件之外被编译时,Discord 客户端没有登录。一旦客户端登录并发出事件本身,就会执行事件中的代码。

    【讨论】:

    • 有没有办法让它等到客户端登录后再编译?我尝试使用 setTimeout 函数来做到这一点,但从你所说的情况来看,它不会那样工作。
    • 遗憾的是,编译器无论如何都会运行您的代码。是否有不使用 ready 事件的特定原因?
    • 主要是不必使用 EventEmitter。无论如何,这更像是一个概念性问题,所以谢谢!
    猜你喜欢
    • 2021-04-12
    • 2020-03-06
    • 1970-01-01
    • 2021-10-20
    • 2017-09-28
    • 2012-07-07
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多