1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/keipack/stars/api_kei.py

59 lines
2.1 KiB
Python
Raw Normal View History

2019-11-29 20:18:01 +00:00
import random
import datetime
from typing import *
2019-11-11 12:40:26 +00:00
from starlette.requests import Request
from starlette.responses import *
2019-11-29 20:18:01 +00:00
from royalnet.constellation import *
2019-11-11 12:40:26 +00:00
from royalnet.utils import *
2019-11-29 23:45:41 +00:00
from ..tables import *
2019-12-09 01:22:29 +00:00
from ..utils import *
2019-11-11 12:40:26 +00:00
class ApiKei(PageStar):
path = "/api/kei"
2019-11-29 23:45:41 +00:00
methods = ["POST"]
2019-12-09 01:22:29 +00:00
def __init__(self, config: Dict[str, Any], constellation: "Constellation"):
super().__init__(config, constellation)
self._conversations: Dict[str, Conversation] = {}
2019-11-11 12:40:26 +00:00
async def page(self, request: Request) -> JSONResponse:
async with self.session_acm() as session:
2019-11-29 23:45:41 +00:00
form = await request.form()
2019-12-09 01:22:29 +00:00
kpid = form["kpid"]
convid = form["convid"]
message = form.get("message")
first = form.get("first", False)
person = await asyncify(session.query(self.alchemy.get(KeiPerson)).filter_by(kpid=kpid).one_or_none)
2019-11-29 23:45:41 +00:00
if person is None:
2019-12-09 01:22:29 +00:00
person = self.alchemy.get(KeiPerson)(kpid=kpid)
2019-11-29 23:45:41 +00:00
session.add(person)
2019-12-09 01:22:29 +00:00
message = self.alchemy.get(KeiMessage)(kei_person=person, message=message)
2019-11-29 23:45:41 +00:00
session.add(message)
await asyncify(session.commit)
2019-12-09 01:22:29 +00:00
# Find conversation
while True:
if convid not in self._conversations:
# Create a new conversation
self._conversations[convid] = await ExampleConversation.create()
conv: Conversation = self._conversations[convid]
try:
emotion, text = await conv.next(session=session, person=person, message=message)
except StopAsyncIteration:
del self._conversations[convid]
continue
except Exception as e:
print(e)
emotion, text = Emotion.NEUTRAL, "...?"
else:
break
2019-11-11 12:40:26 +00:00
return JSONResponse({
2019-11-29 23:45:41 +00:00
"emotion": str(emotion),
2019-11-11 12:40:26 +00:00
"text": text,
2019-12-09 01:22:29 +00:00
}, headers={
"Access-Control-Allow-Origin": "https://kei.steffo.eu",
2019-11-11 12:40:26 +00:00
})