我目前正在使用 Discord.js 和 Firebase 实时数据库为我的 Discord 机器人实现反链接功能。该功能应该删除服务器通道内包含链接的任何消息。但是,我遇到了机器人无法删除带有链接的消息的问题。
反链接功能旨在根据用户命令打开/关闭(反链接开/关)。 启用该功能后,机器人预计会实时删除任何包含链接的消息。 我已验证机器人成功检索频道中的消息并正确识别带有链接的消息。 然而,尽管识别出带有链接的消息,机器人仍无法按预期删除它们。
// antilink.js
const { EmbedBuilder } = require('discord.js');
const db = require('../db/db.js'); //firebase
// Function to delete messages containing links
async function deleteMessagesWithLinks(channel) {
try {
const messages = await channel.messages.fetch(); // Fetch all messages in the channel
messages.forEach(msg => {
if (msg.content.match(/(http(s)?:\/\/[^\s]+)/g)) { // Check if the message contains a link
msg.delete()
.then(deletedMsg => console.log(`Deleted message: ${deletedMsg.content}`))
.catch(error => console.error('Error deleting message:', error));
}
});
} catch (error) {
console.error('Error fetching or deleting messages:', error);
}
}
// Command to toggle anti-link feature on/off and delete links
async function execute(message, args) {
if (!message.guild) return message.reply('This command can only be used in a server.');
const guildId = message.guild.id;
try {
if (args[0] === 'status') {
// Check the current status of the anti-link feature
const snapshot = await db.ref(`guilds/${guildId}/antilink/enabled`).once('value');
const isEnabled = snapshot.val();
// Send a message with the current status
const statusMessage = isEnabled ? 'enabled' : 'disabled';
const embed = new EmbedBuilder()
.setColor('#00ff00') // Example color
.setTitle(`Anti-link feature is ${statusMessage}`)
.setDescription(`Anti-link feature is currently ${statusMessage}.`);
return message.channel.send({ embeds: [embed] });
}
// Toggle anti-link feature on/off
const snapshot = await db.ref(`guilds/${guildId}/antilink/enabled`).once('value');
let isEnabled = snapshot.val();
if (args[0] === 'on') {
if (isEnabled) {
return message.channel.send('Anti-link feature is already enabled.');
}
isEnabled = true;
} else if (args[0] === 'off') {
if (!isEnabled) {
return message.channel.send('Anti-link feature is already disabled.');
}
isEnabled = false;
} else {
// If no argument is provided, display the current status
const status = isEnabled ? 'enabled' : 'disabled';
return message.channel.send(`Anti-link feature is currently ${status}.`);
}
// Update the anti-link feature status in the database
await db.ref(`guilds/${guildId}/antilink`).update({ enabled: isEnabled });
// Send a confirmation message with status
const statusMessage = isEnabled ? 'enabled' : 'disabled';
const embed = new EmbedBuilder()
.setColor('#00ff00') // Example color
.setTitle(`Anti-link feature has been ${statusMessage}`)
.setDescription(`Anti-link feature is now ${statusMessage}.`);
message.channel.send({ embeds: [embed] });
// If anti-link feature is enabled, delete messages with links
if (isEnabled) {
await deleteMessagesWithLinks(message.channel);
}
} catch (error) {
console.error('Error toggling anti-link feature:', error);
message.channel.send('An error occurred while toggling anti-link feature. Please try again later.');
}
}
// Export the command and the deleteMessagesWithLinks function in a single module.exports
module.exports = {
name: 'antilink',
description: 'Toggle anti-link feature on/off and delete links.',
execute,
deleteMessagesWithLinks
};
deleteMessagesWithLinks 函数负责获取频道中的消息并删除包含链接的消息。 执行函数根据用户命令处理打开/关闭反链接功能。 这两个函数都从模块中导出,并在机器人收到相关命令时相应地执行。
我已确保机器人具有删除频道中的消息所需的权限(例如 MANAGE_MESSAGES)。 Firebase 实时数据库已正确配置,机器人能够从中检索和更新数据,不会出现任何问题。
我正在寻求指导来确定此问题的潜在原因并实施解决方案,以确保机器人在启用反链接功能时成功删除包含链接的消息。
任何见解、建议或替代方法将不胜感激。预先感谢您的协助!
注意:版本 -discord.js v14
如果没有看到 MessageCreate 事件文件,我无法 100% 确定问题的原因是什么,但我认为这很可能是由于 MessageCreate 事件侦听器中的代码结构造成的。 “deleteMessagesWithLinks”函数在命令执行后不会触发,最好的解决方案是将此函数放在 MessageCreate 事件的顶部。
它应该看起来像这样
discord.client.on('MessageCreate', (msg) => {
const guild = msg.guild;
const channel = msg.channel;
if (!msg.startsWith('prefix')) {
// check here for the link in msg.content
} else {
// execute cmd
}
}).setMaxListeners(0);