英文:
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: 'post',
path: '/channels/1137254692179689542/messages',
code: 50006,
httpStatus: 400
}
This is my code:
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('Review Bot logged in successfully!');
} catch (error) {
console.error('Error logging in:', error);
}
this.once('ready', () => {
console.log('Review Bot is ready!');
});
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: `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 !== 'text') {
console.error(`Invalid or missing review channel with 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: [embed] });
console.log(`Review sent by ${message.author.tag} in #reviews: ${review}`);
this.cooldowns.set(userId, now + cooldownTime * 60 * 1000);
setTimeout(() => this.cooldowns.delete(userId), cooldownTime * 60 * 1000);
} catch (error) {
console.error('Error sending review:', 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:
"review_cooldown_time":"5" (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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论