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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay