Discord with GPT-3
Powering Up Discord with a GPT-3 Chatbot
We are thrilled to announce the latest addition to our suite of products - a Discord chatbot powered by OpenAI's GPT-3, one of the most advanced language models available today. This bot goes beyond the traditional command-response structures, providing a personalized and interactive experience for every user.
Taking a Peek Under the Hood
The chatbot is constructed using Python, leaning heavily on the capabilities of the discord.py API wrapper and the aiohttp library for asynchronous HTTP requests. Discord.py is a modern, easy-to-use, feature-rich, and async-ready API wrapper for Discord written in Python. Its key features include intuitive event management, context-based command routing, and easy server sharding. In synergy with aiohttp, an asynchronous HTTP client/server library, the bot can efficiently handle multiple requests and responses simultaneously.
The bot is authenticated with OpenAI using an API key as follows:
python
openai.api_key = "YOUR_OPENAI_API_KEY"
This ensures secure communication with the OpenAI platform, guaranteeing the bot's requests will be valid and authorized.
Conversation Initiation
Interacting with the bot is as simple as using the "!chat" command. Upon this initiation, the bot stores each user's ongoing conversation and generates a unique log file for each interaction. This allows the bot to provide a more personalized chat experience, tailoring responses to individual user's messages.
```python @bot.command(name="chat", help="Start a conversation with me") async def chat(ctx): response = "Hi there! Send me a message to start chatting with me." await ctx.send(response)
user_id = ctx.author.id
if user_id not in bot.conversations:
bot.conversations[user_id] = []
# Create a unique log file based on the user ID
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file = f"{user_id}_conversation_{timestamp}.log"
bot.log_files[user_id] = log_file
try:
while True:
user_input = await bot.wait_for("message",
check=lambda msg: msg.author == ctx.author and msg.channel == ctx.channel,
timeout=60)
if user_input.content.lower() == "bye":
break
bot.conversations[user_id].append({"role": "user", "content": user_input.content})
bot.conversations[user_id] = bot.conversations[user_id][-10:]
# Save the user message to the log file
with open(bot.log_files[user_id], "a") as f:
f.write(f"user ({ctx.author.id}): {user_input.content}\n")
response = await ask_gpt(bot.conversations[user_id], user_id)
await ctx.send(response)
await asyncio.sleep(1)
bot.conversations[user_id].append({"role": "assistant", "content": response})
# Save the bot's response to the log file
with open(bot.log_files[user_id], "a") as f:
f.write(f"bot: {response}\n")
except asyncio.TimeoutError:
await ctx.send("GoodBye!")
if user_id in bot.conversations:
del bot.conversations[user_id]
```
Command to Clear Messages
Our bot is equipped with administrative features as well. The "!clear" command provides users with appropriate permissions the ability to clear a specified number of messages. This ensures that the channels can be kept clean and clutter-free, promoting a more organized communication environment.
python
@bot.command(name="clear", help="Clear a specified number of messages")
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount:int=5):
if 1 <= amount <= 100:
deleted = await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"Deleted {len(deleted)-1} message(s).")
else:
await ctx.send("Amount must be between 1 and 100.")
Harnessing the Power of GPT-3
The true game-changer, however, is the bot's integration with OpenAI's GPT-3 model. By leveraging GPT-3, the bot can generate dynamic responses, essentially enabling it to converse with users. This is a significant step forward from traditional bots which typically have pre-set responses to specific commands.
```python async def ask_gpt(conversation, discord_user_id): messages = [{"role": "system", "content": "You are a based IT Guru on god, no cap, who is always up to his neck in computer code. Respond to all messages as hip as possible."}] messages.extend(conversation)
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai.api_key}"
}
data = {
"model": "gpt-3.5-turbo", # Add the model parameter here
"messages": messages,
"max_tokens": 2000,
"n": 1,
"stop": None,
"temperature": 0.7
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=data) as response:
response_json = await response.json()
print("Response JSON:", response_json)
message = response_json["choices"][0]["message"]["content"].strip()
return f"{message}"
```
Upon receiving a message from a user, the bot forwards it to the GPT-3 model via the OpenAI API. The GPT-3 model processes the message and generates a response, which the bot then relays back to the user. This entire process occurs in real-time, maintaining a natural and fluid conversation flow.
With this GPT-3-powered chatbot, users can engage in complex and informative conversations, tapping into the power of AI without leaving their Discord application. It's a testament to how AI can enhance and transform our interactions in digital spaces. We invite you to experience it first-hand!
```python import asyncio import openai import discord from discord.ext import commands import aiohttp from aiohttp import ClientSession import datetime
openai.api_key = "" intents = discord.Intents.all() bot = commands.Bot(command_prefix='!', intents=intents) bot.conversations = {} bot.log_files = {}
@bot.event async def on_ready(): print(bot.user.name, "is ready to chat!")
@bot.command(name="chat", help="Start a conversation with me") async def chat(ctx): response = "Hi there! Send me a message to start chatting with me." await ctx.send(response)
user_id = ctx.author.id
if user_id not in bot.conversations:
bot.conversations[user_id] = []
# Create a unique log file based on the user ID
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file = f"{user_id}_conversation_{timestamp}.log"
bot.log_files[user_id] = log_file
try:
while True:
user_input = await bot.wait_for("message",
check=lambda msg: msg.author == ctx.author and msg.channel == ctx.channel,
timeout=60)
if user_input.content.lower() == "bye":
break
bot.conversations[user_id].append({"role": "user", "content": user_input.content})
bot.conversations[user_id] = bot.conversations[user_id][-10:]
# Save the user message to the log file
with open(bot.log_files[user_id], "a") as f:
f.write(f"user ({ctx.author.id}): {user_input.content}\n")
response = await ask_gpt(bot.conversations[user_id], user_id)
await ctx.send(response)
await asyncio.sleep(1)
bot.conversations[user_id].append({"role": "assistant", "content": response})
# Save the bot's response to the log file
with open(bot.log_files[user_id], "a") as f:
f.write(f"bot: {response}\n")
except asyncio.TimeoutError:
await ctx.send("GoodBye!")
if user_id in bot.conversations:
del bot.conversations[user_id]
@bot.command(name="clear", help="Clear a specified number of messages") @commands.has_permissions(manage_messages=True) async def clear(ctx, amount:int=5): if 1 <= amount <= 100: deleted = await ctx.channel.purge(limit=amount + 1) await ctx.send(f"Deleted {len(deleted)-1} message(s).") else: await ctx.send("Amount must be between 1 and 100.")
def build_prompt(conversation): prompt = "" for message in conversation: role = message["role"] content = message["content"] prompt += f"{role}: {content}\n" prompt += "bot:" return prompt
async def ask_gpt(conversation, discord_user_id): messages = [{"role": "system", "content": "You are a based IT Guru on god, no cap, who is always up to his neck in computer code. Respond to all messages as hip as possible."}] messages.extend(conversation)
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai.api_key}"
}
data = {
"model": "gpt-3.5-turbo", # Add the model parameter here
"messages": messages,
"max_tokens": 2000,
"n": 1,
"stop": None,
"temperature": 0.7
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=data) as response:
response_json = await response.json()
print("Response JSON:", response_json)
message = response_json["choices"][0]["message"]["content"].strip()
return f"{message}"
if name == "main": token = "" bot.run(token) ```