如何在Discord交互中向指定频道发送嵌入日志消息?
实现Discord逮捕命令的日志记录功能
要在执行/arrest命令的频道外发送审核日志到指定频道,你可以按照以下方式修改代码:
关键修改点
- 新增日志频道的获取逻辑
- 创建包含完整审核信息的日志嵌入消息
- 添加日志消息的发送处理(含错误捕获)
修改后的完整代码
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder } = require('discord.js'); // 替换成你的日志频道ID const LOG_CHANNEL_ID = '你的日志频道ID'; module.exports = { data: new SlashCommandBuilder() .setName('arrest') .setDescription('puts the member to jail') .addUserOption(option => option .setName('target') .setDescription('The member to arrest') .setRequired(true)) .addStringOption(option => option .setName('reason') .setDescription('The reason for arrest')) .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers), async execute(interaction) { // 回复用户的逮捕提示嵌入 const userEmbed = new EmbedBuilder() .setTitle('ARRESTED!') .setDescription(`***${interaction.options.getUser('target').tag}*** *broke a leg. Oops.*`) .setColor(0xBD7A21) .setImage('https://eca.astrookai.repl.co/media/arrest.gif'); await interaction.reply({ embeds: [userEmbed] }); // 准备日志嵌入内容 const targetUser = interaction.options.getUser('target'); const reason = interaction.options.getString('reason') || '无理由'; const logEmbed = new EmbedBuilder() .setTitle('🔒 逮捕操作日志') .setColor(0xFF0000) .addFields( { name: '执行者', value: `${interaction.user.tag} (ID: ${interaction.user.id})`, inline: true }, { name: '目标用户', value: `${targetUser.tag} (ID: ${targetUser.id})`, inline: true }, { name: '原因', value: reason }, { name: '操作时间', value: `<t:${Math.floor(Date.now() / 1000)}:F>` } ) .setTimestamp(); try { // 获取日志频道并发送日志 const logChannel = await interaction.guild.channels.fetch(LOG_CHANNEL_ID); await logChannel.send({ embeds: [logEmbed] }); } catch (error) { // 捕获错误,避免命令崩溃,可选择通知执行者 console.error('发送日志失败:', error); await interaction.followUp({ content: '无法发送审核日志,请检查频道ID或机器人权限', ephemeral: true }); } }, };
注意事项
- 确保机器人在日志频道拥有发送消息和嵌入链接的权限
- 日志频道ID可以通过开启Discord开发者模式后右键频道复制获取
- 如果不想硬编码频道ID,可以使用环境变量(如
process.env.LOG_CHANNEL_ID)提升代码灵活性
内容的提问来源于stack exchange,提问作者AstrooKai.
相关产品推荐
相关产品推荐

