Discord Bot 无法按名称或 ID 找到频道

Discord Bot can't find channel by name or id

我正在尝试用 node.js 制作一个不和谐的机器人 我想 post 只在特定频道发消息 我试图这样做以将频道保存在变量中,但这不起作用:

const Discord = require('discord.js');
const fs = require("fs");

var bot = new Discord.Client();
var myToken = 'NDQ2OTQ1...................................................';
//client.msg = require ("./char.json");

var prefix = ("/");

//let preset = JSON.parse(fs.readFileSync('preset.json', 'utf8')); // This calls the JSON file.


var offTopic = bot.channels.find("id","448400100591403024"); //.get("448392061415325697");
console.log(offTopic);

每当我 运行 我的机器人它 returns 'null' 与查找和 'undefined' 与获取。 我在 Internet 上搜索帮助,即使我遵循此 post 我的代码也不起作用: 我也试图通过名称找到我的频道,但我也得到了 'undefined' :/

确保您已将 "find" 行放在事件侦听器中。 例如,假设您想在机器人连接成功时找到特定频道:

bot.on('ready', () => {
    console.log(`Logged in as ${bot.user.tag}!`);
    var offTopic = bot.channels.get("448400100591403024");
    console.log(offTopic);
});

当然,可以使用的事件监听器种类繁多,适合您要查找频道的场景。您会在 Events section of the Client Class in the DiscordJS docs. 中找到事件侦听器 试试这个,如果有效请告诉我。

似乎新版本的库使用 .fetch 而不是 .get 并且它 returns 一个承诺:

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
  client.channels.fetch('448400100591403024')
    .then(channel => console.log(channel.name));
});

您从客户端检索信息的方式在 discordjs v12 中发生了变化,如果信息被缓存了,那也适用。

var offTopic = bot.channels.cache.get('448400100591403024'); //.get('448392061415325697');
console.log(offTopic);

如果信息未缓存,您将需要使用 Taylan 建议的获取方法。此方法使用 Discord API 通过 ID 获取 Discord 对象。

client.channels.fetch('448400100591403024')
  .then(channel => console.log(channel.name));

您可以阅读更多关于 discordjs v12 带来的变化here

    bot.on('ready', (message) => {
        var offTopic = client.channels.cache.get("448400100591403024")
        console.log(offTopic)
    })

您可以通过 .then promise 调用或通过 async await 执行此操作,如此处所述:.

代码如下(如果需要,将变量 client 更改为您的机器人):

let channel = await client.channels.fetch('channel-id-here')

// or you can use:

client.channels.fetch('channel-id-here').then( () => {
  // do something here
})

我希望它对这两种情况都有帮助。