如何避免Discord机器人因命令输入错误触发报错?
Hey there! The issue you're hitting happens because when a user inputs a skin name that doesn't exist (or has a typo), the find() method returns undefined—and trying to access .name, .tier, etc., on undefined throws that frustrating error. Let's fix this step by step.
Step 1: Cache the Find Result (and Cut Redundant Work)
Right now you’re calling Object.values(info.skins).find() four times for the same query—that’s unnecessary and inefficient. Instead, run the search once and store the result in a variable. This lets us check if a match exists before trying to access any properties.
Step 2: Add a Guard Clause for Missing Skins
After getting the search result, if it’s undefined, send a friendly message to the user and exit the function immediately. This stops the code from trying to access properties on a non-existent object.
Modified Working Code
Here’s your updated code with these fixes:
if (msg.content.startsWith('LB skin')) { if (msg.author.bot) return; const text = msg.content.slice(8).trim(); // Added trim() to handle accidental extra spaces if (!text) return msg.reply('Please give me a valid skin!'); const info = database; // Your JSON file // Run the search ONCE and store the matched skin object const matchedSkin = Object.values(info.skins).find( (value) => value.name.toLowerCase() === text.toLowerCase() ); // Guard clause: if no skin is found, reply and exit early if (!matchedSkin) { return msg.reply(`Sorry, I couldn't find a skin named "${text}". Double-check the spelling!`); } // Safely extract properties from the matched skin object using destructuring const { name: Name, tier: Tier, weapons: Weapons, event: Event, game_version: Game_version } = matchedSkin; const embed = new Discord.MessageEmbed() .setColor('#0099ff') .setTitle('Leak info:') .setAuthor('LeakBot#8631', 'https://cdn.discordapp.com/avatars/779616585001861120/d8c6dd64ac92ec5ee5a1a893578722c3.png?size=256', 'https://www.paypal.com/paypalme/LeakBot') .setDescription(text) .addFields( { name: 'Name:', value: Name , inline: true }, { name: 'Tier:', value: Tier, inline: true }, { name: 'Weapons:', value: Weapons, inline: true }, { name: 'Event:', value: Event, inline: true }, { name: 'Game version:', value: Game_version, inline: true }, { name: '\u200B', value: '\u200B', inline: true }, ) .setTimestamp() .setFooter('Created by pitched_mobile', 'https://cdn.discordapp.com/icons/539804475150434314/e22de33df46a9022b41817bfb732c9b3.jpg'); msg.channel.send(embed); }
Bonus: Upgrade User Experience (Optional)
If you want to go the extra mile, you could add fuzzy search to suggest similar skin names when there’s no exact match. For example, using a lightweight library like fuse.js to find close matches and display them to the user—this helps users correct typos without guessing. But the code above will solve your immediate error problem perfectly.
内容的提问来源于stack exchange,提问作者pitched mobile

