Added the remind_me function

This commit is contained in:
tsuk 2024-01-21 00:17:12 -08:00
parent 275c5b7ee2
commit 0d646ebcba
2 changed files with 90 additions and 2 deletions

View file

@ -1,9 +1,10 @@
#sparkytron 3000 plugin #sparkytron 3000 plugin
import os import os
import time import time
import json
from PIL import Image, PngImagePlugin from PIL import Image, PngImagePlugin
import aiohttp import aiohttp
from discord.ext import commands from discord.ext import commands, tasks
class AsyncOpenAI(commands.Cog): class AsyncOpenAI(commands.Cog):
@ -13,6 +14,7 @@ class AsyncOpenAI(commands.Cog):
self.working_dir = "tmp/open_ai/" self.working_dir = "tmp/open_ai/"
self.data_dir = "data/open_ai/" self.data_dir = "data/open_ai/"
self.folder_setup() self.folder_setup()
self.remind_me_loop.start()
def folder_setup(self): def folder_setup(self):
try: try:
@ -23,6 +25,21 @@ class AsyncOpenAI(commands.Cog):
except: except:
print("AsyncOpenAI failed to make directories") print("AsyncOpenAI failed to make directories")
def read_db(self,filepath):
with open(filepath,"r") as fileobj:
db_content = json.load(fileobj)
#print(db_content,type(db_content))
return db_content
def save_to_db(self,filepath,db_content):
with open(filepath,"w") as fileobj:
json.dump(db_content,fileobj,indent=4)
async def remind(self,reminder_dict): #THIS IS THE FUNCTION TO AUTOMATICALLY FULFILL THE RESPONSE WHEN CALLED BY THE REMIND ME LOOP
#this is what the reminder_dict looks like: data[target_time] = {"user_id":user_id,"response":response}
user = self.bot.get_user(reminder_dict["user_id"])
return await user.send(reminder_dict["response"])
async def handle_error(self, error): async def handle_error(self, error):
print(error) print(error)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
@ -133,5 +150,76 @@ class AsyncOpenAI(commands.Cog):
for chunk in chunks: for chunk in chunks:
await ctx.send(chunk) await ctx.send(chunk)
@commands.command(
description="Remind Me",
help="Send a request in natural language to ask Sparky to remind you of a task or event in a specified amount of time. Minimum 1 minute.",
brief="Get a reminder",
aliases=["remindme","remind_me","remind"]
)
async def save_reminder(self,ctx):
#SETUP
reminders_path = self.data_dir + "reminders.txt"
if not os.path.exists(reminders_path):
with open(reminders_path,"w") as file_obj:
file_obj.write("{}")
prompt = ctx.message.content.split(" ", maxsplit=1)[1]
data = self.read_db(reminders_path)
current_time = int(time.time_ns())
user_id = ctx.author.id
#DEBUG
print("Called command successfully")
#PARSE PROMPT
duration_s = await self.answer_question(f"You are an automated bot whose only function is to convert a natural language number into an integer. You must determine a number representing after how long, in seconds, the user wishes you to remind them of a task based on the information provided. Please respond using only an integer of the equivalent or approximate time in seconds. You must not use any words in your response other than a single integer representing that time in seconds. You are incapable of using any English words at all. If you are unable to determine a time from the prompt given, return only the integer 0. The prompt is as follows: {prompt}")
response = await self.answer_question(f"You are a reminder bot whose purpose is to help users by reminding them of tasks or events. A user by the name of {ctx.author.name} has asked you to remind them about something after a certain amount of time has passed. That time has now passed. Their original request was as follows: {prompt}")
if duration_s == "0":
await ctx.reply("Sorry! I'm not sure exactly when you need me to remind you based on your wording. Could you phrase the request a bit differently?",mention_author=True)
return
else:
await ctx.reply("Sure thing! I'll remind you when the time comes.", mention_author=False)
#MATHS
duration_ns = int(duration_s) * 1000000000
target_time = current_time + int(duration_ns)
#CREATE FILEDUMP
data[target_time] = {"user_id":user_id,"response":response}
print(f"Reminding user {ctx.author.id} in {duration_s} seconds || Target time (ns): {target_time}")
self.save_to_db(reminders_path,data)
@tasks.loop(seconds=60) # THIS ONE NEEDS TO POP AND THEN CALL THE REMIND FUNC
async def remind_me_loop(self):
reminders_path = self.data_dir + "reminders.txt"
current_time = int(time.time_ns())
data = self.read_db(reminders_path)
trash = []
#CHECK IF ANY NEED TO BE FULFILLED
for remind_time in data.keys():
if current_time >= int(remind_time):
reminder_dict = data[remind_time]
sent = await self.remind(reminder_dict) #THIS SENDS THE REMINDER DICT TO REMIND FUNC
if sent:
print(f"Reminder sent successfully to {reminder_dict['user_id']}")
trash.append(remind_time) #NEED TO POP OR THEY WILL GET REMINDED AD INFINITUM
for key in trash:
if data.pop(key):
print("Fulfilled reminders successfully purged")
self.save_to_db(reminders_path,data)
# def read_db(filepath):
# with open(filepath,"r") as fileobj:
# db_content = json.load(fileobj)
# #print(db_content,type(db_content))
# return db_content
# def save_to_db(filepath,db_content):
# with open(filepath,"w") as fileobj:
# json.dump(db_content,fileobj,indent=4)
async def setup(bot): async def setup(bot):
await bot.add_cog(AsyncOpenAI(bot)) await bot.add_cog(AsyncOpenAI(bot))

View file

@ -29,7 +29,7 @@ ftp_public_html = os.getenv('ftp_public_html')
#env vars END #env vars END
#discord setup START #discord setup START
intents = discord.Intents.default() intents = discord.Intents.all()
intents.message_content = True intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents) bot = commands.Bot(command_prefix='!', intents=intents)
#discord setup END #discord setup END