Discord机器人全局斜杠命令配置及消息存储问题求助
Discord 斜杠命令全局部署与重置方案(附消息日志机器人实现要点)
一、让斜杠命令在所有服务器可用(全局命令)
discord.js 中,全局命令直接注册到机器人应用程序层面,而非单个服务器。部署方式如下:
- 使用
client.application.commands.create()方法创建全局命令,而非指定服务器的guild.commands.create() - 全局命令生效需要约1小时同步时间,测试阶段可先用服务器级命令(即时生效),正式上线再切换全局
示例代码(注册全局日志配置命令):
const { SlashCommandBuilder } = require('discord.js'); // 机器人就绪后执行注册 client.on('ready', async () => { await client.application.commands.create( new SlashCommandBuilder() .setName('log-setup') .setDescription('配置消息日志存储频道') .addChannelOption(option => option.setName('channel') .setDescription('选择日志存储频道') .setRequired(true) ) ); console.log('全局命令已提交注册'); });
二、删除所有已注册命令后重新添加
1. 删除所有全局命令
client.on('ready', async () => { // 获取所有全局命令 const globalCommands = await client.application.commands.fetch(); // 批量删除 await Promise.all(globalCommands.map(cmd => cmd.delete())); console.log('所有全局命令已删除'); // 重新注册新命令 await client.application.commands.create( new SlashCommandBuilder() .setName('new-command') .setDescription('新的全局命令') ); });
2. 删除指定服务器的所有命令
如果之前注册过服务器级命令,需单独清理:
client.on('ready', async () => { const guild = client.guilds.cache.get('你的服务器ID'); if (!guild) return; const guildCommands = await guild.commands.fetch(); await Promise.all(guildCommands.map(cmd => cmd.delete())); console.log(`服务器 ${guild.name} 的所有命令已删除`); });
三、消息日志机器人核心实现要点
针对删除/编辑消息存储需求,补充两个关键逻辑:
1. 监听消息删除事件
const fs = require('fs'); client.on('messageDelete', async (message) => { // 排除机器人自身消息 if (message.author.bot) return; // 构造日志数据 const logData = { type: 'deleted', content: message.content, author: message.author.tag, authorId: message.author.id, channel: message.channel.name, channelId: message.channel.id, timestamp: new Date().toISOString() }; // 写入JSON文件(可替换为数据库操作) fs.readFile('./message-logs.json', 'utf8', (err, data) => { const logs = err ? [] : JSON.parse(data); logs.push(logData); fs.writeFile('./message-logs.json', JSON.stringify(logs, null, 2), (err) => { if (err) console.error('写入日志失败:', err); }); }); });
2. 监听消息编辑事件
client.on('messageUpdate', async (oldMessage, newMessage) => { if (oldMessage.author.bot) return; // 排除内容未变化的情况 if (oldMessage.content === newMessage.content) return; const logData = { type: 'edited', oldContent: oldMessage.content, newContent: newMessage.content, author: oldMessage.author.tag, authorId: oldMessage.author.id, channel: oldMessage.channel.name, channelId: oldMessage.channel.id, timestamp: new Date().toISOString() }; // 写入JSON或数据库(逻辑同消息删除事件) });
内容的提问来源于stack exchange,提问作者Donutowiec
相关产品推荐
相关产品推荐

