- Prerequisites:
- Discord account
- Python 3.6 or higher
- OpenAI API Key
- Basic understanding of Python programming
- Setting up the environment:
- Install the required packages by running “pip install discord openai” in the terminal.
- Create a new Discord bot by visiting the Discord Developer Portal and following the instructions.
- Note down the bot token as it will be used later.
- Writing the code:
- Open a new Python file and import the required packages using “import discord” and “import openai”.
- Define the Discord bot client using “client = discord.Client()”.
- Use the “on_message” event to listen for incoming messages and trigger the AI response using OpenAI API.
- Implement the logic to send the response to the Discord channel using the “send” method on the “channel” object.
- Provide the OpenAI API key using the “openai.api_key = ‘API_KEY'” syntax.
- Testing the bot:
- Run the code and check if the bot is connected to the Discord server by checking the console logs.
- Test the bot by sending a message to the Discord channel and verify if the AI response is received.
- Deployment:
- Save the code to a file named “chatgpt_discord_bot.py”.
- Run the bot using the command “python chatgpt_discord_bot.py” in the terminal.
Congratulations! You have successfully created a ChatGPT Discord bot. You can customize the bot further by adding additional functionalities like listening for specific keywords or sending random responses.
Full Sample Code:
import discord
import openai
openai.api_key = "YOUR_OPENAI_API_KEY"
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
@client.event
async def on_message(message):
if message.author == client.user:
return
response = openai.Completion.create(
engine="text-davinci-002",
prompt=message.content,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
).get("choices")[0].text
await message.channel.send(response)
client.run('YOUR_DISCORD_BOT_TOKEN')
Replace YOUR_OPENAI_API_KEY
with your OpenAI API key and YOUR_DISCORD_BOT_TOKEN
with your Discord bot token. Then, run the code and your ChatGPT Discord bot should be up and running!