{"id":23146473,"url":"https://github.com/zeldafan0225/discordaichatbot","last_synced_at":"2025-04-04T13:23:19.664Z","repository":{"id":264688291,"uuid":"837882217","full_name":"ZeldaFan0225/DiscordAIChatBot","owner":"ZeldaFan0225","description":"A Discord Bot which can talk to any LLM API you want","archived":false,"fork":false,"pushed_at":"2025-02-07T21:19:22.000Z","size":106,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-07T22:26:41.428Z","etag":null,"topics":["ai","chatbot","chatgpt","claude","discord","discord-bot","discordbot","gemini","llm","openai"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ZeldaFan0225.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-04T10:24:30.000Z","updated_at":"2025-02-07T21:19:26.000Z","dependencies_parsed_at":"2024-11-25T19:39:56.265Z","dependency_job_id":"c86da4af-5edf-4ea3-b4ad-688e56eb4e28","html_url":"https://github.com/ZeldaFan0225/DiscordAIChatBot","commit_stats":null,"previous_names":["zeldafan0225/discordaichatbot"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeldaFan0225%2FDiscordAIChatBot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeldaFan0225%2FDiscordAIChatBot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeldaFan0225%2FDiscordAIChatBot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeldaFan0225%2FDiscordAIChatBot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZeldaFan0225","download_url":"https://codeload.github.com/ZeldaFan0225/DiscordAIChatBot/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247182952,"owners_count":20897492,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","chatbot","chatgpt","claude","discord","discord-bot","discordbot","gemini","llm","openai"],"created_at":"2024-12-17T16:29:27.042Z","updated_at":"2025-04-04T13:23:19.646Z","avatar_url":"https://github.com/ZeldaFan0225.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Discord AI Chat Bot 🤖\n\nA powerful, multi-provider Discord bot for AI interactions. Seamlessly integrate multiple AI models into your Discord server with support for text, images, and audio responses.\n\n## Features ✨\n\n- **Multiple AI Providers** \n  - OpenAI (e.g. GPT-4)\n  - Anthropic (e.g. Claude 3.5)\n  - Google AI (Gemini 1.5)\n  - Together AI (e.g. Llama 3.1)\n  - Groq\n  - Wolfram Alpha\n  - Hybrid connectors (e.g., Wolfram + OpenAI)\n\n- **Advanced Capabilities**\n  - Multi-modal support (text + images)\n  - Audio responses\n  - Message history tracking\n  - Content moderation\n  - Configurable system instructions\n  - Passive listening with custom triggers\n\n- **Discord Integration**\n  - Slash commands\n  - Context menus\n  - Rich interactions\n  - Guild and DM support\n  - Permission management\n  - User blacklisting\n\n## Prerequisites 📋\n\n- Node.js and npm\n- PostgreSQL database server\n- Discord bot token\n- API keys for desired AI providers\n\n## Discord Bot Setup 🤖\n\n1. Create a new Discord application at [Discord Developer Portal](https://discord.com/developers/applications)\n2. Create a bot user and get your bot token\n3. Enable required Privileged Gateway Intents:\n   - Message Content Intent\n   - Server Members Intent\n4. Generate an invite with the required Bot Permissions:\n   - Send Messages\n   - Send Messages in Threads\n   - Embed Links\n   - Attach Files\n   - Read Message History\n   - Use Slash Commands\n   - Add Reactions\n   - Use External Emojis\n\n## Quick Start 🚀\n\n1. **Clone the Repository**\n```bash\ngit clone https://github.com/ZeldaFan0225/DiscordAIChatBot\ncd DiscordAIChatBot\nnpm install\n```\n\n2. **Environment Setup**\nCreate a `.env` file:\n```env\nDISCORD_TOKEN=your_discord_bot_token\nDB_NAME=your_database_name\nDB_USERNAME=your_database_user\nDB_PASSWORD=your_database_password\nDB_IP=localhost\nDB_PORT=5432\nOPENAI_KEY=your_openai_key\nANTHROPIC_KEY=your_anthropic_key\nGOOGLE_AI_KEY=your_google_ai_key\nTOGETHERAI_KEY=your_together_ai_key\nGROQ_KEY=your_groq_key\nWOLFRAM_ALPHA_ID=your_wolfram_api_key\nGITHUB_PAT=your_github_personal_access_token\n```\n\n3. **Bot Configuration**\nCreate `config.json` from template:\n```json\n{\n    \"staff_roles\": [\"your_admin_role_id\"],\n    \"user_blacklist\": [],\n    \"hey\": {\n        \"enabled\": true,\n        \"ignoreNonMentionReplies\": true,\n        \"triggers\": {\n            \"hey gpt\": {\n                \"model\": \"gpt-4o-mini\",\n                \"systemInstruction\": \"default\",\n                \"previousMessagesContext\": 5\n            }\n        }\n    },\n    \"chat\": {\n        \"maxHistoryDepth\": 5\n    },\n    \"ask\": {\n        \"model\": \"gpt-4o-mini\",\n        \"systemInstruction\": \"default\",\n        \"initialPromptTemplate\": \"Take the following message:\\n\\n{{TARGET_MESSAGE_CONTENT}}\\n\\nWhat I need you to do:\\n{{USER_PROMPT}}\"\n    },\n    \"systemInstructions\": {\n        \"default\": \"You are a helpful, lightweight AI assistant\"\n    },\n    \"connectorConfigurations\": {\n        \"OpenAIConnector\": {\n            \"class\": \"classes/connectors/OpenAIConnector\",\n            \"connectionOptions\": {\n                \"url\": \"https://api.openai.com/v1/chat/completions\",\n                \"apiKey\": \"OPENAI_KEY\"\n            }\n        }\n    },\n    \"modelConfigurations\": {\n        \"gpt-4o-mini\": {\n            \"connector\": \"OpenAIConnector\",\n            \"displayName\": \"GPT-4o Mini\",\n            \"defaultSystemInstructionName\": \"default\",\n            \"systemInstructionAllowed\": true,\n            \"images\": {\n                \"supported\": true\n            },\n            \"generationOptions\": {\n                \"model\": \"gpt-4o-mini\"\n            }\n        }\n    }\n}\n```\n\n4. **Database Setup**\n- Create a PostgreSQL database\n- The required tables will be automatically created on first run\n- Tables created:\n  - `chat_messages`: Stores chat interactions\n  - `hey_messages`: Stores passive listening responses\n\n5. **Launch the Bot**\n```bash\n# For Node.js version 20 or below\nnpm run deploy\n\n# For Node.js version 22 and above\nnode --run deploy\n```\n\nNote: To disable validation of the config file when starting the process, use the `--disable-validation` flag:\n```bash\n# For Node.js version 20 or below\nnpm run deploy -- --disable-validation\n\n# For Node.js version 22 and above\nnode --run deploy --disable-validation\n```\n\n## Docker Deployment 🐳\n\nYou can deploy the bot using Docker with two different database configurations:\n\n### 1. Build the Docker Image\n```bash\n# Build the image\ndocker build -t discord-chatbot:latest .\n```\n\n### 2. Choose a Deployment Option\n\n#### Option A: Integrated Database\nThis option runs both the bot and PostgreSQL database in Docker containers:\n\n1. Navigate to the docker-compose directory:\n```bash\ncd docker-compose\n```\n\n2. Start the services:\n```bash\ndocker-compose -f with-database.yml up -d\n```\n\nThis setup:\n- Creates a Docker network for container communication\n- Runs PostgreSQL in a container with persistent volume\n- Automatically initializes the database using init.sql\n- Connects the bot to the containerized database\n\n#### Option B: Database on Host\nUse this option if you're running PostgreSQL on your host machine:\n\n1. Navigate to the docker-compose directory:\n```bash\ncd docker-compose\n```\n\n2. Start the service:\n```bash\ndocker-compose -f database-on-host.yml up -d\n```\n\nThis setup:\n- Runs only the bot in a container\n- Connects to PostgreSQL running on your host machine\n- Uses host.docker.internal to communicate with the host's database\n\n### Configuration\nFor both options:\n- Ensure your .env file is present in the project root\n- Make sure config.json is present in the project root\n- The Docker setup will automatically mount these files into the container\n\n### Stopping the Services\n```bash\n# For either option, in the docker-compose directory:\ndocker-compose -f \u003cfilename\u003e.yml down\n\n# To also remove the database volume (Option A only):\ndocker-compose -f with-database.yml down -v\n```\n\n## Development Setup 🛠️\n\n1. **TypeScript Configuration**\nThe project uses TypeScript. A `tsconfig.json` is provided with recommended settings.\n\n2. **Building**\n- The `deploy` script handles TypeScript compilation and bot startup\n- Source files are compiled to the `dist` directory\n\n3. **Dependencies**\n- discord.js: ^14.16.1\n- @discordjs/builders, formatters, rest, util\n- pg: ^8.12.0 (PostgreSQL client)\n- TypeScript development dependencies\n\n## Usage 💡\n\n### Chat Command\nUse `/chat` with these options:\n- `message`: Your message to the AI\n- `model`: Select AI model (autocomplete available)\n- `system_instruction`: Optional system prompt\n- `image`: Optional image attachment\n\n### Hey Triggers\nConfigure passive listening triggers in config.json:\n```json\n\"hey\": {\n    \"enabled\": true,\n    \"triggers\": {\n        \"hey gpt\": {\n            \"model\": \"gpt-4o-mini\",\n            \"systemInstruction\": \"default\",\n            \"previousMessagesContext\": 5\n        }\n    }\n}\n```\n\n### Adding AI Providers\n1. Add API key to `.env`\n2. Configure connector in `config.json`\n3. Add desired models in `modelConfigurations`\n## Creating Custom Connectors 🔌\n\nYou can create custom connectors to integrate additional AI providers. Here's how:\n\n### 1. Create Your Connector Class\n\nCreate a new file in `src/classes/connectors/` (e.g., `CustomConnector.ts`):\n\n```typescript\nimport BaseConnector, {\n    ChatCompletionResult,\n    ChatMessage,\n    GenerationOptions\n} from \"./BaseConnector\";\n\nexport default class CustomConnector extends BaseConnector {\n    override async requestChatCompletion(\n        messages: ChatMessage[],\n        generationOptions: GenerationOptions,\n        user_id?: string\n    ): Promise\u003cChatCompletionResult\u003e {\n        // 1. Convert messages to your AI provider's format\n        const formattedMessages = this.convertMessages(messages);\n\n        // 2. Send request to AI provider\n        const response = await this.sendRequest({\n            messages: formattedMessages,\n            ...generationOptions\n        });\n\n        // 3. Convert response to standard format\n        return {\n            resultMessage: {\n                role: \"assistant\",\n                content: response.text,\n                // Optional: audio_data_string for audio responses\n                // Optional: attachments for image URLs\n            }\n        };\n    }\n\n    private async sendRequest(payload: any) {\n        const response = await fetch(this.connectionOptions.url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n                \"Authorization\": `Bearer ${process.env[this.connectionOptions.apiKey]}`\n            },\n            body: JSON.stringify(payload)\n        });\n\n        const data = await response.json();\n        if (data.error) throw new Error(\"API Error\", {cause: data});\n        return data;\n    }\n\n    private convertMessages(messages: ChatMessage[]) {\n        // Convert messages to your AI provider's format\n        return messages.map(m =\u003e ({\n            // Your conversion logic here\n        }));\n    }\n}\n```\n\n### 2. Implement Required Interfaces\n\nYour messages must conform to these interfaces:\n\n```typescript\ninterface ChatMessage {\n    role: \"user\" | \"assistant\" | \"system\";\n    content: string;\n    name?: string;\n    attachments?: string[];\n    audio_data_string?: string;\n}\n\ninterface ChatCompletionResult {\n    resultMessage: ChatMessage;\n}\n```\n\n### 3. Configure Your Connector\n\nAdd your connector configuration to `config.json`:\n\n```json\n{\n    \"connectorConfigurations\": {\n        \"CustomConnector\": {\n            \"class\": \"classes/connectors/CustomConnector\",\n            \"connectionOptions\": {\n                \"url\": \"https://api.your-ai-provider.com/v1/chat\",\n                \"apiKey\": \"YOUR_API_KEY_ENV_VAR\"\n            }\n        }\n    }\n}\n```\n\n### 4. Add Model Configuration\n\nConfigure models that use your connector:\n\n```json\n{\n    \"modelConfigurations\": {\n        \"custom-model\": {\n            \"connector\": \"CustomConnector\",\n            \"displayName\": \"Custom AI Model\",\n            \"defaultSystemInstructionName\": \"default\",\n            \"systemInstructionAllowed\": true,\n            \"images\": {\n                \"supported\": false\n            },\n            \"generationOptions\": {\n                \"model\": \"your-model-name\"\n            }\n        }\n    }\n}\n```\n\n### Key Considerations\n\n1. **Error Handling**\n   - Implement proper error handling for API responses\n   - Throw meaningful errors that can be caught by the bot\n\n2. **Message Format**\n   - Implement proper conversion between the bot's message format and your AI provider's format\n   - Handle system instructions if supported\n   - Handle attachments if supported\n\n3. **Authentication**\n   - Use environment variables for API keys\n   - Implement proper authentication headers\n\n4. **Optional Features**\n   - Image support: Handle attachments array in messages\n   - Audio support: Provide audio_data_string in responses\n   - Moderation: Implement content filtering if needed\n\n### Example Features\n\nYour connector can implement additional features:\n\n```typescript\n// Content moderation\nprivate async moderateContent(message: string): Promise\u003cboolean\u003e {\n    // Your moderation logic\n    return true;\n}\n\n// Image processing\nprivate handleAttachments(attachments: string[]) {\n    // Your attachment handling logic\n}\n\n// Audio response handling\nprivate formatAudioResponse(audioData: any) {\n    return `data:audio/mp3;base64,${audioData}`;\n}\n```\n\n## Architecture 🏗️\n\n- **Connector System**: Modular design for easy AI provider integration\n- **Database**: PostgreSQL for message history and threading\n- **Discord Integration**: Full support for Discord's interaction features\n- **Configuration**: Flexible setup for providers, models, and permissions\n\n## Error Handling 🔧\n\nCommon issues and solutions:\n- Database connection errors: Check PostgreSQL credentials and server status\n- Discord API errors: Verify bot token and permissions\n- AI provider errors: Validate API keys and model configurations\n- TypeScript compilation errors: Check for syntax issues in source files\n\n## License 📄\n\nThis project is licensed under the GNU Affero General Public License v3.0 with additional terms:\n- No commercial use without explicit permission\n- Attribution required\n- Modified versions must share source code\n\nSee the [LICENSE](LICENSE) file for details.\n\n## Acknowledgments 🙏\n\n- Original creator: [ZeldaFan0225](https://github.com/ZeldaFan0225)\n- All AI providers for their APIs\n- Discord.js team for their excellent library\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzeldafan0225%2Fdiscordaichatbot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzeldafan0225%2Fdiscordaichatbot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzeldafan0225%2Fdiscordaichatbot/lists"}