DiscoGPT/bot.py
2024-05-31 04:23:06 +00:00

53 lines
1.6 KiB
Python
Executable File

import os
import discord
from openai import AsyncOpenAI
from discord.ext import commands
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
DISCORD_TOKEN = os.getenv('DISCORD_TOKEN')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
aclient = AsyncOpenAI(api_key=OPENAI_API_KEY)
# Initialize OpenAI API
# Set up the bot with the message content intent
intents = discord.Intents.default()
intents.message_content = True # Ensure the bot can read message content
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Bot is ready. Logged in as {bot.user}')
@bot.event
async def on_message(message):
# Log the message content for debugging
print(f'Message from {message.author}: {message.content}')
# Process commands if the message is not from the bot itself
if message.author == bot.user:
return
await bot.process_commands(message)
@bot.command(name='bot')
async def ask_gpt(ctx, *, question: str):
try:
# Send the question to GPT-4o using the new OpenAI API
response = await aclient.chat.completions.create(model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant. You exist inside a discord server"},
{"role": "user", "content": question}
])
answer = response.choices[0].message.content.strip()
# Send the response back to the Discord channel
await ctx.send(answer)
except Exception as e:
await ctx.send("An error occurred while processing your request.")
print(f'Error: {e}')
# Run the bot
bot.run(DISCORD_TOKEN)