Table of contents
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
Install discord.py API:
pip install discord.py
Install openai API:
pip install openai
Install dotenv:
pip install python-dotenv
Creating your Bot
Click on 'New Application'
Give a name to your application
-
Click on 'Bot' on the left then 'Add Bot'
- Click on 'Copy' and paste this token into a notepad. We will use this later.
Enable the 'Message Content Intent'
Go to 'URL Generator in OAuth2', then check the given boxes. These are the permissions that your bot needs to work properly.
- 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
Create a new folder for your bot, ChatGPT_Bot.
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)
Create a folder 'tokens' that will contain your discord and openai tokens. Create files - discord_token.env, and openai_token.env
discord_token.env
DISCORD_TOKEN=ABC123
Get the openai token from https://platform.openai.com/account/api-keys
openai_token.env
OPENAI_TOKEN=abc123
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!