Discord机器人封禁命令报错求助:Lexical declaration语法错误
Hey there! Let's get that ban command working properly—first bots can be tricky, but this is a straightforward fix.
What's Causing the Error?
The SyntaxError: Lexical declaration cannot appear in a single-statement context comes from how you've structured your if statement. When you write:
if (message.member.hasPermission("BAN_MEMBERS")) let User = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
You're trying to declare a variable (let User) directly after an if statement without wrapping the code in curly braces {}. JavaScript doesn't allow block-scoped declarations (let/const) in a single-line if context like this—you need to explicitly define the block with braces.
Corrected Code
Here's the fixed version of your command, with additional improvements to handle edge cases (like letting the user know if they don't have permission to ban):
module.exports = { name: "ban", aliases: ["banuser"], execute(client, message, args) { // Check if the command user has ban permissions if (!message.member.hasPermission("BAN_MEMBERS")) { return message.reply("Nincs jogosultságod felhasználókat kitiltani!"); } // Get the target user (either via mention or ID) let User = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]); if (!User) { return message.channel.send("Meg kell nevezned egy személyt!"); } // Prevent banning users with ban permissions if (User.hasPermission("BAN_MEMBERS")) { return message.reply("Nem tudtam kitiltani a felhasználót—ő is rendelkezik kitiltási jogosultsággal!"); } // Handle ban reason let banReason = args.join(" ").slice(22); if (!banReason) banReason = "None"; // Execute the ban with success/error feedback User.ban({ reason: banReason }) .then(() => { message.channel.send(`Sikeresen kitiltottam ${User.user.tag}-ot oka: ${banReason}`); }) .catch(err => { message.reply("Valami hiba történt a kitiltás során!"); console.error(err); }); } };
Key Changes Made:
- Wrapped all
ifstatement logic in curly braces{}to fix the syntax error - Added a check to notify the user if they don't have permission to use the ban command
- Added success/error feedback so you know when the ban works (or fails)
- Fixed a small typo in your error message for clarity
Extra Note for Newer Discord.js Versions:
If you're using Discord.js v12 or higher, message.guild.members.get() is deprecated. Replace it with message.guild.members.fetch() instead, and add async to your execute function to use await:
async execute(client, message, args) { // ... let User = message.guild.member(message.mentions.users.first()) || await message.guild.members.fetch(args[0]); // ... }
内容的提问来源于stack exchange,提问作者Marcell2810

