Building a Discord Bot with AI Responses: Complete Guide
Building a Discord Bot with AI Responses: Complete Guide Create a Discord bot that uses free AI APIs to respond intelligently to messages. Introduction Discord bots with AI capabilities are popular for communities, support servers, and entertainment. This tutorial shows how to build one using free AI APIs — no paid tokens required. Prerequisites Node.js 18+ Discord Developer account Free API key…
Building a Discord Bot with AI Responses: Complete Guide
Creating a Discord bot that utilizes free AI APIs to generate intelligent responses to messages has become a popular trend across communities, support servers, and entertainment platforms. This guide demonstrates how to develop such a bot using free AI APIs, without the need for paid tokens.
Prerequisites:
- Node.js version 18 or higher
- A Discord Developer account
- A free API key from OpenRouter, Groq, or Together.ai
- The discord.js library: npm install discord.js
Step 1: Discord Bot Setup
Create a file named bot.js and import the necessary modules from discord.js. Set up the client object with the required intents, including Guilds, Guild Messages, and Message Content. Once the bot successfully connects to Discord, log its user tag to the console. Remember to set the DISCORD_TOKEN environment variable before running the bot.
Step 2: AI Integration (OpenRouter)
In a separate file named ai.js, define an asynchronous function getAIResponse that accepts a prompt and an optional provider parameter (defaulting to OpenRouter). This function fetches an AI-generated response using the specified provider's API key. Configure the API endpoints and models for OpenRouter and Groq, then make a POST request to the chosen provider's API endpoint. Handle any errors, such as missing API keys or unsuccessful responses, and return the AI-generated content.
Step 3: Message Handler with Fallback
In another file named handler.js, import the getAIResponse function from ai.js and define an array of provider options (Groq and OpenRouter). The handleMessage function checks if the message is not authored by a bot and if it mentions the bot itself. If these conditions are met, the function will attempt to fetch an AI response using the configured providers. If both providers fail to provide a response, the message will be ignored.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to