如何修复Discord.js调用Giphy API时的ts(1128)语法错误?
Fixing the ts(1128) Error in Your Discord.js + Giphy API Bot
Hey there! I can spot exactly what's throwing off your code—there are a couple of syntax mistakes in your second if block that's triggering the TypeScript Declaration or statement expected ts(1128) error. Let's work through fixing this step by step.
What's Causing the Error?
Looking at your code snippet, two key issues are breaking the syntax:
- You have an extra, unmatched
})at the end of thegiphy.trending().then()callback - There's an orphaned
filekeyword in the callback that serves no purpose (TypeScript flags this as an invalid, unrecognized statement) - Bonus: Your two
ifstatements will both trigger when someone sends${prefix}gif(since it still starts with the base prefix), leading to duplicate messages being sent
Corrected Code
Here's the fixed version with clear improvements:
client.on('message', message =>{ //console.log(message.content); if(message.content.startsWith(`${prefix}`)) { message.channel.send("oh yeah it's the prefix of the bot") } // Use else if to prevent overlapping logic else if(message.content.startsWith(`${prefix}gif`)) { giphy.trending("gifs", {}) .then((response) => { var totalResponses = response.data.length; var responseIndex = Math.floor((Math.random() * 10) +1) % totalResponses; var responseFinal = response.data[responseIndex]; message.channel.send("There you go!", { files: [responseFinal.images.fixed_height.url] }); // Removed the unused "file" line here }) // Removed the extra, unmatched }) here .catch(err => { // Optional: Add error handling for failed Giphy API calls console.error('Error fetching GIF:', err); message.channel.send('Oops, couldn\'t grab a GIF right now!'); }); } });
Key Fixes Explained:
- Removed the extra
}): This was breaking the code's structure, which is exactly what the TypeScript error was complaining about. - Deleted the
filestatement: It was an invalid, unused line that confused the compiler. - Switched to
else if: Now only one message will send when someone uses the GIF command, instead of both the prefix confirmation and GIF message. - Added optional error handling: The
.catch()block helps you debug if the Giphy API call fails (like missing API keys or network issues) and lets users know something went wrong.
Give this revised code a test run—your syntax error should vanish, and the GIF command should work as intended!
内容的提问来源于stack exchange,提问作者Raymond
相关产品推荐
相关产品推荐

