Discord.js V12如何为指定角色锁定所有频道?代码报错求助
Fixing the "INVALID_TYPE" Permission Overwrites Error in Discord.js
Let's break down what's causing your error and fix it step by step:
Why You're Seeing This Error
The TypeError [INVALID_TYPE] pops up for a few key reasons in your code:
- You're trying to iterate over channels directly via
message.guild.channels(in newer Discord.js versions, this is a manager object, not the channel list itself) - You aren't handling cases where the "Mute" role might not exist (which would pass an invalid ID to the permission overwrite)
- You're using
forEachwith an asynchronous function, which doesn't wait for permission changes to complete and can lead to unexpected behavior
Fixed Code
client.on('message', async message => { if (message.content.startsWith(prefix + "modrek")) { // First, locate the Mute role and handle if it's missing const muteRole = message.guild.roles.cache.find(role => role.name === "Mute"); if (!muteRole) { return message.reply("Couldn't find a role named 'Mute'! Please create it first."); } // Filter to only target text channels (since we're modifying message permissions) const textChannels = message.guild.channels.cache.filter(ch => ch.type === "text"); // Use Promise.all to wait for all permission updates to finish await Promise.all(textChannels.map(async channel => { await channel.overwritePermissions([ { id: muteRole.id, deny: ['SEND_MESSAGES'], }, ], 'Locked channel for Mute role enforcement'); })); message.reply("Successfully locked all text channels for the Mute role!"); } });
Key Improvements Made
- Role existence check: Prevents crashes if the "Mute" role doesn't exist, and gives a clear error message.
- Proper channel iteration: Uses
channels.cacheto access the actual list of channels (required in modern Discord.js versions). - Async safety:
Promise.all+mapensures the bot waits for every channel's permission change to complete before sending a success notification. - Targeted channel filtering: Focuses only on text channels, since
SEND_MESSAGESpermissions don't apply to voice or category channels.
Quick Note for Discord.js v13+
If you're using v13 or later, the channel type string is GUILD_TEXT instead of text—just update that filter line to match:
const textChannels = message.guild.channels.cache.filter(ch => ch.type === "GUILD_TEXT");
Also, make sure your bot has the Manage Channels permission enabled in the server, otherwise it won't be able to modify channel permissions.
内容的提问来源于stack exchange,提问作者Medraj




