Building a discord chatbot using OpenAI's GPT 3 model

manethpak

Pak Maneth

Posted on January 10, 2023

Building a discord chatbot using OpenAI's GPT 3 model

Creating a Discord bot with GPT-3 is a great way to get started with the latest in artificial intelligence technology. With GPT-3, you can create a bot that can generate conversations, respond to user queries, and provide useful answers for your discord server. All you need is a little bit of coding and googling around.

Requirements

  • Discord account
  • OpenAI account
  • Some python magic

Setting up a discord bot and acquiring the token

First, head to discord developer portal page and create yourself a bot. When the page is loaded, you will see the "New Application" button on the top right corner. Click on it and give your new application a name and agree to discord's term.
Discord application

Once you have created an application. Head over to the Bot section and create a new bot. After a bot has been created you'll need to give the bot a proper username then you can continue by clicking on the reset token and then save the revealed token to your notepad or somewhere safe. We will need this token later on.
Discord's bot token
(Don't worry about this token I will reset it later)

Then scroll down to the Privileged Gateway Intents and enabled the Message Content Intent so that the bot will be able to read and send messages in discord
Discord's Privileged Gateway Intents

Finally, you will need a link to invite your newly created bot to your server. Go into OAuth2 > URL Generator then select the following:

For scopes

Discord URL Generator's scopes

For permission

Discord URL Generator's permissions

(You can set multiple text permissions to your need)

Copy the Generated URL and invite the bot to any of your server, and you're done setting up a discord bot! Congrats🎉, just kidding there's still 2 more steps to go.


Acquiring OpenAI's api key

If you don't have an OpenAI account then create one, it free! Plus you will get 18$ worth of credit to use. To obtain OpenAI's api key you will need be authenticated then head on to OpenAI User's API Keys management page. Then generate yourself a new API Key, and just like the Discord Token, copy the key and save it somewhere safe we going to need the key to access the GPT-3 model.
Image description


Coding time 👨‍💻

Creating a virtual environment

We're going to make a new directory for our project

mkdir chatbot
cd chatbot
Enter fullscreen mode Exit fullscreen mode

Since we are using python we're going to need a virtual environment to isolate our environment. I will be using pipenv to to create a virtual environment. You can install pipenv with the command below

pip install pipenv
Enter fullscreen mode Exit fullscreen mode

Then we going to need install the necessary module and activate the shell for this environment

pipenv install openai discord.py python-dotenv 

pipenv shell 
Enter fullscreen mode Exit fullscreen mode

Final part

Once you're done setting up your virtual environment and installing the module we can start coding our bot with Python.

First thing first, we need a .env file to save our important token and key that we had to obtain earlier. Remember, we need to keep the token and key safe so if you're going to upload the source code to a remote repository like GitHub you should make a .gitignore file and add *.env to the file so that it will not upload the credential to the public.

touch .env
Enter fullscreen mode Exit fullscreen mode

In the .env file we will declare 2 environment

OPENAI_API_KEY=<OpenAI api key here>
DISCORD_TOKEN=<Discord token here>
Enter fullscreen mode Exit fullscreen mode

After creating our .env file we will get into our python code

touch main.py
Enter fullscreen mode Exit fullscreen mode

Inside the main.py we will first import the our module that we are going to use on top of the file and load our environment variable

from os import getenv
import openai
import discord
from dotenv import load_dotenv

load_dotenv()


DISCORD_TOKEN = getenv("DISCORD_TOKEN")
openai.api_key = getenv("OPENAI_API_KEY") # set openai's api key
Enter fullscreen mode Exit fullscreen mode

Now we going to start building the discord bot

# Declare our intent with the bot and setting the messeage_content to true
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

PREFIX = ">>" # set any prefix you want

@client.event
async def on_ready():
    """
    Print a message when the bot is ready
    """
    print(f"We have logged in as {client.user}")


@client.event
async def on_message(message: discord.Message):
    """
    Listen to message event
    """
    # ignore messages from the bot itself and messages that don't start with the prefix we have set
    if message.author == client.user or not not message.content.startswith(PREFIX):
        return 

    # listen to any messages that start with '>>ask'
    if message.content.startswith(">>ask"):
        await chat(message)


async def chat(message: discord.Message):
    try:
        # get the prompt from the messsage by spliting the command
        command, text = message.content.split(" ", maxsplit=1)
    except ValueError:
        await message.channel.send("Please provide a question using the >>ask command")
        return

    # get reponse from openai's text-davinci-003 aka GPT-3
    # You can play around with the filter to get a better result
    # Visit https://beta.openai.com/docs/api-reference/completions/create for more info
    response = Completion.create(
        engine="text-davinci-003",
        prompt=text,
        temperature=0.8,
        max_tokens=512,
        top_p=1,
        logprobs=10,
    )

    # Extract the response from the API response
    response_text = response["choices"][0]["text"]

    await message.channel.send(response_text)

# Run the bot by passing the discord token into the function
client.run(DISCORD_TOKEN)
Enter fullscreen mode Exit fullscreen mode

And you're done! All you had to do left is run your bot and play around with it in your discord server! You can run the bot with

python main.py
Enter fullscreen mode Exit fullscreen mode

Test your bot

Go to the server that you have invited your bot then start messaging!
chatgpt discord bot
Why do your homework, when you can ask GPT to write you one🤣

Going further

This bot above only contain a very minimum features to run, so feel free to add more feature to it. Have fun with it and explore it potential.

You should note that the bot here is not usable for the general public. More security and error handling should be enforced before it is ready to be host to the public, or it will be easily exploited.

The source code is available on my github's repo. Tho I made some changes to it so it won't be the same code as the one in this article.

💖 💪 🙅 🚩
manethpak
Pak Maneth

Posted on January 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related