ChatGPT bot for Discord in Python
To get started, you will need three things: a Discord server, a Discord Developer application, and the ChatGPT API.
Let’s get started. You are going to need two Python files. This is not essential, as you can merge your tokens into one script, but for the sake of this tutorial, we will separate the config file. The scripts should be called main.py
and config.py
.
Here is the code for both files:
# config.py
TOKEN = "INSERT YOUR DISCORD TOKEN"
API_KEY = "INSERT YOUR CHATGPT API"
# main.py
import asyncio
import discord
from discord.ext import commands
import openai
from config import TOKEN, API_KEY
openai.api_key = API_KEY
bot = commands.Bot(command_prefix="?")
@bot.event
async def on_ready():
print("Bot has connected")
@bot.event
async def on_message(message):
if message.content.startswith("?"):
print('I read the message')
print(f"{message.author} asked {message.content[1:]}")
async with message.channel.typing():
await asyncio.sleep(0.5)
question = message.content[1:]
response = openai.Completion.create(
engine="text-davinci-003",
prompt=f"{question}\n",
temperature=0.7,
max_tokens=1024,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
await message.channel.send(response.choices[0].text)
print(f"I replied with {response.choices[0].text}")
bot.run(TOKEN)