Creating An Interactive Discord Chat Bot With ChatGPT— Day 23 of #30daysofAI

Atomic Read
7 min readAug 25, 2023

--

The goal for today was to build a simple interactive chat bot on Discord that is powered by ChatGPT conversation APIs. Here are the steps that I went through to do this and what I learned in the process.

CatBot by Stable Diffusion

The Goal

My idea was to see how difficult it would be to create a chatbot wired up to Discord that sends prompt queries to ChatGPT. I started with a very simple chatbot example to see how it would work- but with inklings of judging the difficulty to build something like a customer service bot for a business or product in the same fashion.

The Bot

For my sample bot, I decided to go with a Python Discord bot that would respond to !fact commands and reply back to the user with a unique interesting fact about cats (aka CatBot).

Prerequisites

Here are the main prereqs for anyone interested to try this out for themselves:

The Discord Bot Setup

First thing needing to be done is to create a bot within the Discord account being used. The easiest way to get started with this is to go to the Discord user account settings and check out ”Developer Mode” under the “Advanced” panel. There’s a link from there that goes to the Discord developer docs.

From this point, the next thing to do is to create a new Application in the Discord developer portal

Once this is done, configure some required settings under the “Bot” tab so that the bot will be able to process messages in servers it gets invited into:

The next thing to do is to create a server invite link for the bot, so it can join into a server and process chat commands. This can be done under the “URL Generator” tab of “OAuth2” inside the Discord developer Application portal. Here are the minimum settings I used so the bot can read and process messages:

At the end of selecting these settings a URL will be generated at the bottom, which can be copied. This is the bot invite link- visiting this link while logged into a Discord account will prompt a user to invite the bot to a server

After the bot has been invited to a server, make sure it has permissions to read/write messages in at least one channel. This can be done by viewing the settings for channels inside the server by a server admin.

Creating The Bot Code

Creating the Discord Bot Skeleton

To get started with the bot code I ended up starting with GitHub Copilot with this prompt:

# a python module that contains the CatBot class
# CatBot class is a discord bot that connects to OpenAI’s GPT-3 API
# CatBot responds to !fact commands with a cat fact from OpenAI’s API
# CatBot responds to !fact <message> commands with a message from OpenAI’s API

However, CoPilot ended up giving some suggestions but then stalling before anything was in a working state. So instead I took the queries to ChatGPT-4:

create a discord bot that responds to !fact message commands returning a random cat fact

ChatGPT gave some good suggestions with sample code that worked, after plugging in the Discord bot token from the Discord Developer Portal:

import discord
from discord.ext import commands
import random

TOKEN = 'YOUR_DISCORD_BOT_TOKEN'

intents = discord.Intents.default()
intents.messages = True
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)

cat_facts = [
"Cats can jump up to six times their body length in one jump.",
"The oldest known pet cat was found in a 9,500-year-old grave on the Mediterranean island of Cyprus.",
"A group of cats is called a clowder.",
"Cats have five toes on their front paws and four on their back paws.",
"Cats have 230 bones, while humans only have 206.",
"Cats have a special reflective layer behind their retinas called the tapetum lucidum, which boosts their night vision.",
# You can add as many facts as you like!
]

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')

@bot.command(name='cat')
async def cat(ctx):
await ctx.send(random.choice(cat_facts))

bot.run(TOKEN)

Setting Up The Python Environment

I did a very simple Python environment set up for this bot once ChatGPT did the heavy lifting of the code. Here are the console commands I ran (on Linux or Windows WSL):

python3 -m venv venv
. ./venv/bin/activate
pip install discord
pip install openai
pip freeze > requirements.txt

After this I pasted the above code from ChatGPT-4 response into a file called catbot.py, replacing YOUR_DISCORD_BOT_TOKEN with my bot token.

Running The Skeleton Bot

With the environment set up, and the bot code in place and the YOUR_DISCORD_BOT_TOKEN replaced with a real bot token all that’s needed to do is to run:

python catbot.py

The bot could then be tested by running typing !fact into any channel that the bot is present, in Discord.

Wiring Up OpenAI GPT-3

Once I had the Discord bot running I wanted to make the responses more interactive by wiring up to OpenAI. I asked ChatGPT-4 to update the code to wire up to OpenAI with this prompt:

Update the bot to connect to openai and ask GPT-3 for a random cat fact

This resulted in the below code, which used the legacy Completions API integration. This worked, but as more or less been deprecated by OpenAI already in favor of a new set of endpoints using GPT-3. Here’s the code it generated:

import discord
from discord.ext import commands
import openai

# Discord & OpenAI Configuration
TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)
openai.api_key = OPENAI_API_KEY

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')

@bot.command(name='cat')
async def cat(ctx):
# Ask GPT-3 for a random cat fact
response = openai.Completion.create(
engine="davinci",
prompt="Tell me a random cat fact.",
max_tokens=50
)

cat_fact = response.choices[0].text.strip()
await ctx.send(cat_fact)

bot.run(TOKEN)

Note: This also requires changing YOUR_OPENAI_API_KEY to a valid OpenAI API key once the API account is set up (as described in the prereqs)

Fixing To Use OpenAI Chat API

To make the responses even more fluid I asked ChatGPT to upgrade the calls to use the new API. This took a few prompts back and forth since the first generated response resulted in broken code. Here are the two prompts I used to get working code:

Update the bot to use gpt-3.5-turbo for querying openai

I got this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidRequestError: This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?

This resulted in the final working code:

import discord
from discord.ext import commands
import openai

# Discord & OpenAI Configuration
TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)
openai.api_key = OPENAI_API_KEY

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')

@bot.command(name='cat')
async def cat(ctx):
# Ask GPT-3.5-turbo for a random cat fact using the chat model
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me a random cat fact."}
]
)

cat_fact = response.choices[0].message['content']
await ctx.send(cat_fact)

bot.run(TOKEN)

End Product

Here’s what the final product of the bot looked like, with some example command runs:

Final Thoughts

All-in, it took less than an hour to get a working Discord bot wired up to OpenAI GPT-3 APIs. Most of the time was taken by looking up bot permissions and doing trial/error on which permissions were needed by the bot to run.

This flow seems like a very easy way to get started with an interactive bot. For businesses looking to set up chatbots for their products- this same flow could be used (if using Discord or similar for chat), with some creative prompting in the API calls to OpenAI. Any more specific or complex responses may require some model fine-tuning in OpenAI (e.g. for things like training the model to respond based on product info that’s recent, etc.) as an additional step.

I would recommend anyone that is looking to do easy interactive chat on a product to try this out, with the following pricing caveat:

API Pricing

The Discord bot API is free to use. However, the OpenAI APIs (as described in the prereqs) are not free, and are billed per use. For my testing (doing a dozen or so commands), it used less than $0.01 in charges- so for development or small traffic bots this seems very cheap to run. For anything high scale, it’s worth checking the pricing model for OpenAI queries before taking a big dependency on it.

<< EOM >>

Have feedback or questions about setting up an interactive chatbot? Drop me a line in the comments and let me know what you think.

--

--