Create a ChatGPT Discord Bot

Ivan Campos
Sopmac Labs
5 min readMar 6, 2023

--

If you don’t have a Discord server or would like to create a server for testing the bot, go to https://discord.com/

Create a Discord Application

  1. Create a new application on the Discord developer portal (https://discord.com/developers/applications). Give it a name and an avatar, and note down the CLIENT ID. Set your Bot Permissions (e.g. Administrator) and enable MESSAGE CONTENT INTENT under Privileged Gateway Intents.
  2. Click on the “Bot” section on the left-hand side of the screen, then click Add Bot. Give your bot a name and avatar, and note down the bot token.
  3. Set up your development environment. Install Node.js (https://nodejs.org/) and a code editor of your choice (such as Visual Studio Code).
  4. Create a new directory for your bot project and open a terminal or command prompt in that directory.
  5. Initialize a new Node.js project using the command npm init. This will create a new package.json file in your project directory.
  6. Install the necessary Node.js packages using the command npm install discord.js dotenv openai. These packages provide libraries for interacting with the Discord API, OpenAI API, and storing your secret values.
  7. Create a new JavaScript file in your project directory named index.js.

Note: Ensure that your package.json is of “type”: “module”

OAuth2

Locate your Discord Application’s CLIENT ID under Settings → OAuth2

Access the following link with your CLIENT ID (noted down in step 1): https://discord.com/oauth2/authorize?scope=bot&client_id=YOUR_CLIENT_ID

When prompted, select your Discord Server and click Authorize.

Basic setup for Discord Bot and the OpenAI API

Inside your index.js, start with the following:

import dotenv from "dotenv";
import { Client, GatewayIntentBits } from "discord.js";
import { Configuration, OpenAIApi } from "openai";

dotenv.config();

const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});

const openai = new OpenAIApi(new Configuration({
apiKey: process.env.OPENAI_API_KEY,
})
);

The bot is created using the Discord.js package and the OpenAI package. The dotenv package is used to load the environment variables from a .env file, which contains sensitive information like API keys.

After importing the necessary modules and packages, the code creates a new Discord client with specific intents. The intents are used to specify what types of events the bot will receive from Discord servers. In this case, the bot will receive messages from servers, including the content of those messages.

The OpenAIApi class is then initialized with the API key from your .env file. This allows the bot to make requests to the OpenAI API to generate text.

The .env file

Create a .env file for your project with your OpenAI API Key and Bot Token values:

OPENAI_API_KEY=YOUR_KEY
BOT_TOKEN=YOUR_TOKEN

Your BOT_TOKEN value comes from the bot token we noted down in step 2

Your OPENAI_API_KEY value comes from https://platform.openai.com/account/api-keys

The .gitignore file

If using Git, create an entry in your .gitignore file for the .env

Responding in Discord with the ChatGPT API

Append the following to index.js

client.on("messageCreate", async function (message) {
if (message.author.bot) return;

try {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{role: "system", content: "You are a helpful assistant who responds succinctly"},
{role: "user", content: message.content}
],
});

const content = response.data.choices[0].message;
return message.reply(content);

} catch (err) {
return message.reply(
"As an AI robot, I errored out."
);
}
});

This code listens for a “messageCreate” event in the Discord client, triggered when a user sends a message. The function checks if the message was sent by a bot and then creates a chat completion request to the OpenAI API using the message content from the user. The OpenAI API responds with a completion based on the message, and the function sends the response back to the user in the same channel using the message.reply() method. If an error occurs, the function sends a default error message to the user.

Connecting the Bot to Discord

Complete index.js by adding this at the end.

client.login(process.env.BOT_TOKEN);

This code logs the Discord bot in by using the bot token stored in the environment variable BOT_TOKEN. The login() method is called on the client object to establish a WebSocket connection to Discord’s servers and authenticate the bot with the specified token.

By retrieving the bot token from the environment variable using the process.env method, the code keeps the token secure and protects it from being exposed in the source code, which is a best practice in software development to protect sensitive information.

Chatting with the Bot

Run your bot with the following command:

node index.js

You can then begin chatting with your Discord Bot 🤖

Once you’re done developing your bot, you can deploy it to a hosting service like Heroku or AWS to keep it running 24/7.

GitHub Repo

All of the code discussed is available in the following repo:

References

--

--

Ivan Campos
Sopmac Labs

Exploring the potential of AI to revolutionize the way we live and work. Join me in discovering the future of tech