import re
from pprint import pprint
def split_user_name(username):
name_regex = re.compile('^(?P<first_name>[^ ]*) ?(?P<last_name>.*)$')
return name_regex.match(username).groupdict()
def upsert_user(data, tenant, user=None):
client_id = data.get('to')
user_data = data.get('messages')[0]
user_info = {
'username': data['contacts'][user_data['from']].get('name')
if 'contacts' in data.keys() else user_data['from'],
'phone_number': user_data.get('from'),
'ext_identifier': f'{user_data["from"]}_{client_id}'
}
if not user:
user_info.update(**split_user_name(user_info.get('username', '')))
print(user_info)
else:
first_last_name = split_user_name(user_info.get('username', ''))
print(first_last_name.get('first_name'))
print(first_last_name.get('last_name'))
print(user_info.get('username', None))
return user
def _convert_contacts(contact_data):
return {c.get('wa_id'): c.get('profile') for c in contact_data}
def _get_first_message_schedule_remaining(data):
if len(data.get('messages', [])) > 0:
first_message = {'messages': [data['messages'].pop(0)]}
elif len(data.get('statusses', [])) > 0:
first_message = {'statusses': [data['statusses'].pop(0)]}
else:
logger.info('Multiple messages list incorrectly handled.')
logger.debug(data)
first_message = {}
if (len(data.get('messages', [])) + len(data.get('statusses', []))) > 0:
# pprint(data)
upsert_user(data, 'TENANT1')
upsert_user(data, 'TENANT1', 'USER1')
return first_message
def split_multiple_messages(data):
if isinstance(data.get('contacts'), list):
data['contacts'] = _convert_contacts(data['contacts'])
if (len(data.get('messages', [])) + len(data.get('statusses', []))) > 1:
single_data = {'contacts': data['contacts'], }
single_data.update(
_get_first_message_schedule_remaining(data))
# pprint(single_data)
upsert_user(single_data, 'TENANT1')
upsert_user(single_data, 'TENANT1', 'USER1')
return single_data
print('ASYNC')
print(data)
return data
def inbound(data):
"""
:param data:
:return:
"""
split_multiple_messages(data)
inbound({
"contacts": [
{
"profile": {
"name": "Sinterklaas"
},
"wa_id": "31612348878"
},
{
"profile": {
"name": "en Piet"
},
"wa_id": "31687884321"
}
],
"messages": [
{
"from": "31687884321",
"id": "ABDDMWUTkIl_Bo6u9GkRZ9LgEsG",
"text": {
"body": "Testmessage 88 van Piet"
},
"timestamp": "1575285446",
"type": "text"
},
{
"from": "31612348878",
"id": "ABEEWUTkIl_Bgo6uGDvZ9LgEsG",
"text": {
"body": "Testmessage 88 van Sinterklaas"
},
"timestamp": "1575285446",
"type": "text"
}
]
})