Build your ChatGPT Discord Bot in 10 mins

Build your ChatGPT Discord Bot in 10 mins

·

2 min read

Are you interested in building your own ChatGPT Discord bot using Python?

In this step-by-step guide, I'll show you how to create a ChatGPT Discord bot in just 10 minutes. This tutorial is aimed at beginners who want to build the bot from scratch. The blog will cover everything from setting up a new Discord bot to coding it in Python and testing it on a Discord server. By the end of this tutorial, you'll have your own ChatGPT Discord bot up and running. Let's get started!

Prerequisites

  1. Install Python: python.org/downloads

  2. Install discord.py API: pip install discord.py

  3. Install openai API: pip install openai

  4. Install dotenv: pip install python-dotenv

Creating your Bot

  1. Go to Discord Developers Portal

  2. Click on 'New Application'

  1. Give a name to your application

  2. Click on 'Bot' on the left then 'Add Bot'

  1. Click on 'Copy' and paste this token into a notepad. We will use this later.

  1. Enable the 'Message Content Intent'

  2. Go to 'URL Generator in OAuth2', then check the given boxes. These are the permissions that your bot needs to work properly.

  1. A URL will be generated at the bottom. Copy this URL in your browser to invite your new bot to your Discord server.

Coding the Bot

  1. Create a new folder for your bot, ChatGPT_Bot.

  2. Create main.py file

import discord
from discord.ext import commands
import os
import openai
from dotenv import load_dotenv

# Get discord token from a file
load_dotenv('tokens/discord_token.env')
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")

# Get openai token from a file
load_dotenv('tokens/openai_token.env')
openai.api_key = os.getenv("OPENAI_TOKEN")

intents = discord.Intents.default()
intents.message_content=True
bot = commands.Bot(command_prefix= "!", intents=intents)

@bot.command()
async def chat(ctx, *args):
    try:
        prompt = ''.join(args)
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",    
            messages=[{"role": "user", "content": f"{prompt} "}]
        )

        reply = ""

        if not 'error' in response:
            reply = response['choices'][0]['message']['content']
            await ctx.channel.send(reply)

    except Exception:
        await ctx.channel.send("Something went wrong.")

bot.run(DISCORD_TOKEN)
  1. Create a folder 'tokens' that will contain your discord and openai tokens. Create files - discord_token.env, and openai_token.env

  2. discord_token.env

    DISCORD_TOKEN=ABC123

  3. Get the openai token from https://platform.openai.com/account/api-keys

    openai_token.env

    OPENAI_TOKEN=abc123

  4. Run main.py

Run the Bot

To use the bot in the server, we will use - !chat

Great job! You've successfully created your very own ChatGPT Discord bot! With your bot up and running, you now have ChatGPT in your own Discord server. Have fun chatting with it!