Building a discord chatbot using OpenAI's GPT 3 model (2024)

Building a discord chatbot using OpenAI's GPT 3 model (1)

Pak Maneth

Posted on

Building a discord chatbot using OpenAI's GPT 3 model (3) Building a discord chatbot using OpenAI's GPT 3 model (4) Building a discord chatbot using OpenAI's GPT 3 model (5) Building a discord chatbot using OpenAI's GPT 3 model (6) Building a discord chatbot using OpenAI's GPT 3 model (7)

#discord #openai #chatbot #python

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.
Building a discord chatbot using OpenAI's GPT 3 model (8)

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.
Building a discord chatbot using OpenAI's GPT 3 model (9)
(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
Building a discord chatbot using OpenAI's GPT 3 model (10)

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

Building a discord chatbot using OpenAI's GPT 3 model (11)

For permission

Building a discord chatbot using OpenAI's GPT 3 model (12)

(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.
Building a discord chatbot using OpenAI's GPT 3 model (13)

Coding time 👨‍💻

Creating a virtual environment

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

mkdir chatbotcd chatbot

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

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 

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

In the .env file we will declare 2 environment

OPENAI_API_KEY=<OpenAI api key here>DISCORD_TOKEN=<Discord token here>

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

touch main.py

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 getenvimport openaiimport discordfrom dotenv import load_dotenvload_dotenv()DISCORD_TOKEN = getenv("DISCORD_TOKEN")openai.api_key = getenv("OPENAI_API_KEY") # set openai's api key

Now we going to start building the discord bot

# Declare our intent with the bot and setting the messeage_content to trueintents = discord.Intents.default()intents.message_content = Trueclient = discord.Client(intents=intents)PREFIX = ">>" # set any prefix you want@client.eventasync def on_ready(): """ Print a message when the bot is ready """ print(f"We have logged in as {client.user}")@client.eventasync 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 functionclient.run(DISCORD_TOKEN)

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

Test your bot

Go to the server that you have invited your bot then start messaging!
Building a discord chatbot using OpenAI's GPT 3 model (14)
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.

I am YouChat, a large language model from You.com. I have access to a wide range of information and can provide assistance on various topics. I can help you with questions related to creating a Discord bot with GPT-3, as well as provide information on concepts mentioned in the article you shared.

Now, let's dive into the concepts mentioned in the article:

Discord Bot with GPT-3

Creating a Discord bot with GPT-3 allows you to leverage the power of artificial intelligence to generate conversations, respond to user queries, and provide useful answers on your Discord server. To get started, you will need a Discord account and an OpenAI account. Here are the steps outlined in the article:

  1. Setting up a Discord bot:

    • Go to the Discord Developer Portal page and create a new application.
    • Create a new bot within the application and give it a proper username.
    • Reset the token and save it for later use.
    • Enable the Message Content Intent in the Privileged Gateway Intents section.
    • Generate a URL to invite the bot to your server.
  2. Acquiring OpenAI's API key:

    • Create an OpenAI account if you don't have one.
    • Authenticate yourself and go to the OpenAI User's API Keys management page.
    • Generate a new API key and save it for later use.
  3. Coding the Discord bot:

    • Create a new directory for your project and set up a virtual environment using pipenv.
    • Install the necessary modules: openai, discord.py, python-dotenv.
    • Create a .env file to store your Discord token and OpenAI API key.
    • Write the code in main.py to import the required modules and load the environment variables.
    • Build the Discord bot by declaring intents, setting a prefix, and defining event handlers.
    • Implement the chat function to handle user queries and generate responses using GPT-3.
    • Run the bot using the client.run(DISCORD_TOKEN) function.
  4. Testing the bot:

    • Go to the server where you invited the bot and start messaging to interact with it.

Please note that the article mentions that the provided bot is not ready for public use and suggests adding more features, security measures, and error handling before hosting it publicly.

I hope this information helps you understand the process of creating a Discord bot with GPT-3. If you have any further questions, feel free to ask!

Building a discord chatbot using OpenAI's GPT 3 model (2024)
Top Articles
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated:

Views: 6452

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.