Python Script for Data Synchronization Between SmartLead and Crelate Not Working After Heroku Deployment

52 Views Asked by At

I've deployed a Python application on Heroku that's intended to synchronize contact information between SmartLead and Crelate. This synchronization is based on matching emails and phone numbers. Despite a successful deployment, the expected data sync isn't occurring.

Environment:

Deployment platform: Heroku

Job scheduler: Heroku Scheduler

Version control: Connected to a GitHub repository

External Services: SmartLead and Crelate APIs

Expected Behavior: The script should update contacts in Crelate with information fetched from SmartLead campaigns, including details like emails sent.

Current Behavior: The script does not perform the synchronization as expected. No errors are visible on the surface, and the app deployment logs show a successful release.

Steps Already Taken:

Verified that Heroku Scheduler jobs are set up correctly. Confirmed that all necessary API keys and environment variables are present.

Thank you for any assistance you can provide.

This is my code:

import requests
import logging
import json
from datetime import datetime

# Constants for API keys and endpoints
SMARTLEAD_API_KEY = "YOUR_SMARTLEAD_API_KEY"
SMARTLEAD_ENDPOINT = "https://server.smartlead.ai/api/v1/campaigns"
CRELATE_API_KEY = "YOUR_CRELATE_API_KEY"
CRELATE_ENDPOINT = "https://app.crelate.com/api/pub/v1/contacts"

# Setup logging
logging.basicConfig(filename='sync_log.log', level=logging.INFO,
                    format='%(asctime)s:%(levelname)s:%(message)s')

def get_smartlead_campaigns():
    try:
        response = requests.get(SMARTLEAD_ENDPOINT, headers={"Authorization": f"Bearer 
{SMARTLEAD_API_KEY}"})
        response.raise_for_status()  # Will raise an HTTPError if the HTTP request returned an 
unsuccessful status code
        return response.json()
    except requests.exceptions.RequestException as e:
        logging.error(f"Error fetching SmartLead campaigns: {e}")
        return None

def get_crelate_contacts():
    try:
        response = requests.get(CRELATE_ENDPOINT, headers={"Authorization": f"Bearer 
{CRELATE_API_KEY}"})
        if response.status_code == 200:
            try:
                return response.json()
            except json.decoder.JSONDecodeError as e:
                logging.error(f"Error decoding JSON: {e}")
                logging.error(f"Response content: {response.text}")
                return None
        else:
            logging.error(f"Error: Unexpected response {response.status_code}: {response.text}")
            return None
    except requests.exceptions.RequestException as e:
        logging.error(f"Error fetching Crelate contacts: {e}")
        return None

def update_crelate(contact_id, campaign_data):
    try:
        response = requests.put(f"{CRELATE_ENDPOINT}/{contact_id}", json=campaign_data, headers=
{"Authorization": f"Bearer {CRELATE_API_KEY}"})
        response.raise_for_status()
        return True
    except requests.exceptions.RequestException as e:
        logging.error(f"Error updating Crelate contact {contact_id}: {e}")
        return False

def sync_data():
    smartlead_campaigns = get_smartlead_campaigns()
    crelate_contacts = get_crelate_contacts()

    if smartlead_campaigns and crelate_contacts:
        for campaign in smartlead_campaigns['data']:
            for contact in crelate_contacts['data']:
                if contact["email"] == campaign["email"] or contact["phone_number"] ==     
campaign["phone_number"]:
                    campaign_data = {
                        "tasks_completed": campaign["sequences"],
                        "opportunity": campaign["campaign_name"],
                        # Add more fields here as necessary
                    }
                    if update_crelate(contact["id"], campaign_data):
                        logging.info(f"Updated contact {contact['id']} successfully")
                    else:
                        logging.error(f"Failed to update contact {contact['id']}")

def main():
    try:
        logging.info('Starting the synchronization script...')
        sync_data()
    except Exception as e:
        logging.error(f'An error occurred: {e}')
    finally:
        logging.info('The synchronization script has completed running.')

if __name__ == "__main__":
    main()
0

There are 0 best solutions below