Refactor and implement queueing messages

This commit is contained in:
2025-02-12 18:45:21 +00:00
parent 213df9176e
commit 018d2f87c7
23 changed files with 804 additions and 338 deletions

0
core/clients/__init__.py Normal file
View File

79
core/clients/signal.py Normal file
View File

@@ -0,0 +1,79 @@
from rest_framework.views import APIView
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework import status
from django.http import HttpResponse
from core.models import QueuedMessage, Message
import requests
import orjson
from django.conf import settings
from core.messaging import natural
import aiohttp
from asgiref.sync import sync_to_async
async def start_typing(uuid):
url = f"http://signal:8080/v1/typing_indicator/{settings.SIGNAL_NUMBER}"
data = {"recipient": uuid}
async with aiohttp.ClientSession() as session:
async with session.put(url, json=data) as response:
return await response.text() # Optional: Return response content
async def stop_typing(uuid):
url = f"http://signal:8080/v1/typing_indicator/{settings.SIGNAL_NUMBER}"
data = {"recipient": uuid}
async with aiohttp.ClientSession() as session:
async with session.delete(url, json=data) as response:
return await response.text() # Optional: Return response content
async def send_message(db_obj):
recipient_uuid = db_obj.session.identifier.identifier
text = db_obj.text
send = lambda x: send_message_raw(recipient_uuid, x) # returns ts
start_t = lambda: start_typing(recipient_uuid)
stop_t = lambda: stop_typing(recipient_uuid)
tss = await natural.natural_send_message(
text,
send,
start_t,
stop_t,
) # list of ts
#result = await send_message_raw(recipient_uuid, text)
await sync_to_async(db_obj.delete)()
result = [x for x in tss if x] # all trueish ts
if result: # if at least one message was sent
ts1 = result.pop() # pick a time
await sync_to_async(Message.objects.create)(
user=db_obj.session.user,
session=db_obj.session,
custom_author="BOT",
text=text,
ts=ts1, # use that time in db
)
async def send_message_raw(recipient_uuid, text):
url = "http://signal:8080/v2/send"
data = {
"recipients": [recipient_uuid],
"message": text,
"number": settings.SIGNAL_NUMBER,
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as response:
response_text = await response.text()
response_status = response.status
if response_status == status.HTTP_201_CREATED:
ts = orjson.loads(response_text).get("timestamp", None)
if not ts:
return False
return ts
else:
return False