Solved

Python code to create a duplicate of a List

  • 29 March 2023
  • 2 replies
  • 22 views

Badge +1
import requestsimport configparserimport os# Read API key from config.iniconfig = configparser.ConfigParser()config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')config.read(config_path)apikey = config.get('frontapp', 'api_key')def list_contact_groups():    url = "https://api2.frontapp.com/contact_groups"    headers = {        "accept": "application/json",        "authorization": f"Bearer {apikey}"    }    response = requests.get(url, headers=headers)    if response.status_code == 200:        return response.json().get('_results', [])    else:        raise Exception(f"Failed to fetch contact groups. Status code: {response.status_code}, Response text: {response.text}")def get_contacts_from_group(group_id):    url = f"https://api2.frontapp.com/contact_groups/{group_id}/contacts?limit=100"    headers = {        "accept": "application/json",        "authorization": f"Bearer {apikey}"    }    response = requests.get(url, headers=headers)    if response.status_code == 200:        return response.json()["_results"]    else:        raise Exception(f"Failed to fetch contacts from group {group_id}. Status code: {response.status_code}, Response text: {response.text}")def add_contacts_to_group(new_group_id, contacts):    url = f"https://api2.frontapp.com/contact_groups/{new_group_id}/contacts"    contact_ids = [contact["id"] for contact in contacts]    payload = {"contact_ids": contact_ids}    headers = {        "content-type": "application/json",        "authorization": f"Bearer {apikey}"    }    response = requests.post(url, json=payload, headers=headers)    if response.status_code not in (200, 204):        print(f"Failed to add contacts to the group {new_group_id}")        print(f"Status code: {response.status_code}")        print(f"Response text: {response.text}")    else:        print(f"Successfully added contacts to the group {new_group_id}")def generate_duplicate_group_name(name, groups):    base_name = name    count = 1    new_name = f"{base_name} (Duplicate {count})"    existing_names = [group["name"] for group in groups]    while new_name in existing_names:        count += 1        new_name = f"{base_name} (Duplicate {count})"    return new_namedef duplicate_contact_group(group_id, group_name):    # Get contacts from the original group    original_group_contacts = get_contacts_from_group(group_id)    # Generate a name for the duplicate group    groups = list_contact_groups()    new_group_name = generate_duplicate_group_name(group_name, groups)    # Create the duplicate group    url = "https://api2.frontapp.com/contact_groups"    headers = {        "accept": "application/json",        "authorization": f"Bearer {apikey}",        "content-type": "application/json",    }    data = {"name": new_group_name}    response = requests.post(url, headers=headers, json=data)    if response.status_code != 201:        print(f"Failed to create contact group {new_group_name}")        print(f"Status code: {response.status_code}")        print(f"Response text: {response.text}")        return None    duplicate_group = response.json()    # Add contacts to the duplicate group    add_contacts_to_group(duplicate_group["id"], original_group_contacts)    return duplicate_groupdef main():    # List all the contact groups and ask the user to select one    groups = list_contact_groups()    print("Contact Groups:")    for i, group in enumerate(groups):        print(f"{i + 1}. {group['name']}")    selected_group_number = int(input("Enter the number of the contact group you want to duplicate: "))    selected_group = groups[selected_group_number - 1]    print(f"Selected Contact Group: {selected_group['name']}")    # Duplicate the selected contact group    duplicated_group = duplicate_contact_group(selected_group.get('id'), selected_group.get('name'))    # Display a message confirming the successful duplication of the contact group    if duplicated_group:        print(f"Successfully duplicated contact group '{selected_group['name']}' as '{duplicated_group['name']}'")    else:        print("Failed to duplicate contact group")if __name__ == "__main__":    main()
icon

Best answer by zqush 3 April 2023, 18:34

View original

2 replies

Userlevel 3
Badge +8

Thank you for sharing this code, Ziad! It will certainly help other developers building with Python.

Badge +1

let me try that once again with better formatting :-)

 

import requests
import configparser
import os
import time

# Read API key from config.ini
config = configparser.ConfigParser()
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')
config.read(config_path)
apikey = config.get('frontapp', 'api_key')


def list_contact_groups():
url = "https://api2.frontapp.com/contact_groups"
headers = {
"accept": "application/json",
"authorization": f"Bearer {apikey}"
}

response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json().get('_results', [])
else:
raise Exception(f"Failed to fetch contact groups. Status code: {response.status_code}, Response text: {response.text}")


def get_contacts_from_group(group_id):
url = f"https://api2.frontapp.com/contact_groups/{group_id}/contacts?limit=100"
headers = {
"accept": "application/json",
"authorization": f"Bearer {apikey}"
}

response = requests.get(url, headers=headers)
response_json = response.json()
contacts = response_json["_results"]

# Check if there are more pages of contacts to retrieve
while response_json.get("_pagination", {}).get("next"):
url = response_json["_pagination"]["next"]

# Limit the rate of API calls to 1 call per second
time_since_last_call = time.time() - get_contacts_from_group.last_call_time
if time_since_last_call < 1:
time.sleep(1 - time_since_last_call)
get_contacts_from_group.last_call_time = time.time()

response = requests.get(url, headers=headers)
response_json = response.json()
contacts.extend(response_json["_results"])

return contacts

# Set the initial value of last_call_time to the current time
get_contacts_from_group.last_call_time = time.time()

def add_contacts_to_group(new_group_id, contacts):
url = f"https://api2.frontapp.com/contact_groups/{new_group_id}/contacts"
contact_ids = [contact["id"] for contact in contacts]
payload = {"contact_ids": contact_ids}
headers = {
"content-type": "application/json",
"authorization": f"Bearer {apikey}"
}

response = requests.post(url, json=payload, headers=headers)

if response.status_code not in (200, 204):
print(f"Failed to add contacts to the group {new_group_id}")
print(f"Status code: {response.status_code}")
print(f"Response text: {response.text}")
else:
print(f"Successfully added contacts to the group {new_group_id}")



def generate_duplicate_group_name(name, groups):
base_name = name
count = 1
new_name = f"{base_name} (Duplicate {count})"
existing_names = [group["name"] for group in groups]

while new_name in existing_names:
count += 1
new_name = f"{base_name} (Duplicate {count})"
return new_name

def duplicate_contact_group(group_id, group_name):
# Get contacts from the original group
original_group_contacts = get_contacts_from_group(group_id)

# Generate a name for the duplicate group
groups = list_contact_groups()
new_group_name = generate_duplicate_group_name(group_name, groups)

# Create the duplicate group
url = "https://api2.frontapp.com/contact_groups"
headers = {
"accept": "application/json",
"authorization": f"Bearer {apikey}",
"content-type": "application/json",
}
data = {"name": new_group_name}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 201:
print(f"Failed to create contact group {new_group_name}")
print(f"Status code: {response.status_code}")
print(f"Response text: {response.text}")
return None

duplicate_group = response.json()

# Add contacts to the duplicate group
add_contacts_to_group(duplicate_group["id"], original_group_contacts)

return duplicate_group


def main():
# List all the contact groups and ask the user to select one
groups = list_contact_groups()
print("Contact Groups:")
for i, group in enumerate(groups):
print(f"{i + 1}. {group['name']}")
selected_group_number = int(input("Enter the number of the contact group you want to duplicate: "))
selected_group = groups[selected_group_number - 1]
print(f"Selected Contact Group: {selected_group['name']}")

# Duplicate the selected contact group
duplicated_group = duplicate_contact_group(selected_group.get('id'), selected_group.get('name'))

# Display a message confirming the successful duplication of the contact group
if duplicated_group:
print(f"Successfully duplicated contact group '{selected_group['name']}' as '{duplicated_group['name']}'")
else:
print("Failed to duplicate contact group")

if __name__ == "__main__":
main()

and the config.ini file should look something like this:

[frontapp]
api_key = eyasdfweiOi23uio897sljclkjasd............

of course you’ll need to put in your own api key. 

Reply