2024-04-06 23:51:14 +02:00
|
|
|
import redis.asyncio as redis
|
2024-04-07 22:22:07 +02:00
|
|
|
import aiohttp
|
2024-04-06 23:51:14 +02:00
|
|
|
import json
|
|
|
|
|
|
|
|
class History():
|
|
|
|
r: redis.Redis()
|
2024-04-07 22:22:07 +02:00
|
|
|
haste_url: ""
|
2024-04-06 23:51:14 +02:00
|
|
|
|
2024-04-07 22:22:07 +02:00
|
|
|
def __init__(self, redis_host, redis_port, haste_url):
|
2024-04-06 23:51:14 +02:00
|
|
|
self.r = redis.Redis(host=redis_host, port=redis_port, db=0)
|
2024-04-07 22:22:07 +02:00
|
|
|
self.haste_url = haste_url
|
2024-04-06 23:51:14 +02:00
|
|
|
|
|
|
|
def createCacheKey(self, id):
|
|
|
|
return f"gpt-history-user-{id}"
|
|
|
|
|
|
|
|
async def reset(self, userData):
|
2024-04-08 23:25:00 +02:00
|
|
|
key = self.createCacheKey(userData["sender"] + userData["room_id"])
|
2024-04-06 23:51:14 +02:00
|
|
|
await self.r.mset(key, null)
|
|
|
|
|
|
|
|
async def get(self, userData):
|
2024-04-08 23:25:00 +02:00
|
|
|
key = self.createCacheKey(userData["sender"] + userData["room_id"])
|
2024-04-06 23:51:14 +02:00
|
|
|
history = await self.r.get(key)
|
|
|
|
|
|
|
|
if history is not None:
|
|
|
|
history = json.loads(history)
|
|
|
|
return history
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
async def add(self, userData, userMessage, assistantMessage):
|
|
|
|
history = await self.get(userData)
|
|
|
|
history.append({ "role": "user", "content": userMessage })
|
|
|
|
history.append({ "role": "assistant", "content": assistantMessage })
|
|
|
|
|
2024-04-08 23:25:00 +02:00
|
|
|
key = self.createCacheKey(userData["sender"] + userData["room_id"])
|
2024-04-06 23:51:14 +02:00
|
|
|
history = json.dumps(history)
|
|
|
|
await self.r.psetex(key, 300_000, history) # 5 mins
|
|
|
|
|
|
|
|
async def dump(self, userData):
|
|
|
|
history = await self.get(userData)
|
|
|
|
if (len(history) == 0):
|
|
|
|
return "You have no ChatGPT history at the moment."
|
2024-04-07 17:52:05 +02:00
|
|
|
|
|
|
|
text = ""
|
|
|
|
for i in range(0, len(history), 2):
|
|
|
|
text += f"You: {history[i]['content']}\nGPT: {history[i+1]['content']}\n\n"
|
|
|
|
|
2024-04-07 22:22:07 +02:00
|
|
|
async with aiohttp.request("POST", self.haste_url, data=text) as response:
|
|
|
|
if response.status != 200:
|
|
|
|
return "Could not export the ChatGPT history! Please try again later!"
|
|
|
|
else:
|
|
|
|
haste = await response.json()
|
|
|
|
msg = "Your ChatGPT history: https://haste.snrd.eu/raw/{}".format(haste["key"])
|
|
|
|
return msg
|