Comprehensive Guide to Building a Discord Bot with Multi-Tasking AI Agent Running 24/7 on VPS
A detailed guide on building a Discord bot integrated with a multi-tasking AI Agent, running 24/7 on a VPS with optimized configuration, including setup, configuration, automation,...
Introduction
Discord bots are powerful tools for automating tasks within a Discord server, from user management to command processing and AI interaction. With the advancement of large AI models, integrating a multi-tasking AI Agent into a Discord bot enables the creation of intelligent, autonomous systems that operate 24/7 on a VPS. This guide walks you through the complete process of building a Discord bot with a multi-tasking AI Agent, ensuring stable and efficient operation on a VPS.
Requirements and Preparation
Before starting, ensure you have the following:
- Discord account with server administrator privileges.
- A high-RAM VPS (minimum 4GB, recommended 8GB or more) from High-RAM Cloud VPS for Self-Hosted LLMs & API Gateways.
- SSH access to the VPS.
- Node.js and npm installed.
- GitHub account to manage source code.
Setting Up the Environment and Installing the Basic Bot
1. Log in to the VPS via SSH:
ssh username@your-vps-ip
2. Install Node.js and npm (if not already installed):
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -\nsudo apt-get install -y nodejs
3. Create a project folder and initialize Node.js:
mkdir discord-ai-bot\ncd discord-ai-bot\nnpm init -y
4. Install required libraries:
npm install discord.js axios dotenv
5. Create a `.env` file to store configuration:
DISCORD_TOKEN=your-discord-bot-token\nAI_API_URL=https://your-ai-api-endpoint.com\nAI_API_KEY=your-api-key
6. Create a `bot.js` file with basic code:
const { Client, GatewayIntentBits } = require('discord.js');\nconst axios = require('axios');\nconst dotenv = require('dotenv');\n\ndotenv.config();\n\nconst client = new Client({\n intents: [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n ],\n});\n\nclient.on('ready', () => {\n console.log(`Bot is ready with name ${client.user.tag}!`);\n});\n\nclient.on('messageCreate', async (message) => {\n if (message.author.bot) return;\n\n if (message.content.startsWith('!ai')) {\n const query = message.content.slice(4).trim();\n try {\n const response = await axios.post(process.env.AI_API_URL, {\n query: query,\n }, {\n headers: {\n 'Authorization': `Bearer ${process.env.AI_API_KEY}`,\n },\n });\n message.reply(response.data.response);\n } catch (error) {\n message.reply('An error occurred while processing your request.');\n }\n }\n});\n\nclient.login(process.env.DISCORD_TOKEN);
Integrating a Multi-Tasking AI Agent
To expand the bot's capabilities, integrate a multi-tasking AI Agent to perform tasks such as:
- Answering questions.
- Analyzing sentiment.
- Running automated commands.
- Responding contextually.
1. Create an `agents` directory and separate agent files:
mkdir agents\ntouch agents/ai-agent.js\ntouch agents/emotion-analyzer.js\ntouch agents/automation-agent.js
2. Update `bot.js` to load and use the agents:
const aiAgent = require('./agents/ai-agent');\nconst emotionAnalyzer = require('./agents/emotion-analyzer');\nconst automationAgent = require('./agents/automation-agent');\n\nclient.on('messageCreate', async (message) => {\n if (message.author.bot) return;\n\n // Call AI Agent\n if (message.content.startsWith('!ai')) {\n const query = message.content.slice(4).trim();\n const response = await aiAgent.process(query);\n message.reply(response);\n }\n\n // Analyze sentiment\n emotionAnalyzer.analyze(message);\n\n // Automate\n automationAgent.handle(message);\n});
3. Configure the AI Agent to process requests from the AI API:
const axios = require('axios');\nconst dotenv = require('dotenv');\n\nconst AI_API_URL = process.env.AI_API_URL;\nconst AI_API_KEY = process.env.AI_API_KEY;\n\nconst aiAgent = {\n async process(query) {\n try {\n const response = await axios.post(AI_API_URL, {\n query: query,\n }, {\n headers: {\n 'Authorization': `Bearer ${AI_API_KEY}`,\n },\n });\n return response.data.response;\n } catch (error) {\n return 'An error occurred.';\n }\n }\n};\n\nmodule.exports = aiAgent;
Monitoring and 24/7 Operation
To ensure the bot runs stably 24/7, use the following tools:
- PM2 for process management.
- Logrotate for log management.
- Uptime monitoring like UptimeRobot.
1. Install PM2:
npm install pm2 -g
2. Start the bot with PM2:
pm2 start bot.js --name "discord-ai-bot"
3. Configure PM2 to automatically restart on errors:
pm2 startup\npm2 save
4. Check bot status:
pm2 status
Verification and Troubleshooting
1. Check logs:
pm2 logs discord-ai-bot
2. Test AI API connection:
curl -X POST https://your-ai-api-endpoint.com/api/query \\\n -H "Authorization: Bearer your-api-key" \\\n -d '{"query": "Hello, how are you?"}'
3. Test Discord connection:
node bot.js
If the bot fails to start, verify the bot token and permissions on Discord.
References
- Guide to Running Stable Diffusion ComfyUI on VPS GPU for 24/7 AI Art Rendering with Optimized Costs
- Guide to Setting Up Cloudflare Turnstile to Replace ReCAPTCHA on VPS: Increase Page Load Speed by 30% and Optimize UX
- Building an AI Digital Twin for Server: Full Simulation and Failure Prediction for VPS Infrastructure
High-RAM Cloud VPS Plans Optimized for AI, Databases & Cache
Enterprise RAID 10 NVMe SSDs, CMC & FPT District 9 uplinks with Anycast Anti-DDoS and 99.99% SLA.
VPS-4E
10% VAT included
- CPU: 4 vCPU
- RAM: 8 GB
- SSD: 50 GB NVMe
