Write your own homework tutor Discord bot with OpenAI GPT
I asked ChatGPT to write a homework helper, and to write a blog post about of our chat thread.
If you’re a student or a parent helping a student with homework, you might find it helpful to have a Discord bot that can answer questions and provide guidance. In this blog post, we’ll show you how to build a homework helper Discord bot with OpenAI chat integration. Even if you’ve never coded a Discord bot or used an OpenAI API before, you can follow these steps to create your own bot.
Prerequisites
Before we get started, there are a few things you’ll need:
- A Discord account: You’ll need to create a Discord account if you don’t already have one. You can create a new account at https://discord.com/register.
- Python and pip: You’ll need to have Python and pip installed on your computer. If you don’t already have them installed, you can download Python from https://www.python.org/downloads/ and pip will be installed automatically with Python.
- A Discord bot token: You’ll need to create a new Discord bot and obtain a bot token. You can follow the steps in the Discord Developer Portal to create a new bot and obtain a bot token.
- An OpenAI API key: You’ll need to sign up for an OpenAI API key at https://beta.openai.com/signup/.
Step 1: Install the Discord.py and OpenAI Libraries
The first thing we need to do is install the Discord.py and OpenAI libraries, which are Python libraries for interacting with the Discord API and the OpenAI API. To install the libraries, open a terminal or command prompt window and run the following commands:
pip install discord.py
pip install openai
This will install the latest versions of the Discord.py and OpenAI libraries.
Step 2: Create a New Discord Bot
Next, we need to create a new Discord bot and obtain a bot token. To do this, follow these steps:
- Go to the Discord Developer Portal at https://discord.com/developers/applications.
- Click the “New Application” button and give your application a name.
- Click on the “Bot” tab and click the “Add Bot” button.
- Give your bot a name and customize its avatar if you’d like.
- Copy the bot token and save it for later.
Step 3: Create a New Python Script
Now that we have our bot token, we can create a new Python script for our bot. Open your favorite text editor or Python IDE and create a new file called homeworkbot.py
.
In the file, we’ll start by importing the Discord.py library, creating a new Discord client object, and setting up the OpenAI API:
import discord
import openai
intents = discord.Intents.default()
client = discord.Client(intents=intents)
openai.api_key = "OPENAI_KEY"
model_engine = "gpt-3.5-turbo"
system_prompt = """
You are a homework helper bot. The students you're helping are ages 10 - 12. You will only guide and give hints. You cannot give answers.
"""
global_messages = [{"role": "system", "content": system_prompt}]
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
(Author note: Notice in the system_prompt
we’re instructing the bot not to give answers outright.)
In this code, we’re setting up the Discord client object with default intents and setting the OpenAI API key and language model.
Next, we’ll define an event handler function that will be called when the bot receives a message:
@client.event
async def on_message(message):
global global_messages
print("Message", message.content)
print("Author", message.author)
In this function, we’re printing out the contents of the message and the author to the console for debugging purposes. We’re also defining a list of global_messages
that we'll use to maintain context over multiple messages.
Now, let’s parse the incoming message and pass it to the OpenAI API to get a response:
messages = message.content.split()
print('Messages', messages)
if len(messages) and messages[0].startswith("<@") and messages[0].endswith(">"):
user_input = ""
for m in messages[1:]:
if m.startswith("<@") and m.endswith(">"):
continue
user_input += f"{m} "
user_input = user_input.strip()
print("User input", user_input, "\n")
if "!restart" in user_input or len(global_messages) > 40:
global_messages = [{"role": "system", "content": system_prompt}]
global_messages.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(
model=model_engine,
messages=global_messages
)
if "choices" in response:
global_messages.append(response["choices"][0]["message"])
await message.channel.send(response["choices"][0]["message"]["content"])
(Author note: I’m using an arbitrary 40 message count limit as a bad proxy to avoid hitting the token limit. You can do this properly using the tiktoken
library instead.)
In this code, we’re parsing the message to extract the user input, and passing it to the OpenAI API to get a response. We’re also appending the user input and OpenAI-generated response to a list of messages, so that the bot can maintain context over multiple messages.
Finally, we’re sending the OpenAI-generated response back to the user in the same channel.
Step 4: Run the Bot
Now that we have our bot script set up and integrated with OpenAI chat, we can run the bot and test it out. To do this, open a terminal or command prompt window and navigate to the directory where your homeworkbot.py
file is located. Then, run the following command:
python homeworkbot.py
This will start the bot and log it in to Discord. You should see a message in the console indicating that the bot has logged in successfully.
Step 5: Invite the Bot to a Discord Channel
Now that we have our bot set up and running, we need to invite it to a Discord channel so that it can respond to messages. To do this, follow these steps:
- Go to the Discord Developer Portal at https://discord.com/developers/applications.
- Click on the application that you created earlier for your bot.
- Click on the “OAuth2” tab.
- Scroll down to the “Scopes” section and select the “bot” checkbox.
- In the “Bot Permissions” section, select the permissions that you want to grant to your bot. For a homework helper bot, you’ll probably want to grant it “Read Messages” and “Send Messages” permissions at a minimum.
- Copy the generated OAuth2 URL and paste it into your web browser.
- Select the Discord server where you want to invite the bot.
- Click the “Authorize” button.
- Once authorized, the bot should appear in the server’s member list.
- To add the bot to a specific channel, right-click on the channel name and select “Edit Channel”.
- In the “Permissions” tab, scroll down to the “Roles/Members” section and click on the “+” button.
- Select the bot from the member list, and click “Add”.
- Finally, configure the bot’s permissions for the channel by checking or unchecking the appropriate checkboxes.
Once the bot is added to the channel, it should be able to read and send messages in that channel, as long as it has the appropriate permissions. You can test this by sending a message to the channel and seeing if the bot responds.
Congratulations! You’ve successfully invited your bot to a Discord channel and tested it out.
Conclusion
In this blog post, we’ve shown you how to build a homework helper Discord bot with OpenAI chat integration. Even if you’ve never coded a Discord bot or used an OpenAI API before, you can follow these steps to create your own bot.
We started by installing the Discord.py and OpenAI libraries, creating a new Discord bot, and setting up a Python script to handle incoming messages. Then, we integrated the bot with OpenAI chat to provide more intelligent responses to user messages. We also showed you how to invite the bot to a Discord channel so that it can respond to messages.
With this bot, you can now have a powerful homework helper at your fingertips whenever you need it. You can customize the bot to respond to specific types of questions, add new features, or integrate with other APIs to provide even more functionality.
We hope you found this blog post helpful. Happy coding!