|
| 1 | +import csv |
| 2 | +import os |
| 3 | +from urllib.parse import urljoin |
| 4 | + |
| 5 | +import requests |
| 6 | +from fetch_rapidpro_contacts import FIELD_MAPPING |
| 7 | +from temba_client.v2 import TembaClient |
| 8 | + |
| 9 | +RAPIDPRO_URL = "https://rapidpro.qa.momconnect.co.za" |
| 10 | +TURN_URL = "https://whatsapp-praekelt-cloud.turn.io" |
| 11 | + |
| 12 | +WA_IDS = ["27836378531"] |
| 13 | + |
| 14 | +rapidpro_client = TembaClient(RAPIDPRO_URL, os.environ["RAPIDPRO_TOKEN"]) |
| 15 | + |
| 16 | + |
| 17 | +def get_rapidpro_contact(wa_id): |
| 18 | + urn = f"whatsapp:{wa_id}" |
| 19 | + contact = rapidpro_client.get_contacts(urn=urn).first(retry_on_rate_exceed=True) |
| 20 | + data = {} |
| 21 | + |
| 22 | + for rapidpro_field, turn_details in FIELD_MAPPING.items(): |
| 23 | + if turn_details["type"] == "default": |
| 24 | + data[rapidpro_field] = getattr(contact, rapidpro_field) |
| 25 | + else: |
| 26 | + data[rapidpro_field] = contact.fields[rapidpro_field] |
| 27 | + |
| 28 | + return data |
| 29 | + |
| 30 | + |
| 31 | +def get_turn_contact(wa_id): |
| 32 | + headers = { |
| 33 | + "Authorization": "Bearer {}".format(os.environ["TURN_TOKEN"]), |
| 34 | + "content-type": "application/json", |
| 35 | + "Accept": "application/vnd.v1+json", |
| 36 | + } |
| 37 | + response = requests.get( |
| 38 | + urljoin(TURN_URL, "/v1/contacts/{}/profile".format(wa_id)), |
| 39 | + headers=headers, |
| 40 | + ) |
| 41 | + contact = response.json()["fields"] |
| 42 | + |
| 43 | + data = {} |
| 44 | + for rapidpro_field, turn_details in FIELD_MAPPING.items(): |
| 45 | + data[rapidpro_field] = contact[turn_details["turn_name"]] |
| 46 | + return data |
| 47 | + |
| 48 | + |
| 49 | +def compare_contacts(): |
| 50 | + rows = [] |
| 51 | + for wa_id in WA_IDS: |
| 52 | + rapidpro_data = get_rapidpro_contact(wa_id) |
| 53 | + turn_data = get_turn_contact(wa_id) |
| 54 | + |
| 55 | + row = {"wa_id": wa_id} |
| 56 | + for rapidpro_field in FIELD_MAPPING.keys(): |
| 57 | + row[f"RP {rapidpro_field}"] = rapidpro_data[rapidpro_field] |
| 58 | + row[f"TURN {rapidpro_field}"] = turn_data[rapidpro_field] |
| 59 | + |
| 60 | + rows.append(row) |
| 61 | + |
| 62 | + with open("compare.csv", "w", encoding="utf-8") as f: |
| 63 | + fieldnames = rows[0].keys() |
| 64 | + writer = csv.DictWriter(f, fieldnames=fieldnames) |
| 65 | + writer.writeheader() |
| 66 | + writer.writerows(rows) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + compare_contacts() |
0 commit comments