DEV Community

Cover image for Building a Discord Bot with OpenAI GPT
Emīls Oto Leimanis
Emīls Oto Leimanis

Posted on

2 1

Building a Discord Bot with OpenAI GPT

Creating a Discord bot powered by OpenAI's GPT model allows you to add conversational AI capabilities to your Discord server. Follow this guide to build your bot step by step.


Step 1: Set Up a Discord Bot

  1. Create a Discord Application:

  2. Generate a Bot Token:

    • Navigate to the Bot tab.
    • Click Add Bot to create your bot.
    • Under the "Token" section, click Copy to save the bot token. This token is essential for authenticating your bot. Keep it secure.
  3. Set Bot Permissions:

    • Navigate to the OAuth2 tab and then to the URL Generator section.
    • Select the "bot" scope and assign permissions like "Read Messages", "Send Messages", and "Manage Messages" as needed.
    • Copy the generated URL and use it to invite your bot to your Discord server.

Step 2: Set Up Your Development Environment

  1. Install Node.js:

    • Download and install Node.js if you don’t have it already.
  2. Set Up a New Project:

    • Open a terminal and create a new folder for your project:
     mkdir discord-gpt-bot
     cd discord-gpt-bot
    
  • Initialize a new project:

     npm init -y
    
  1. Install Required Packages:

    • Install the Discord.js library:
     npm install discord.js
    
  • Install the OpenAI API library:

     npm install openai
    

Step 3: Write the Bot Code

  1. Create a Bot File:

    • Create a file named bot.js in your project folder.
  2. Add the Basic Bot Structure:

    • Paste the following code into bot.js:
     const { Client, GatewayIntentBits } = require('discord.js');
     const { Configuration, OpenAIApi } = require('openai');
    
     const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
    
     const configuration = new Configuration({
         apiKey: 'YOUR_OPENAI_API_KEY', // Replace with your OpenAI API key
     });
     const openai = new OpenAIApi(configuration);
    
     client.once('ready', () => {
         console.log('Bot is online!');
     });
    
     client.on('messageCreate', async (message) => {
         if (message.author.bot) return;
    
         const response = await openai.createCompletion({
             model: 'text-davinci-003',
             prompt: message.content,
             max_tokens: 150,
         });
    
         message.reply(response.data.choices[0].text.trim());
     });
    
     client.login('YOUR_DISCORD_BOT_TOKEN'); // Replace with your bot token
    
  3. Replace Placeholder Values:

    • Replace YOUR_OPENAI_API_KEY with your OpenAI API key.
    • Replace YOUR_DISCORD_BOT_TOKEN with your bot token.

Step 4: Run the Bot

  1. Start the Bot:

    • In the terminal, run:
     node bot.js
    
  2. Test the Bot:

    • Send a message in your Discord server. The bot should respond with a GPT-generated reply.

Step 5: Customize Your Bot

  1. Add Command Handling:

    • Allow the bot to respond to specific commands like !ask or !gpt.
    • Example modification:
     if (message.content.startsWith('!ask')) {
         const userQuery = message.content.replace('!ask', '').trim();
         const response = await openai.createCompletion({
             model: 'text-davinci-003',
             prompt: userQuery,
             max_tokens: 150,
         });
         message.reply(response.data.choices[0].text.trim());
     }
    
  2. Limit Response Length:

    • Adjust max_tokens in the createCompletion method to control response length.
  3. Error Handling:

    • Add error handling to manage unexpected issues:
     try {
         // Your OpenAI call
     } catch (error) {
         console.error(error);
         message.reply('Sorry, something went wrong.');
     }
    

Step 6: Deploy Your Bot

  1. Use a Cloud Hosting Service:

  2. Keep Your Bot Online:

    • Use a service like UptimeRobot to ensure your bot stays active.

By following these steps, you’ll create a functional Discord bot powered by OpenAI GPT. Customize it further to add more features and improve the experience for your community!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️