File size: 2,088 Bytes
b7f929e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import environ
import json
import os
import requests

from datetime import datetime
from supabase import create_client


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env = environ.Env()
env_path = os.path.join(BASE_DIR, '.env')
environ.Env.read_env('.env')

SUPA = create_client(env('SUPABASE_URL'), env('SUPABASE_KEY'))

def log_message_data_through_supabase_api(table_name, log_data):
    return SUPA.table(table_name).insert(log_data).execute()


def format_datetime_in_isoformat(dt):
    return getattr(dt.now(), 'isoformat', lambda x: None)()


def prepare_message_data_for_logging(message_data):
    project_data = {
        'name': "turn.io",
        # Autogenerated fields: id, created_at, modified_at   
    }
    project_data_log = log_message_data_through_supabase_api('project', project_data)
 
    contact_data = {
        'project': project_data_log.data[0]['id'], # FK
        'original_contact_id': message_data['message']['_vnd']['v1']['chat']['contact_uuid'],
        'urn': "",
        'language_code': "en",
        'contact_inserted_at': format_datetime_in_isoformat(datetime.now())
        # Autogenerated fields: id, created_at, modified_at  
    }
    contact_data_log = log_message_data_through_supabase_api('contact', contact_data)

    message_data = {
        'contact': contact_data_log.data[0]['id'], # FK
        'original_message_id': message_data['message']['id'],
        'text': message_data['message']['text']['body'],
        'direction': message_data['message']['_vnd']['v1']['direction'],
        'sender_type': message_data['message']['_vnd']['v1']['author']['type'],
        'channel_type': "whatsapp / turn.io",
        'message_inserted_at': message_data['message']['_vnd']['v1']['chat']['inserted_at'],
        'message_modified_at': message_data['message']['_vnd']['v1']['chat']['updated_at'],
        'message_sent_at': format_datetime_in_isoformat(datetime.now())
        # Autogenerated fields: created_at, modified_at   
    }
    message_data_log = log_message_data_through_supabase_api('message', message_data)