A 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.
-
Multiple AI Providers
- OpenAI (e.g. GPT-4)
- Anthropic (e.g. Claude 3.5)
- Google AI (Gemini 1.5)
- Together AI (e.g. Llama 3.1)
- Groq
- Wolfram Alpha
- Hybrid connectors (e.g., Wolfram + OpenAI)
-
Advanced Capabilities
- Multi-modal support (text + images)
- Audio responses
- Message history tracking
- Content moderation
- Configurable system instructions
- Passive listening with custom triggers
-
Discord Integration
- Slash commands
- Context menus
- Rich interactions
- Guild and DM support
- Permission management
- User blacklisting
- Node.js and npm
- PostgreSQL database server
- Discord bot token
- API keys for desired AI providers
- Create a new Discord application at Discord Developer Portal
- Create a bot user and get your bot token
- Enable required Privileged Gateway Intents:
- Message Content Intent
- Server Members Intent
- Generate an invite with the required Bot Permissions:
- Send Messages
- Send Messages in Threads
- Embed Links
- Attach Files
- Read Message History
- Use Slash Commands
- Add Reactions
- Use External Emojis
- Clone the Repository
git clone https://github.com/ZeldaFan0225/DiscordAIChatBot
cd DiscordAIChatBot
npm install-
Environment Setup Create a
.envfrom templatetemplate.env -
Bot Configuration Create
config.jsonfrom templatetemplate.config.json -
Database Setup
- Create a PostgreSQL database
- The required tables will be automatically created on first run
- Tables created:
chat_messages: Stores chat interactionshey_messages: Stores passive listening responses
- Launch the Bot
# For Node.js version 20 or below
npm run deploy
# For Node.js version 22 and above
node --run deployNote: To disable validation of the config file when starting the process, use the --disable-validation flag:
# For Node.js version 20 or below
npm run deploy -- --disable-validation
# For Node.js version 22 and above
node --run deploy --disable-validationYou can deploy the bot using Docker with two different database configurations:
# Build the image
docker build -t discord-chatbot:latest .This option runs both the bot and PostgreSQL database in Docker containers:
- Navigate to the docker-compose directory:
cd docker-compose- Start the services:
docker-compose -f with-database.yml up -dThis setup:
- Creates a Docker network for container communication
- Runs PostgreSQL in a container with persistent volume
- Automatically initializes the database using init.sql
- Connects the bot to the containerized database
Use this option if you're running PostgreSQL on your host machine:
- Navigate to the docker-compose directory:
cd docker-compose- Start the service:
docker-compose -f database-on-host.yml up -dThis setup:
- Runs only the bot in a container
- Connects to PostgreSQL running on your host machine
- Uses host.docker.internal to communicate with the host's database
For both options:
- Ensure your .env file is present in the project root
- Make sure config.json is present in the project root
- The Docker setup will automatically mount these files into the container
# For either option, in the docker-compose directory:
docker-compose -f <filename>.yml down
# To also remove the database volume (Option A only):
docker-compose -f with-database.yml down -v-
TypeScript Configuration The project uses TypeScript. A
tsconfig.jsonis provided with recommended settings. -
Building
- The
deployscript handles TypeScript compilation and bot startup - Source files are compiled to the
distdirectory
- Dependencies
- discord.js: ^14.16.1
- @discordjs/builders, formatters, rest, util
- pg: ^8.12.0 (PostgreSQL client)
- TypeScript development dependencies
Use /chat with these options:
message: Your message to the AImodel: Select AI model (autocomplete available)system_instruction: Optional system promptimage: Optional image attachment
Configure passive listening triggers in config.json:
"hey": {
"enabled": true,
"triggers": {
"hey gpt": {
"model": "gpt-4o-mini",
"systemInstruction": "default",
"previousMessagesContext": 5
}
}
}- Add API key to
.env - Configure connector in
config.json - Add desired models in
modelConfigurations
You can create custom connectors to integrate additional AI providers. Here's how:
Create a new file in src/classes/connectors/ (e.g., CustomConnector.ts):
import BaseConnector, {
ChatCompletionResult,
ChatMessage,
GenerationOptions
} from "./BaseConnector";
export default class CustomConnector extends BaseConnector {
override async requestChatCompletion(
messages: ChatMessage[],
generationOptions: GenerationOptions,
user_id?: string
): Promise<ChatCompletionResult> {
// 1. Convert messages to your AI provider's format
const formattedMessages = this.convertMessages(messages);
// 2. Send request to AI provider
const response = await this.sendRequest({
messages: formattedMessages,
...generationOptions
});
// 3. Convert response to standard format
return {
resultMessage: {
role: "assistant",
content: response.text,
// Optional: audio_data_string for audio responses
// Optional: attachments for image URLs
}
};
}
private async sendRequest(payload: any) {
const response = await fetch(this.connectionOptions.url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env[this.connectionOptions.apiKey]}`
},
body: JSON.stringify(payload)
});
const data = await response.json();
if (data.error) throw new Error("API Error", {cause: data});
return data;
}
private convertMessages(messages: ChatMessage[]) {
// Convert messages to your AI provider's format
return messages.map(m => ({
// Your conversion logic here
}));
}
}Your messages must conform to these interfaces:
interface ChatMessage {
role: "user" | "assistant" | "system";
content: string;
name?: string;
attachments?: string[];
audio_data_string?: string;
}
interface ChatCompletionResult {
resultMessage: ChatMessage;
}Add your connector configuration to config.json:
{
"connectorConfigurations": {
"CustomConnector": {
"class": "classes/connectors/CustomConnector",
"connectionOptions": {
"url": "https://api.your-ai-provider.com/v1/chat",
"apiKey": "YOUR_API_KEY_ENV_VAR"
}
}
}
}Configure models that use your connector:
{
"modelConfigurations": {
"custom-model": {
"connector": "CustomConnector",
"displayName": "Custom AI Model",
"defaultSystemInstructionName": "default",
"systemInstructionAllowed": true,
"images": {
"supported": false
},
"generationOptions": {
"model": "your-model-name"
}
}
}
}-
Error Handling
- Implement proper error handling for API responses
- Throw meaningful errors that can be caught by the bot
-
Message Format
- Implement proper conversion between the bot's message format and your AI provider's format
- Handle system instructions if supported
- Handle attachments if supported
-
Authentication
- Use environment variables for API keys
- Implement proper authentication headers
-
Optional Features
- Image support: Handle attachments array in messages
- Audio support: Provide audio_data_string in responses
- Moderation: Implement content filtering if needed
Your connector can implement additional features:
// Content moderation
private async moderateContent(message: string): Promise<boolean> {
// Your moderation logic
return true;
}
// Image processing
private handleAttachments(attachments: string[]) {
// Your attachment handling logic
}
// Audio response handling
private formatAudioResponse(audioData: any) {
return `data:audio/mp3;base64,${audioData}`;
}- Connector System: Modular design for easy AI provider integration
- Database: PostgreSQL for message history and threading
- Discord Integration: Full support for Discord's interaction features
- Configuration: Flexible setup for providers, models, and permissions
Common issues and solutions:
- Database connection errors: Check PostgreSQL credentials and server status
- Discord API errors: Verify bot token and permissions
- AI provider errors: Validate API keys and model configurations
- TypeScript compilation errors: Check for syntax issues in source files
This project is licensed under the GNU Affero General Public License v3.0 with additional terms:
- No commercial use without explicit permission
- Attribution required
- Modified versions must share source code
See the LICENSE file for details.
- Original creator: ZeldaFan0225
- All AI providers for their APIs
- Discord.js team for their excellent library