如何在discord.js中实现基于关键词的Waifu搜索命令?
Hey there! Let's build that waifu search command you need. I'll walk you through the whole process, from setting up the data to creating the polished embed response.
1. Prepare Your Waifu Data
First, let's get your waifu JSON ready. You can save it as a separate file (like waifus.json) with the structure you provided:
{ "waifuID": { "1": { "names": "Megumin", "img_url": "https://s4.anilist.co/file/anilistcdn/character/large/b89361-xH1t0q5WeAN8.png", "claims": "#1" }, "2": { "names": "Mai Sakurajima", "img_url": "https://s4.anilist.co/file/anilistcdn/character/large/b127222-IY5iDRuXLY8i.png", "claims": "#2" }, "3": { "names": "Zero Two", "img_url": "https://s4.anilist.co/file/anilistcdn/character/large/b124381-pkTKi6HHNuVR.png", "claims": "#3" } } }
Alternatively, you can define the object directly in your code—whichever fits your workflow better.
2. Build the Command Code
Here's the complete, commented code for your !search command, using discord.js v14 (the latest stable version). I've added little touches to make it user-friendly:
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js'); // Import your waifu data (adjust the file path if needed) const waifuData = require('./waifus.json'); // Initialize the Discord client const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent // Required to read user message content ] }); // Triggered when the bot finishes logging in client.on('ready', () => { console.log(`Logged in as ${client.user.tag}—ready to search waifus!`); }); // Handle incoming messages client.on('messageCreate', async (message) => { // Ignore messages from other bots to avoid loops if (message.author.bot) return; // Check if the message starts with our !search command if (!message.content.startsWith('!search')) return; // Extract the search query (remove the !search prefix and trim extra spaces) const searchQuery = message.content.slice(7).trim(); // Remind the user to enter a waifu name if they didn't if (!searchQuery) { return message.reply('Hey, you need to tell me which waifu to search! Try `!search Zero Two`'); } // Look for a matching waifu in our data let foundWaifu = null; // Loop through all waifu entries for (const waifu of Object.values(waifuData.waifuID)) { // Case-insensitive match so users don't stress about capitalization if (waifu.names.toLowerCase() === searchQuery.toLowerCase()) { foundWaifu = waifu; break; // Stop searching once we find a match } } // If we found a match, build and send the embed if (foundWaifu) { const waifuEmbed = new EmbedBuilder() .setTitle(foundWaifu.names) .setImage(foundWaifu.img_url) .setColor('#FF69B4') // A cute pink hue for waifu vibes 😊 .addFields({ name: 'Claim Number', value: foundWaifu.claims, inline: true }); return message.channel.send({ embeds: [waifuEmbed] }); } else { // Let the user know if their search didn't turn up anything return message.reply(`Sorry, I couldn't find a waifu named **${searchQuery}**!`); } }); // Log in to Discord with your bot's token (replace with your actual token) client.login('YOUR_BOT_TOKEN_HERE');
3. Key Tips & Customizations
- Intent Setup: Don't forget to enable the
Message Content Intentin your Discord Developer Portal (under Bot > Privileged Gateway Intents)—without it, the bot can't read message content. - v13 Compatibility: If you're using discord.js v13, swap
EmbedBuilderforMessageEmbedand send the embed like this:message.channel.send(waifuEmbed)(no need for theembedsarray). - Fuzzy Matching: Want to allow partial matches (e.g.,
!search Zerofinds Zero Two)? Replace the equality check withwaifu.names.toLowerCase().includes(searchQuery.toLowerCase()). - Embed Tweaks: You can add descriptions, change the color, or add more fields to the embed—check the discord.js docs for all available customization options.
Example Output
When a user sends !search Zero Two, the bot will send an embed that looks like this:
Zero Two
[Image of Zero Two]
Claim Number: #3
内容的提问来源于stack exchange,提问作者HK420

