KaniumCogs/reginaldCog/reginald.py

62 lines
2.1 KiB
Python
Raw Normal View History

2023-03-14 17:24:21 +01:00
import openai
2023-03-14 18:49:44 +01:00
import os
2023-03-14 19:15:46 +01:00
import random
2023-03-14 17:45:58 +01:00
from redbot.core import Config, commands
2023-03-14 17:24:21 +01:00
class ReginaldCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
2023-03-14 17:59:57 +01:00
self.config = Config.get_conf(self, identifier=71717171171717)
2023-03-14 17:45:58 +01:00
self.config.register_global(
openai_model="text-davinci-002"
)
2023-03-14 18:58:49 +01:00
self.config.register_guild(
openai_api_key=None
)
2023-03-14 17:24:21 +01:00
2023-03-14 17:54:14 +01:00
@commands.guild_only()
@commands.has_permissions(manage_guild=True)
2023-03-14 17:24:21 +01:00
@commands.command()
2023-03-14 18:58:49 +01:00
async def setreginaldcogapi(self, ctx, api_key):
"""Set the OpenAI API key"""
await self.config.guild(ctx.guild).openai_api_key.set(api_key)
await ctx.send("OpenAI API key set successfully.")
@commands.guild_only()
@commands.command()
2023-03-14 17:24:21 +01:00
async def reginald(self, ctx, *, prompt=None):
"""Ask Reginald a question"""
2023-03-14 19:15:46 +01:00
greetings = [
"Greetings! How may I be of assistance to you?",
"Yes? How may I help?",
"Good day! How can I help you?",
"You rang? What can I do for you?",
]
2023-03-14 17:24:21 +01:00
if prompt is None:
2023-03-14 19:15:46 +01:00
await ctx.send(random.choice(greetings))
return
2023-03-14 17:54:14 +01:00
try:
2023-03-14 18:58:49 +01:00
api_key = await self.config.guild(ctx.guild).openai_api_key()
2023-03-14 18:49:44 +01:00
if api_key is None:
2023-03-14 19:05:31 +01:00
await ctx.author.send('OpenAI API key not set. Please use the "!setreginaldcogapi" command to set the key.')
return
2023-03-14 17:54:14 +01:00
model = await self.config.openai_model()
openai.api_key = api_key
max_tokens = min(len(prompt) * 2, 2048)
response = openai.Completion.create(
model=model,
prompt=prompt,
max_tokens=max_tokens,
n=1,
stop=None,
temperature=0.5,
)
await ctx.send(response.choices[0].text.strip())
except openai.error.OpenAIError as e:
2023-03-14 18:49:44 +01:00
import traceback
traceback.print_exc()
2023-03-14 19:15:46 +01:00
await ctx.send(f"I apologize, but I am unable to generate a response at this time. Error message: {str(e)}")
2023-03-14 17:24:21 +01:00
def setup(bot):
2023-03-14 17:40:21 +01:00
cog = ReginaldCog(bot)
2023-03-14 17:54:14 +01:00
bot.add_cog(cog)