UNPKG

aifordiscord-api

Version:

An advanced npm package for Discord bots providing AI-enhanced random content, memes, jokes, and utilities with comprehensive documentation.

534 lines (423 loc) 13.1 kB
# aifordiscord-api An advanced npm package for Discord bots providing AI-enhanced random content, memes, jokes, and utilities with comprehensive documentation. [![npm version](https://badge.fury.io/js/aifordiscord-api.svg)](https://www.npmjs.com/package/aifordiscord-api) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## 🚀 Features - **AI-Enhanced Content**: Powered by OpenAI for improved jokes, advice, facts, and custom content - **Comprehensive API**: 15+ content types including memes, jokes, advice, anime images, facts, quotes, animal images, trivia, and more - **Built-in Caching**: Intelligent caching system to reduce API calls - **Rate Limiting**: Built-in rate limiting to prevent abuse - **TypeScript Support**: Full TypeScript definitions included - **Easy Integration**: Simple Discord.js integration - **Error Handling**: Robust error handling and validation - **Customizable**: Flexible configuration options - **GitHub Integration**: Fetch user information from GitHub - **Trivia Questions**: Multiple choice questions with difficulty levels - **Animal Images**: Random dog and cat images - **Inspirational Content**: Quotes, compliments, and affirmations ## 📦 Installation ```bash npm install aifordiscord-api ``` ## 🚀 Quick Start ```javascript const { AIForDiscord } = require('aifordiscord-api'); // Basic usage (no AI features) const random = new AIForDiscord(); // With AI enhancement (requires OpenAI API key) const random = new AIForDiscord({ openaiApiKey: 'your-openai-key', enableAI: true, enableCache: true }); // Get a meme const meme = await random.getMeme(); console.log(meme.title, meme.url); // Get advice const advice = await random.getAdvice(); console.log(advice.advice); ``` ## 📚 API Reference ### Basic Content Methods #### `getMeme()` Returns a random meme from Reddit with metadata. ```javascript const data = await random.getMeme(); message.channel.send({ embeds: [{ title: data.title, image: { url: data.url }, url: data.postLink, footer: { text: `r/${data.subreddit} • ${data.ups} upvotes` } }] }); ``` **Returns:** `MemeResponse` ```typescript { title: string; url: string; postLink: string; subreddit: string; author: string; nsfw: boolean; spoiler: boolean; ups: number; } ``` #### `getAdvice()` Provides random advice with optional AI enhancement. ```javascript const data = await random.getAdvice(); message.channel.send(`💡 **Advice:** ${data.advice}`); ``` **Returns:** `AdviceResponse` ```typescript { advice: string; slip_id: number; } ``` #### `getNeko()` Provides a random neko (cat girl) image. ```javascript const data = await random.getNeko(); message.channel.send({ embeds: [{ title: '🐱 Random Neko', image: { url: data.url } }] }); ``` **Returns:** `NekoResponse` ```typescript { url: string; } ``` #### `getRandomJoke()` Provides a random funny joke with optional AI enhancement. ```javascript const data = await random.getRandomJoke(); if (data.type === 'twopart') { message.channel.send(`${data.setup}\n\n||${data.delivery}||`); } else { message.channel.send(data.joke); } ``` **Returns:** `JokeResponse` ```typescript { setup?: string; delivery?: string; joke?: string; category: string; type: string; safe: boolean; id: number; } ``` #### `getNameJoke(firstName, lastName?)` Provides a random funny joke related to the given name. ```javascript const data = await random.getNameJoke("John", "Doe"); message.channel.send(`😄 ${data.joke}`); ``` **Parameters:** - `firstName` (string): Required first name - `lastName` (string, optional): Last name **Returns:** `NameJokeResponse` ```typescript { joke: string; name: string; enhanced: boolean; } ``` #### `getAnimeImgURL(type)` Provides a random anime image URL based on action type. ```javascript const data = await random.getAnimeImgURL("hug"); message.channel.send({ embeds: [{ title: `🤗 ${data.type.toUpperCase()}`, image: { url: data.url } }] }); ``` **Parameters:** - `type` (string): Action type - "pat", "hug", "waifu", "cry", "kiss", "slap", "smug", "punch" **Returns:** `AnimeImageResponse` ```typescript { url: string; type: string; } ``` #### `getFact()` Provides a random fact with optional AI enhancement. ```javascript const data = await random.getFact(); message.channel.send(`🧠 **Did you know?**\n${data.fact}`); ``` **Returns:** `FactResponse` ```typescript { fact: string; source?: string; enhanced: boolean; } ``` #### `getNPM(packageName)` Provides information about an NPM package. ```javascript const data = await random.getNPM("discord.js"); message.channel.send({ embeds: [{ title: `📦 ${data.name}`, description: data.description, fields: [ { name: 'Version', value: data.version, inline: true }, { name: 'Author', value: data.author || 'Unknown', inline: true } ] }] }); ``` #### `getQuote()` Provides a random inspirational quote. ```javascript const data = await random.getQuote(); message.channel.send(`💭 **"${data.quote}"** - *${data.author}*`); ``` #### `getDogImage()` Provides a random dog image. ```javascript const data = await random.getDogImage(); message.channel.send({ embeds: [{ title: '🐕 Random Dog', image: { url: data.url } }] }); ``` #### `getCatImage()` Provides a random cat image. ```javascript const data = await random.getCatImage(); message.channel.send({ embeds: [{ title: '🐱 Random Cat', image: { url: data.url } }] }); ``` #### `getTrivia(category?, difficulty?)` Provides a trivia question with multiple choice answers. ```javascript const data = await random.getTrivia(); const answers = data.answers.map((answer, index) => `${index + 1}. ${answer}`).join('\n'); message.channel.send(`🧠 **Trivia Time!**\n\n${data.question}\n\n${answers}`); ``` #### `getDadJoke()` Provides a random dad joke. ```javascript const data = await random.getDadJoke(); message.channel.send(`👨 **Dad Joke:** ${data.joke}`); ``` #### `getChuckNorrisJoke()` Provides a random Chuck Norris joke. ```javascript const data = await random.getChuckNorrisJoke(); message.channel.send(`💪 **Chuck Norris:** ${data.joke}`); ``` #### `getCompliment()` Provides a random compliment. ```javascript const data = await random.getCompliment(); message.channel.send(`😊 ${data.compliment}`); ``` #### `getAffirmation()` Provides a positive affirmation. ```javascript const data = await random.getAffirmation(); message.channel.send(`✨ ${data.affirmation}`); ``` #### `getGitHubUser(username)` Provides information about a GitHub user. ```javascript const data = await random.getGitHubUser("octocat"); message.channel.send({ embeds: [{ title: `👨‍💻 ${data.name || data.username}`, description: data.bio, thumbnail: { url: data.avatarUrl }, fields: [ { name: 'Followers', value: data.followers.toString(), inline: true }, { name: 'Following', value: data.following.toString(), inline: true }, { name: 'Public Repos', value: data.publicRepos.toString(), inline: true } ], url: data.htmlUrl }] }); ``` ### AI-Enhanced Methods #### `generateCustomJoke(topic)` 🤖 Generates a custom joke using AI on a specific topic (requires OpenAI API key). ```javascript const joke = await random.generateCustomJoke("programming"); message.channel.send(`🤖 ${joke}`); ``` **Parameters:** - `topic` (string): Topic for the joke **Returns:** `string` - AI-generated joke ### Utility Methods #### `clearCache()` Clears the internal cache. ```javascript random.clearCache(); ``` #### `getConfig()` Returns current configuration. ```javascript const config = random.getConfig(); console.log('AI enabled:', config.enableAI); ``` #### `isAIEnabled()` Checks if AI features are enabled and available. ```javascript if (random.isAIEnabled()) { console.log('AI features are ready!'); } ``` ## ⚙️ Configuration Options ```javascript const random = new AIForDiscord({ openaiApiKey: 'your-openai-key', // OpenAI API key for AI features enableCache: true, // Enable caching (default: true) cacheTimeout: 300000, // Cache timeout in ms (default: 5 minutes) enableRateLimit: true, // Enable rate limiting (default: true) rateLimitRequests: 100, // Max requests per window (default: 100) rateLimitWindow: 60000, // Rate limit window in ms (default: 1 minute) enableAI: true, // Enable AI enhancement (default: true) contentFilter: true // Enable content filtering (default: true) }); ``` ## 🤖 AI Features When an OpenAI API key is provided, the package offers enhanced content: - **Enhanced Jokes**: Makes jokes funnier and more engaging - **Enhanced Advice**: Provides more thoughtful and actionable advice - **Enhanced Facts**: Makes facts more interesting while maintaining accuracy - **Custom Jokes**: Generate completely custom jokes on any topic - **Name Personalization**: Better integration of names into jokes ## 📁 Complete Examples ### Basic Discord Bot ```javascript const { Client, GatewayIntentBits } = require('discord.js'); const { AIForDiscord } = require('aifordiscord-api'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }); const random = new AIForDiscord({ enableCache: true, enableAI: false // Set to true if you have OpenAI API key }); client.on('messageCreate', async (message) => { if (message.author.bot || !message.content.startsWith('!')) return; const command = message.content.slice(1).toLowerCase(); try { switch (command) { case 'meme': const meme = await random.getMeme(); message.reply(meme.url); break; case 'advice': const advice = await random.getAdvice(); message.reply(advice.advice); break; case 'neko': const neko = await random.getNeko(); message.reply(neko.url); break; case 'joke': const joke = await random.getRandomJoke(); const jokeText = joke.type === 'twopart' ? `${joke.setup}\n\n${joke.delivery}` : joke.joke; message.reply(jokeText); break; case 'fact': const fact = await random.getFact(); message.reply(fact.fact); break; } } catch (error) { message.reply('Something went wrong! Please try again.'); } }); client.login('YOUR_BOT_TOKEN'); ``` ### Advanced Bot with AI ```javascript const { AIForDiscord } = require('aifordiscord-api'); const random = new AIForDiscord({ openaiApiKey: process.env.OPENAI_API_KEY, enableAI: true, enableCache: true }); // Custom joke generation const customJoke = await random.generateCustomJoke("programming"); console.log('Custom joke:', customJoke); // Enhanced name joke const nameJoke = await random.getNameJoke("Alice", "Johnson"); console.log('Name joke:', nameJoke.joke, '(Enhanced:', nameJoke.enhanced, ')'); ``` ## 🔧 Error Handling The package includes comprehensive error handling: ```javascript try { const meme = await random.getMeme(); console.log(meme); } catch (error) { if (error.message.includes('Rate limit exceeded')) { console.log('Please wait before making another request'); } else if (error.message.includes('not found')) { console.log('Content not available'); } else { console.log('Network or API error:', error.message); } } ``` ## 📊 Performance Features - **Smart Caching**: Reduces API calls with intelligent caching - **Rate Limiting**: Prevents API abuse with configurable limits - **Error Recovery**: Graceful fallbacks when AI enhancement fails - **TypeScript Support**: Full type definitions for better development experience ## 🆚 Comparison with similar packages | Feature | aifordiscord-api | others | |---------|-----------------|---------| | AI Enhancement | ✅ | ❌ | | Caching System | ✅ | ❌ | | Rate Limiting | ✅ | ❌ | | TypeScript Support | ✅ | ❌ | | Custom Joke Generation | ✅ | ❌ | | Comprehensive Error Handling | ✅ | ❌ | | NPM Package Info | ✅ | ❌ | ## 🤝 Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## 📄 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## 🙏 Acknowledgments - OpenAI for AI enhancement capabilities - Various API providers for content sources - Discord.js community for inspiration ## 📞 Support If you encounter any issues or have questions: 1. Check the [examples](./examples/) directory 2. Review this documentation 3. Create an issue on GitHub --- **Made with ❤️ for the Discord bot community**