From 23c36f13ce6e734706019e42954bbac133aeea77 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Sun, 10 Nov 2024 20:10:20 +0530 Subject: [PATCH] Update vcf_gen.py --- vcf_gen.py | 71 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 19 deletions(-) diff --git a/vcf_gen.py b/vcf_gen.py index 44468ed..65fe6f8 100644 --- a/vcf_gen.py +++ b/vcf_gen.py @@ -1,24 +1,57 @@ import os +import pandas as pd +from typing import List, Optional -numbers = [] -group_name = input("Enter the group name: ") +def validate_phone_number(number: str) -> bool: + """Validate if number contains only digits and has appropriate length.""" + cleaned = ''.join(filter(str.isdigit, str(number))) + return len(cleaned) >= 10 and cleaned.isdigit() -while True: - number = input("Enter a phone number (or press Enter to finish): ") - if number == "": - break - numbers.append(number) +def create_vcf_contacts(excel_path: str, group_name: str = "Contacts") -> Optional[str]: + """Create VCF file from Excel containing phone numbers.""" + try: + # Check if file exists + if not os.path.exists(excel_path): + raise FileNotFoundError(f"Excel file not found: {excel_path}") -filename = f"{group_name}_contacts.vcf" -with open(filename, 'w') as f: - for i, number in enumerate(numbers, start=1): - f.write("BEGIN:VCARD\n") - f.write("VERSION:3.0\n") - f.write(f"N:{group_name}_{i:03d};;;\n") - f.write(f"FN:{group_name}_{i:03d}\n") - f.write(f"TEL;TYPE=CELL:+91{number}\n") - f.write(f"X-WhatsApp-Group:{group_name}\n") # Add WhatsApp group tag - f.write("END:VCARD\n\n") + # Read phone numbers from first column of Excel file + df = pd.read_excel(excel_path) + if df.empty: + raise ValueError("Excel file is empty") -print(f"A single VCF file '{filename}' with {len(numbers)} contacts has been created in the current directory.") -print(f"These contacts are tagged for easy addition to a WhatsApp group named '{group_name}'.") \ No newline at end of file + numbers = df.iloc[:, 0].astype(str).tolist() + filename = f"{group_name}_contacts.vcf" + + valid_numbers = 0 + skipped_numbers = 0 + + with open(filename, 'w') as f: + for i, number in enumerate(numbers, start=1): + if not validate_phone_number(number) or not number.isdigit(): + skipped_numbers += 1 + continue + + try: + f.write("BEGIN:VCARD\n") + f.write("VERSION:3.0\n") + f.write(f"N:{group_name}_{i:03d};;;\n") + f.write(f"FN:{group_name}_{i:03d}\n") + f.write(f"TEL;TYPE=CELL:+91{number}\n") + f.write(f"X-WhatsApp-Group:{group_name}\n") + f.write("END:VCARD\n\n") + valid_numbers += 1 + except IOError: + raise + + return filename + + except pd.errors.EmptyDataError: + raise + except Exception: + raise + +if __name__ == "__main__": + try: + created_file = create_vcf_contacts('numbers.xlsx') + except Exception as e: + print(f"Failed to create contacts file: {str(e)}") \ No newline at end of file