我该如何在 discord.js 机器人中修复这个错误?

huangapple go评论123阅读模式
英文:

How can I fix this error in discord.js bot?

问题

这是我的代码:

我为我的 Discord 机器人创建了一个 discord.js 评论功能我将其制作成一个单独的文件以方便使用一切都运行正常没有错误但是当我想要添加一个冷却功能以防止任何人滥用评论时我收到了这条消息我正在使用 replit所以可以让它保持 24/7 在线):

发送评论时出错:DiscordAPIError: 无法发送空消息
在 RequestHandler.execute (/home/runner/Invite-Graphics/node_modules/discord.js/src/rest/RequestHandler.js:154:13) 处
在 processTicksAndRejections (internal/process/task_queues.js:97:5) 处
在 async RequestHandler.push (/home/runner/Invite-Graphics/node_modules/discord.js/src/rest/RequestHandler.js:39:14) 处
在 async ReviewBot.handleReviewCommand (/home/runner/Invite-Graphics/review.js:62:27) 处 {
方法: 'post',
路径: '/channels/1137254692179689542/messages',
代码: 50006,
http 状态: 400
}


这是我的代码:

```js
const { Client, MessageEmbed } = require('discord.js');
const config = require('./config.json');

class ReviewBot extends Client {
  constructor(config) {
    super();
    this.prefix = config.prefix;
    this.reviewChannelId = config.review_channel_id;
    this.cooldowns = new Map();
  }

  async start() {
    try {
      await this.login(process.env.TOKEN);
      console.log('评论机器人成功登录!');
    } catch (error) {
      console.error('登录时出错:', error);
    }
  
    this.once('ready', () => {
      console.log('评论机器人已准备就绪!');
    });
  
    this.on('message', this.handleMessage.bind(this));
  }

  async handleMessage(message) {
    if (!message.content.startsWith(this.prefix) || message.author.bot) return;

    const args = message.content.slice(this.prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'review') {
      const cooldownTime = parseInt(config.review_cooldown_time);
      this.handleReviewCommand(message, args.join(' '), cooldownTime);
    }
  }

  async handleReviewCommand(message, review, cooldownTime) {
    const userId = message.author.id;
    const now = Date.now();
    const userCooldown = this.cooldowns.get(userId);

    if (userCooldown && now < userCooldown) {
      const remainingTime = ((userCooldown - now) / 1000 / 60).toFixed(1);
      message.reply({ content: `您需要等待 ${remainingTime} 分钟才能再次提交评论。`, ephemeral: true });
      return;
    }

    const reviewChannel = this.channels.cache.get(this.reviewChannelId);
    if (!reviewChannel || reviewChannel.type !== 'text') {
      console.error(`无效或缺失的评论通道 ID:${this.reviewChannelId}`);
      return;
    }

    const embed = new MessageEmbed()
      .setAuthor(message.author.username, message.author.displayAvatarURL({ format: 'png', dynamic: true }))
      .setDescription(review)
      .setColor('#00FF00')

    try {
      const sentMessage = await reviewChannel.send({ embeds:  });
      console.log(`评论由 ${message.author.tag} 在 #reviews 中发送:${review}`);

      this.cooldowns.set(userId, now + cooldownTime * 60 * 1000);
      setTimeout(() => this.cooldowns.delete(userId), cooldownTime * 60 * 1000);
    } catch (error) {
      console.error('发送评论时出错:', error);
    }
  }
}

const bot = new ReviewBot(config);
bot.start();

我希望它具有冷却功能,这样当有人发送评论时,他们在一定时间内不能再发送另一个评论。冷却时间将在 config.json 中确定,其格式如下:

"review_cooldown_time": "5"(5 表示 5 分钟)

如果有人想要查看完整的机器人代码,请访问以下链接:https://replit.com/@Cryptic1526/Invite-Graphics#review.js

在尝试添加冷却之前,这是代码的链接:https://pastebin.com/59zxcR0z

英文:

I've made a discord.js reviews feature for my discord bot. I made it on a seperate file for ease of use, and everything works fine, no errors. But when I wanted to add a cooldown feature so no one just spams reviews, I get this message (I'm using replit so I can make it 24/7 online):

Error sending review: DiscordAPIError: Cannot send an empty message
    at RequestHandler.execute (/home/runner/Invite-Graphics/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/Invite-Graphics/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
    at async ReviewBot.handleReviewCommand (/home/runner/Invite-Graphics/review.js:62:27) {
  method: &#39;post&#39;,
  path: &#39;/channels/1137254692179689542/messages&#39;,
  code: 50006,
  httpStatus: 400
}

This is my code:

const { Client, MessageEmbed } = require(&#39;discord.js&#39;);
const config = require(&#39;./config.json&#39;);

class ReviewBot extends Client {
  constructor(config) {
    super();
    this.prefix = config.prefix;
    this.reviewChannelId = config.review_channel_id;
    this.cooldowns = new Map();
  }

  async start() {
    try {
      await this.login(process.env.TOKEN);
      console.log(&#39;Review Bot logged in successfully!&#39;);
    } catch (error) {
      console.error(&#39;Error logging in:&#39;, error);
    }
  
    this.once(&#39;ready&#39;, () =&gt; {
      console.log(&#39;Review Bot is ready!&#39;);
    });
  
    this.on(&#39;message&#39;, this.handleMessage.bind(this));
  }

  async handleMessage(message) {
    if (!message.content.startsWith(this.prefix) || message.author.bot) return;

    const args = message.content.slice(this.prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === &#39;review&#39;) {
      const cooldownTime = parseInt(config.review_cooldown_time);
      this.handleReviewCommand(message, args.join(&#39; &#39;), cooldownTime);
    }
  }

  async handleReviewCommand(message, review, cooldownTime) {
    const userId = message.author.id;
    const now = Date.now();
    const userCooldown = this.cooldowns.get(userId);

    if (userCooldown &amp;&amp; now &lt; userCooldown) {
      const remainingTime = ((userCooldown - now) / 1000 / 60).toFixed(1);
      message.reply({ content: `You need to wait ${remainingTime} more minutes before submitting another review.`, ephemeral: true });
      return;
    }

    const reviewChannel = this.channels.cache.get(this.reviewChannelId);
    if (!reviewChannel || reviewChannel.type !== &#39;text&#39;) {
      console.error(`Invalid or missing review channel with ID: ${this.reviewChannelId}`);
      return;
    }

    const embed = new MessageEmbed()
      .setAuthor(message.author.username, message.author.displayAvatarURL({ format: &#39;png&#39;, dynamic: true }))
      .setDescription(review)
      .setColor(&#39;#00FF00&#39;)

    try {
      const sentMessage = await reviewChannel.send({ embeds: [embed] });
      console.log(`Review sent by ${message.author.tag} in #reviews: ${review}`);

      this.cooldowns.set(userId, now + cooldownTime * 60 * 1000);
      setTimeout(() =&gt; this.cooldowns.delete(userId), cooldownTime * 60 * 1000);
    } catch (error) {
      console.error(&#39;Error sending review:&#39;, error);
    }
  }
}

const bot = new ReviewBot(config);
bot.start();

I wanted it to have a cooldown, so that when someone sends a review, they cant send another one until some minutes have passed. And an ephemeral message would be shown to that user and it will say they need to wait so and so time until they can review again. The cool down time will be determined in a config.json, which has the layout like so:

&quot;review_cooldown_time&quot;:&quot;5&quot; (5 as in 5 minutes)

Here is the code link if anyone wants to see the full bot code: https://replit.com/@Cryptic1526/Invite-Graphics#review.js

I tried ChatGPT and Bard, those didn't help, tried researching online, still nada.

EDIT: Here is the code BEFORE I tried to add the cooldown: https://pastebin.com/59zxcR0z

答案1

得分: -2

Dennis,请下次分享版本。你在一个地方使用了版本12.53,在另一个地方使用了版本13。如果你打算继续使用版本13,你需要迁移,或者降级你的新代码,并遵守API的正确版本。

英文:

Dennis, next time share versions, please. you are using version 12.53 in one and version 13 in the other. you need to migrate if you you are going to continue to use version 13 or downgrade your new code and abide buy the correct version of the API.

huangapple
  • 本文由 发表于 2023年8月5日 15:05:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定