#!/usr/bin/env python3 """ Setup script for initializing and managing user mappings Run this after adding new users to create readable mappings """ import sys from pathlib import Path from user_mapping import get_user_mapper from config_multi_user import SLACK_USER_IDS, BASE_DIR from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from config_multi_user import SLACK_BOT_TOKEN def setup_all_users(): """Initialize all user mappings and create directory""" print("=" * 60) print("SLACK USER SETUP - INITIALIZING USER MAPPINGS") print("=" * 60) print() if not SLACK_USER_IDS: print("āŒ No users configured in .env file!") print(" Add SLACK_USER_IDS=U-ID1,U-ID2,... to your .env file") return False print(f"šŸ“‹ Found {len(SLACK_USER_IDS)} users to set up") print() # Initialize mapper mapper = get_user_mapper() # Test Slack connection client = WebClient(token=SLACK_BOT_TOKEN) try: auth = client.auth_test() print(f"āœ… Connected to Slack workspace: {auth['team']}") print() except SlackApiError as e: print(f"āŒ Failed to connect to Slack: {e}") return False # Fetch and display all users print("Fetching user information from Slack...") print("-" * 60) success_count = 0 failed_users = [] for i, user_id in enumerate(SLACK_USER_IDS, 1): try: print(f"\n[{i}/{len(SLACK_USER_IDS)}] Processing {user_id}...") # Fetch user info user_info = mapper.update_user(user_id, force_update=True) if user_info: print(f" āœ… Name: {user_info['full_name']}") print(f" Email: {user_info.get('email', 'N/A')}") print(f" Title: {user_info.get('title', 'N/A')}") print(f" Display: @{user_info.get('slack_handle', 'N/A')}") print(f" File name: {user_info['sanitized_name']}_*.csv") success_count += 1 else: print(f" āŒ Failed to fetch user information") failed_users.append(user_id) except Exception as e: print(f" āŒ Error: {e}") failed_users.append(user_id) print("\n" + "=" * 60) print("SUMMARY") print("=" * 60) print(f"āœ… Successfully set up: {success_count}/{len(SLACK_USER_IDS)} users") if failed_users: print(f"āŒ Failed users: {', '.join(failed_users)}") print("\nPossible reasons for failures:") print(" - User ID is incorrect") print(" - User has been deactivated") print(" - Bot doesn't have permission to view user") # Show file structure print("\n" + "=" * 60) print("FILE STRUCTURE PREVIEW") print("=" * 60) print("\nYour data files will be organized as:") print() print("data/raw/") for user_id in SLACK_USER_IDS[:5]: # Show first 5 as example info = mapper.get_user_info(user_id) print(f" ā”œā”€ā”€ {info['sanitized_name']}_2025-01-20.csv") if len(SLACK_USER_IDS) > 5: print(f" └── ... ({len(SLACK_USER_IDS) - 5} more users)") print("\ndata/summaries/") print(" ā”œā”€ā”€ team_summary.csv (all users combined)") print(" ā”œā”€ā”€ team_weekly.csv") print(" └── team_monthly.csv") # Create custom data template print("\n" + "=" * 60) print("CUSTOM DATA TEMPLATE") print("=" * 60) template_file = BASE_DIR / "user_custom_template.csv" print("\nCreating template for adding custom user data...") try: import csv with open(template_file, 'w', newline='') as f: fieldnames = ['user_id', 'department', 'team', 'manager', 'location', 'notes'] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() # Add all users as template for user_id in SLACK_USER_IDS: info = mapper.get_user_info(user_id) writer.writerow({ 'user_id': user_id, 'department': '', 'team': '', 'manager': '', 'location': '', 'notes': f"# {info['full_name']}" }) print(f"āœ… Created template: {template_file}") print("\nšŸ“ To add custom data (department, team, etc.):") print(f" 1. Edit: {template_file}") print(" 2. Fill in the custom fields") print(" 3. Run: python3 user_mapping.py --import-csv user_custom_template.csv") except Exception as e: print(f"āŒ Failed to create template: {e}") # Show directory files print("\n" + "=" * 60) print("USER DIRECTORY FILES") print("=" * 60) print(f"\nšŸ“ User mappings saved to:") print(f" JSON: {BASE_DIR / 'user_mappings.json'}") print(f" CSV: {BASE_DIR / 'user_directory.csv'}") print("\nYou can open user_directory.csv in Excel to view all users") return success_count > 0 def show_user_summary(): """Display a summary of all tracked users""" mapper = get_user_mapper() print("\n" + "=" * 60) print("CURRENT USER ROSTER") print("=" * 60) if not mapper.user_map: print("No users mapped yet. Run setup first!") return print(f"\nTotal users tracked: {len(mapper.user_map)}") print("\n" + "-" * 60) print(f"{'#':<3} {'Name':<25} {'Email':<30} {'Dept':<15}") print("-" * 60) for i, (user_id, info) in enumerate(sorted(mapper.user_map.items(), key=lambda x: x[1].get('full_name', '')), 1): name = info['full_name'][:24] email = info.get('email', '')[:29] dept = info.get('department', '')[:14] print(f"{i:<3} {name:<25} {email:<30} {dept:<15}") print("-" * 60) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Setup and manage tracked users') parser.add_argument('--setup', action='store_true', help='Initialize all users from .env') parser.add_argument('--summary', action='store_true', help='Show summary of tracked users') parser.add_argument('--refresh', action='store_true', help='Refresh all user data from Slack') args = parser.parse_args() if args.setup or args.refresh: success = setup_all_users() if success: show_user_summary() sys.exit(0 if success else 1) elif args.summary: show_user_summary() else: # Default action print("User Setup Utility") print("-" * 40) print("Options:") print(" --setup Initialize all users") print(" --summary Show current users") print(" --refresh Update user data") print("\nExample: python3 setup_users.py --setup")