Discord审计日志无法获取频道移动事件,如何记录操作执行人?
问题原因与解决方案
1. 大量channelUpdate事件触发原因
- Discord调整频道位置时,若涉及分类移动、跨分类移动频道,会批量更新所有受影响分类下全部频道的
rawPosition值,因此会触发批量的channelUpdate事件,属于官方正常逻辑。
2. 审计日志拉取不到的原因
- 审计日志类型参数匹配错误:频道位置变更属于
CHANNEL_UPDATE类型,对应discord.js v14+的枚举值为AuditLogEvent.ChannelUpdate,数值为11。此前拉取时没有过滤变更字段,也没有预留审计日志生成的延迟,导致匹配不到对应记录。 - 需确认机器人已经被授予
VIEW_AUDIT_LOG(查看审计日志)权限,无权限时会拉取不到对应记录。
3. 可正常获取操作人的实现代码
const Discord = require('discord.js'); const { AuditLogEvent } = require('discord.js'); // 引入审计日志事件枚举 const fs = require('fs'); // 建议把模块引入放在代码顶部 const { prefix, token, witaitoken , guildID, DBUser, DBPass } = require('./config.json'); const client = new Discord.Client({ shards: 'auto', intents: [ Discord.GatewayIntentBits.Guilds, // 必须开启服务器相关意图 Discord.GatewayIntentBits.GuildMessages ] }); client.on('ready', async () => { console.log(`Logged in as ${client.user.tag}!`); client.user.setActivity(`Star Citizen`, { type: Discord.ActivityType.Playing }); }); client.on('channelUpdate', async (oldChannel, newChannel) => { if (oldChannel.rawPosition === newChannel.rawPosition) return; // 加1秒延迟,等待审计日志生成 setTimeout(async () => { try { // 拉取CHANNEL_UPDATE类型的审计日志 const auditLogs = await oldChannel.guild.fetchAuditLogs({ type: AuditLogEvent.ChannelUpdate, limit: 5 }); // 过滤出当前频道变更position字段的日志 const positionChangeLog = auditLogs.entries.find(entry => { return entry.changes?.some(change => change.key === 'position' && entry.targetId === newChannel.id); }); if (!positionChangeLog) return; // 操作人信息存储在positionChangeLog.executor对象中 const logContent = `频道${newChannel.name}(${newChannel.id})位置变更,操作人:${positionChangeLog.executor.tag}(${positionChangeLog.executor.id}),时间:${new Date().toLocaleString()}\n`; fs.appendFile('audit.txt', logContent, err => { if (err) console.error('写入日志失败', err); }); } catch (err) { console.error('拉取审计日志失败', err); } }, 1000); }); client.login(token); client.on("error", (e) => console.error(e)); client.on("warn", (e) => console.warn(e)); client.on("debug", (e) => console.info(e));
注意事项
- 若使用discord.js v13及更早版本,审计日志枚举和意图的声明方式会有差异,对应调整参数即可。
- 单次批量移动多个频道时,会生成多条审计日志,按上述过滤逻辑可分别匹配到每个频道的操作人。
内容的提问来源于stack exchange,提问作者Garoo
相关产品推荐
相关产品推荐

