Files
medods_crz/medods.py
T
2025-08-05 12:29:53 +03:00

106 lines
3.1 KiB
Python

from datetime import datetime
import logging
import os
import config
import json
from aiohttp import ClientSession
import aiohttp
def loggingDict(title: str, data: dict, call_id: str) -> None:
today = datetime.now().strftime("%Y-%m-%d")
file_name = f"log/{today}/{call_id}.log"
if not os.path.exists(f"log/{today}"):
os.makedirs(f"log/{today}")
with open(file_name, "a") as f:
f.write(f"{title}:\n{json.dumps(data, indent=4)}\n\n")
async def send_post_request(body: dict):
async def post_request(
url: str,
headers: dict = None,
json: dict = None,
**kwargs,
):
try:
async with ClientSession() as session:
async with session.post(
url, json=json, headers=headers, **kwargs
) as response:
response.raise_for_status()
return await response.json()
except aiohttp.ClientError as e:
if config.DEBUG:
logging.error(f"Request failed: {str(e)}")
return None
call_id = body["call_session_id"]
data = {"call": body}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {config.MEDODS_TOKEN}",
}
if config.DEBUG:
loggingDict("Sending data to Medods", data, call_id)
r = await post_request(url=config.MEDODS_SERVER, headers=headers, json=data)
try:
res = {
"id": r["call"]["id"],
"status": r["call"]["status"],
"call_session_id": r["call"]["call_session_id"],
}
except:
res = {}
loggingDict("Recieved data from Medods:", res, call_id)
else:
await post_request(url=config.MEDODS_SERVER, headers=headers, json=data)
async def incoming_call(call_session_id, contact_phone_number, called_phone_number):
body = {
"status": "incoming_call",
"call_session_id": call_session_id,
"contact_phone_number": contact_phone_number,
"called_phone_number": called_phone_number,
}
await send_post_request(body)
async def call_started(call_session_id):
body = {
"status": "call_started",
"call_session_id": call_session_id,
"responsibles": [{"id": 777}],
}
await send_post_request(body)
async def call_finished(call_session_id, duration):
body = {
"status": "call_finished",
"call_session_id": call_session_id,
"duration": duration,
}
await send_post_request(body)
async def call_lost(call_session_id):
body = {
"status": "call_lost",
"call_session_id": call_session_id,
"responsibles": [{"id": 777}],
}
await send_post_request(body)
async def call_record_file(call_session_id, uniqueid):
body = {
"status": "call_record_file",
"call_session_id": call_session_id,
"file_link": f"{config.RECORDS_SERVER}{uniqueid}",
}
await send_post_request(body)