如何在没有消息对象 Discord.js 的情况下向特定频道发送消息

时间:2021-04-05 17:52:34

标签: javascript node.js discord discord.js

我正在尝试让我的机器人每两小时从 .json 文件向特定频道发送一个随机问题。它不在任何事件侦听器中,所以我没有用于发送消息的消息对象。

我试过用 client.channels.cache.get('id') 定义频道,但这只是说 .send 没有定义。这是我当前的代码:

setTimeout(() => {
  const quiz = require('./quiz.json');
  const item = quiz[Math.floor(Math.random() * quiz.length)];
  let channel = client.channels.cache.get('812178275463856128')
  channel.send(item.question)
}, 7200000);

1 个答案:

答案 0 :(得分:1)

尝试 fetch the channel 并通过访问 type 属性检查它是否是文本频道:

client.once('ready', async () => {
  console.log('Bot is connected...');

  const quiz = require('./quiz.json');
  const channelID = '812178275463856128';

  try {
    const channel = await client.channels.fetch(channelID);

    if (!channel || channel.type !== 'text')
      return console.log(`Can't send message to this channel`);

    setTimeout(async () => {
      const item = quiz[Math.floor(Math.random() * quiz.length)];

      channel.send(item.question);
    }, 7200000);
  } catch (error) {
    console.log(error);
  }
});