【问题标题】:How do I send a message to a specific channel without a message object Discord.js如何在没有消息对象 Discord.js 的情况下向特定频道发送消息
【发布时间】:2021-07-01 13:47:15
【问题描述】:

我正在尝试让我的机器人每两小时从.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);

【问题讨论】:

  • 我 console.logged 通道变量并返回 undefined

标签: javascript node.js discord discord.js


【解决方案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);
  }
});

【讨论】:

  • 05.04 14:02:58 [Bot] HTTPError [DiscordjsError]: 请求使用令牌,但客户端无法使用令牌。
  • 您登录了吗?上面的代码不应该抛出这样的错误。不知道你的代码的其余部分是什么样的......
  • 这是我的整个 login.js:pastebin.com/dvXNerWT
  • 你可以用const channel = await bot.channels.fetch(channelID);来代替吗?
  • 我删除了 setTimeout 并重新运行了代码,它工作正常,感谢您的帮助!
猜你喜欢
  • 2021-08-21
  • 2020-04-04
  • 2021-08-09
  • 2020-05-22
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多