You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js含空格用户ID解封失败问题求助

Fixing Your Discord Unban Command for Users with Spaces in Their ID/Username

Hey there! Let's break down why your command is throwing that "Please specify a user ID" error and fix it up.

The Core Issues

Your current code has two key problems that are stopping it from working for users with spaces:

  1. Incorrect parameter splitting: Using split(/ +/g) splits your input by spaces, so if a user's ID/username has a space (like John Doe), args[1] only grabs the first part (John) instead of the full identifier.
  2. Trying to fetch banned users from cache: Banned users aren't part of the server's member cache, so message.guild.members.cache.get() will never find them—even if you had the full ID.

The Fixed Code

Here's a revised version that addresses both issues:

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', message => {
  if (message.content.startsWith('!unban')) {
    // Grab everything after the !unban command (preserves spaces)
    const userIdentifier = message.content.slice('!unban'.length).trim();
    
    if (!userIdentifier) {
      return message.channel.send('Please specify a user ID or username');
    }

    // Use guild.unban directly (no cache needed—Discord handles the lookup)
    message.guild.members.unban(userIdentifier)
      .then(unbannedUser => message.channel.send(`Successfully unbanned ${unbannedUser.tag}!`))
      .catch(error => {
        console.error('Unban error:', error);
        message.channel.send(`Failed to unban: ${error.message}`);
      });
  }
});

Key Changes Explained

  • Preserving full identifiers: message.content.slice('!unban'.length).trim() takes all text after your command, so spaces in the user's ID/username stay intact.
  • Direct unban call: message.guild.members.unban() communicates directly with Discord's API to find and unban the user—no need to rely on local cache (which doesn't include banned accounts).
  • Error handling: The .catch() block will tell you exactly why the unban failed (e.g., invalid ID, missing permissions, or the user wasn't banned), which helps debug those 400/404 errors you were seeing.

Quick Notes

  • Make sure your bot has the BAN_MEMBERS permission enabled in the server settings.
  • If you're using a user's numeric ID (which Discord's actual user IDs are—they don't have spaces), this code still works perfectly. The fix just accommodates usernames/spaced identifiers too.

内容的提问来源于stack exchange,提问作者Unknown people

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:24:09