Successfully logged in to MEGA
folders found: ('8JwhQZ6L', {'h': '8JwhQZ6L', 'p': 'VZxkxQIC', 'u': 'o2NJYuj19cE', 't': 1, 'a': {'n': 'MyUploadedFolder'}, 'k': (3536844887, 717724422, 524814171, 2747771409), 'ts': 1729358868, 'key': (3536844887, 717724422, 524814171, 2747771409)})
Found existing root folder 'MyUploadedFolder' on MEGA
Uploading: Screenshot 2024-02-04 at 12.06.46 PM.png
Successfully uploaded: Screenshot 2024-02-04 at 12.06.46 PM.png
Uploading: .DS_Store
Successfully uploaded: .DS_Store
Created folder: GitHub Pages
Uploading: index.html
An error occurred: module 'mega.errors' has no attribute 'GenericMegaException'
import os
import time
from mega import Mega, errors

def create_folder(mega_client, parent_handle, folder_name):
    """
    Creates a folder in the specified parent folder on MEGA.

    Args:
        mega_client (Mega): The MEGA client instance.
        parent_handle (str): The handle of the parent folder.
        folder_name (str): The name of the folder to create.

    Returns:
        str or None: The handle of the created folder, or None if failed.
    """
    try:
        # Create the folder within the parent folder by passing the parent handle
        folder_handle = mega_client.create_folder(folder_name, parent_handle)
        print(f"Created folder: {folder_name}")
        time.sleep(2)  # Wait for 2 seconds after creating a folder
        return folder_handle
    except errors.GenericMegaException as e:
        print(f"Error creating folder '{folder_name}': {e}")
    except Exception as e:
        print(f"Unexpected error creating folder '{folder_name}': {e}")
    return None

def upload_file(mega_client, file_path, folder_handle):
    """
    Uploads a file to the specified folder on MEGA.

    Args:
        mega_client (Mega): The MEGA client instance.
        file_path (str): The local path of the file to upload.
        folder_handle (str): The handle of the target folder on MEGA.
    """
    try:
        file_name = os.path.basename(file_path)
        print(f"Uploading: {file_name}")
        mega_client.upload(file_path, folder_handle)
        print(f"Successfully uploaded: {file_name}")
    except errors.GenericMegaException as e:
        print(f"Failed to upload {file_name}: {e}")
    except Exception as e:
        print(f"Unexpected error uploading {file_name}: {e}")

def process_directory(mega_client, local_path, folder_handle):
    """
    Recursively processes a local directory, uploading files and creating folders on MEGA.

    Args:
        mega_client (Mega): The MEGA client instance.
        local_path (str): The local directory path to process.
        folder_handle (str): The handle of the target folder on MEGA.
    """
    for item in os.listdir(local_path):
        item_path = os.path.join(local_path, item)
        if os.path.isdir(item_path):
            new_folder_handle = create_folder(mega_client, folder_handle, item)
            if new_folder_handle:
                process_directory(mega_client, item_path, new_folder_handle)
        elif os.path.isfile(item_path):
            upload_file(mega_client, item_path, folder_handle)

def find_folder_handle(mega_client, folder_name):
    """
    Finds the handle of a folder by name. If not found, creates it.

    Args:
        mega_client (Mega): The MEGA client instance.
        folder_name (str): The name of the folder to find or create.

    Returns:
        str: The handle of the found or created folder, or None if failed.
    """
    try:
        folders = mega_client.find(folder_name)
        print(f"folders found: {folders}")
        if folders:
            # Assuming the first match is the desired folder handle
            folder_handle = folders[0]
            print(f"Found existing root folder '{folder_name}' on MEGA")
            return folder_handle
        else:
            # Folder doesn't exist; create it
            folder_handle = mega_client.create_folder(folder_name)
            print(f"Created root folder '{folder_name}' on MEGA")
            time.sleep(2)  # Wait for 2 seconds after creating the root folder
            return folder_handle
    except errors.GenericMegaException as e:
        print(f"Error finding or creating root folder '{folder_name}': {e}")
    except Exception as e:
        print(f"Unexpected error finding or creating root folder '{folder_name}': {e}")
    return None

if __name__ == "__main__":
    # Configuration
    directory_path = "/Users/shivensheth/Desktop"  # Local directory to upload
    mega_folder_name = "MyUploadedFolder"          # Root folder on MEGA

    mega = Mega()

    try:
        # Log in to MEGA
        email = "shivsbots@gmail.com"
        password = "borntosmile02"
        m = mega.login(email, password)
        print("Successfully logged in to MEGA")

        # Get or create the root folder handle
        root_handle = find_folder_handle(m, mega_folder_name)
        if not root_handle:
            raise Exception(f"Failed to obtain handle for root folder '{mega_folder_name}'")

        # Start processing the directory
        process_directory(m, directory_path, root_handle)

        print("Upload process completed!")
    except Exception as e:
        print(f"An error occurred: {e}")