With help from AI, I have managed to create this python script with the intention to be able to import a txt file containing a list of email addresses and append those emails to a newly created group (list). Here’s how it runs:
- The user is asked to input the name of the input file. e.g. test.txt. The file contains a list of emails, one email per line
- The script lists the existing Groups in frontapp and asks the user for the name of the New Group. If the users picks an existing name, the user is asked to choose another name.
- After the user chooses a name for the new group, the script runs a check to see if the emails exist in Frontapp. If it doesn’t exist, it creates a new contact giving it the name “New Contact”.
- The script should then append the existing and new contacts into the New Group
Step four is what I have a problem with. The script does everything, but for some reason, it is failing to append any existing contacts to the New Group. For new contacts however, it works fine and I can see them in the New Group. Can someone help troubleshoot this please?
import csv
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)
try:
apikey = config.get('frontapp', 'api_key')
except:
print("Error: API key not found in config.ini")
# Set the maximum number of API calls per minute
MAX_CALLS_PER_MINUTE = 90
def create_new_contacts(contact_group_id, emails):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {apikey}",
"Accept": "application/json"
}
contact_ids = []
for email in emails:
# Check if the email already exists as a contact in Front
url = f"https://api2.frontapp.com/search?type=contact&q={email}"
response = requests.get(url, headers=headers)
response_json = response.json()
results = response_json.get("_results", [])
if results:
contact_id = results[0]["id"]
contact_ids.append(contact_id) # Add the existing contact ID to the list
continue # Skip the rest of the loop iteration
# Create a new contact
url = "https://api2.frontapp.com/contacts"
data = {
"handles": [
{
"handle": email,
"source": "email"
}
],
"name": f"New Contact"
}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 201:
continue
contact_id = response.json()["id"]
contact_ids.append(contact_id) # Add the new contact ID to the list
# Add the contacts to the contact group
url = f"https://api2.frontapp.com/contact_groups/{contact_group_id}/contacts"
payload = {"contact_ids": contact_ids}
response = requests.post(url, json=payload, headers=headers)
if response.status_code not in (200, 204):
print(f"Failed to add all contacts to the group {contact_group_id}")
print(f"Status code: {response.status_code}")
print(f"Response text: {response.text}")
return False
return True
def read_file(file_path):
emails = []
try:
with open(file_path, 'r') as f:
for line in f:
email = line.strip()
if email:
emails.append(email)
except:
print("Error: Could not open file at the specified path")
return emails
def list_contact_groups():
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {apikey}",
"Accept": "application/json"
}
url = "https://api2.frontapp.com/contact_groups"
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to list contact groups")
print(f"Status code: {response.status_code}")
print(f"Response text: {response.text}")
return []
return response.json()["_results"]
def create_contact_group(name, emails):
# Check if the name is already taken
existing_groups = list_contact_groups()
existing_names = [group["name"] for group in existing_groups]
if name in existing_names:
print(f"A contact group with the name '{name}' already exists")
# Display a list of existing groups
print("Existing contact groups:")
for i, group in enumerate(existing_groups):
print(f"{i + 1}. {group['name']}")
# Prompt the user to choose another name
while True:
new_name = input("Enter a new name for the contact group: ")
if new_name not in existing_names:
name = new_name
break
else:
print(f"A contact group with the name '{new_name}' already exists")
# Create the contact group
url = "https://api2.frontapp.com/contact_groups"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {apikey}",
"Accept": "application/json"
}
data = {"name": name}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 201:
print(f"Failed to create contact group {name}")
print(f"Status code: {response.status_code}")
print(f"Response text: {response.text}")
return None
contact_group = response.json()
# Add contacts to the contact group
contact_group_id = contact_group["id"]
success = create_new_contacts(contact_group_id, emails)
if not success:
print(f"Failed to add all contacts to the group {name}")
return None
return contact_group
def main():
# Read the email addresses from the text file
file_path = input("Enter the path to the file containing the email addresses: ")
emails = read_file(file_path)
if not emails:
print("No valid email addresses found in the file")
return
# Display a list of existing contact groups
existing_groups = list_contact_groups()
if existing_groups:
print("Existing contact groups:")
for i, group in enumerate(existing_groups):
print(f"{i + 1}. {group['name']}")
else:
print("No existing contact groups found")
# Ask the user for a name for the new contact group
while True:
name = input("Enter a name for the new contact group: ")
if not name:
print("Please enter a name for the new contact group")
elif name in [group["name"] for group in existing_groups]:
print(f"A contact group with the name '{name}' already exists")
else:
break
# Create the new contact group and add the contacts to it
contact_group = create_contact_group(name, emails)
if contact_group:
print(f"Successfully created contact group '{name}' with {len(emails)} contacts")
else:
print("Failed to create contact group")
if __name__ == "__main__":
main()
To run the script you’ll need a config.ini file with the api key. Something like this:
[frontapp]
api_key = sdf234rsdfvq34tdafbqafr...........
Best answer by zqush
View original