Delete inactive members

Hi everyone,

I’ve created a Python script named delete_fabman_members.py that can be useful for Fabman account administrators. This script helps you identify and manage members based on their activity status in your Fabman account.

What the Script Does:

  • Identifies Inactive Members: The script lists members who haven’t had any activity since a specific date you set.
  • Option to Delete Members: If you choose, the script can also delete these inactive members. This is a permanent action, so use it carefully.

Installation and Usage:

Requirements:

  • Python installed on your system (3.6 or later recommended).
  • requests library installed (install via pip: pip install requests).

Steps to Use:

  1. Copy the Code below and save the Script: Save it as delete_fabman_members.py to your computer.
  2. Prepare to Run: Ensure Python and requests are installed.
  3. Configure the Script:
  • Open the script in a text editor.
  • Set your Fabman API key, account ID, and the threshold date for detecting inactivity directly in the script.
  • There’s a delete variable in the script. Set it to True if you want to delete the inactive members. Be cautious with this.
  1. Run the Script:
  • Open a command prompt or terminal.
  • Navigate to the folder where the script is saved.
  • Run the script: python delete_fabman_members.py.

Notes:

  • Always Backup First: It’s a good idea to backup your member data before running any scripts that might alter it.
  • Test Before Using: Test the script in a safe environment before using it on your live Fabman account.

This script was created to help manage member databases more efficiently. I hope you find it helpful, and I’m open to any feedback or improvements you might have.

Code:

import requests
import datetime

def get_fabman_data(base_url, api_key, endpoint, account_id):
    headers = {"Authorization": f"Bearer {api_key}"}

    endpoint = f"/api/v1/{endpoint}?account={account_id}&limit=500"
    
    all_data = []
    while True:
        response = requests.get(base_url + endpoint, headers=headers)
        if response.status_code != 200:
            print(f"Error: {response.status_code}")
            break

        all_data.extend(response.json())

        # Pagination - follow the Link header if present
        link_header = response.headers.get('Link')
        if not link_header or 'rel="next"' not in link_header:
            break  # No more pages
        next_link = link_header.split(';')[0].strip('<>')
        endpoint = next_link.replace(base_url, '')  # Update endpoint for the next page

    return all_data

def filter_members_by_last_activity(base_url, api_key, account_id, threshold_date_str):
    members = get_fabman_data(base_url, api_key, "members", account_id=account_id)
    if isinstance(members, str):
        print(members)
        return

    # Convert the threshold date string to a datetime object
    threshold_date = datetime.datetime.strptime(threshold_date_str, '%Y-%m-%d')

    inactive_members = []
    for member in members:
        last_activity_info = member.get('lastActivity')
        if last_activity_info and 'at' in last_activity_info:
            last_activity_date = datetime.datetime.fromisoformat(last_activity_info['at'])
            if last_activity_date.date() < threshold_date.date():
                inactive_members.append(member)
        else:
            inactive_members.append(member)

    return inactive_members

def delete_member(base_url, api_key, member_id):
    headers = {"Authorization": f"Bearer {api_key}"}
    
    response = requests.delete(f"{base_url}/api/v1/members/{member_id}", headers=headers)
    return response.status_code

base_url = "https://fabman.io"
api_key = "API-KEY"
account_id = XXX
threshold_date = "2020-01-01"  # Replace with your desired threshold date
delete = False # Set to true if you really want to delete the members. 

# Get members with no activity after the specified threshold date
inactive_members = filter_members_by_last_activity(base_url, api_key, account_id, threshold_date)

# Print names and email addresses of inactive members
for member in inactive_members:
    name = f"{member.get('firstName', '')} {member.get('lastName', '')}".strip()
    email = member.get('emailAddress', 'No email provided')

    if delete: 
        response_code = delete_member(base_url, api_key, member['id'])
        if response_code >= 200 and response_code <= 299:
            print(f"Deleted member: ID: {member['id']} Name: {name} Email: {email}")
        else:
            print(f"Delete failed: ID: {member['id']} Name: {name} Email: {email}")
    else: 
        print(f"ID: {member['id']} Name: {name} Email: {email}")

print("total members: " + str(len(inactive_members)))
1 Like