File size: 6,706 Bytes
38902c4
2d9a52f
 
38902c4
2d9a52f
 
 
 
38902c4
8cc55ce
2d9a52f
38902c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d9a52f
 
 
38902c4
 
 
 
2d9a52f
 
38902c4
 
 
 
 
 
 
 
 
 
2d9a52f
24aa33f
38902c4
 
 
24aa33f
38902c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24aa33f
38902c4
 
 
 
24aa33f
38902c4
 
 
 
 
 
 
 
 
 
 
451bf76
38902c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d9a52f
a004452
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from email.mime.text import MIMEText
import pickle
import os.path
import base64
import json
import os

# Define los 谩mbitos que necesitas (ajusta seg煤n tus necesidades)
SCOPES = [
    'https://mail.google.com/',  #  Acceso completo a Gmail (preferido)
    'https://www.googleapis.com/auth/gmail.metadata', # Necesario para leer metadatos (etiquetas, etc.)
    'https://www.googleapis.com/auth/gmail.labels',   #  Para gestionar etiquetas
    'https://www.googleapis.com/auth/gmail.addons.current.message.metadata', # Metadatos al ejecutar complemento
    'https://www.googleapis.com/auth/gmail.addons.current.message.readonly', #  Lectura al ejecutar complemento
    'https://www.googleapis.com/auth/gmail.addons.current.action.compose', # Redactar con complemento
    'https://www.googleapis.com/auth/gmail.settings.basic',  # Configuraci贸n b谩sica de Gmail
    'https://www.googleapis.com/auth/gmail.settings.sharing', # Delegaci贸n de acceso (si es necesario)
    'https://www.googleapis.com/auth/drive',        #  Acceso completo a Drive 
    'https://www.googleapis.com/auth/drive.appdata',  # Datos de la app en Drive
    'https://www.googleapis.com/auth/drive.install', # Conexi贸n a Drive
    'https://www.googleapis.com/auth/drive.file', # Para archivos creados o abiertos por la app
    'https://www.googleapis.com/auth/activity' # leer el activity de gmail
]

def gmail_tool(accion, parametros={}):
    """Interact煤a con la API de Gmail."""
    # Obtener credenciales desde secrets del Space
    client_id = os.environ.get("GMAIL_CLIENT_ID")
    client_secret = os.environ.get("GMAIL_CLIENT_SECRET")
    refresh_token = os.environ.get("GMAIL_REFRESH_TOKEN")


    if client_id and client_secret and refresh_token:
        try:
            creds = Credentials(
                token=None,
                refresh_token=refresh_token,
                token_uri="https://oauth2.googleapis.com/token",
                client_id=client_id,
                client_secret=client_secret,
                scopes=SCOPES
            )
            creds.refresh(Request())
            
                     
            service = build('gmail', 'v1', credentials=creds)
            result = {} # Inicializar result
    
            try:
                if accion == "leer_correos":
                    # ... (implementaci贸n para leer correos) ...
                    results = service.users().messages().list(userId='me', maxResults=parametros.get("maxResults", 10)).execute() # Usa parametros para maxResults
                    messages = results.get('messages', [])
                    result["messages"] = [] # Inicializa una lista para almacenar los mensajes
                    for message in messages:
                        try:
                            msg = service.users().messages().get(userId='me', id=message['id']).execute()    
                            # Decodificar el mensaje (puede ser multipart)
                            payload = msg['payload']
                            parts = payload.get('parts', [])  # Verificar si hay partes    
                            body = ""
                            if parts:
                                for part in parts:
                                    if part.get('mimeType') == 'text/plain':
                                        data = part['body'].get('data', '')
                                        body += base64.urlsafe_b64decode(data).decode()
                
                            else:  # Si no hay partes, el cuerpo est谩 en payload['body']
                                data = payload['body'].get('data','')
                                body+= base64.urlsafe_b64decode(data).decode()
                
                            print(body)
                            result["messages"].append({"body": body, "id": message['id']}) #  Asocia el ID al mensaje
                        except Exception as e:
                            print(f"Error al leer el mensaje {message['id']}: {e}")
                            result["messages"].append({"error": str(e), "id": message['id']}) #  Almacena el error para ese mensaje
            
            
                elif accion == "enviar_correo":
                    # ... (implementaci贸n para enviar correo) ...
                    destinatario = parametros.get("destinatario")
                    asunto = parametros.get("asunto")
                    cuerpo_correo = parametros.get("cuerpo")

                    message = MIMEText(cuerpo_correo)
                    message['to'] = destinatario
                    message['from'] = '[email protected]' #!CAMBIAR TU CORREO
                    message['subject'] = asunto
            
                    create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
            
                    send_message = service.users().messages().send(userId='me', body=create_message).execute()
            
                    print(F'Message Id: {send_message["id"]}')
                    result["message_id"] = send_message["id"]  #  Almacenar el ID
                    
                elif accion == "verificar_almacenamiento":
                    try:
                        drive_service = build('drive', 'v3', credentials=creds)
                        about = drive_service.about().get(fields="storageQuota").execute()
                        print(f"Respuesta de la API de Drive: {about}") #  Mensaje de depuraci贸n
                        result = about.get('storageQuota', {}) # Asigna directamente a result.get y maneja si no existe storageQuota
                        return result
            
                    except Exception as e:
                        print(f"Error al verificar el almacenamiento: {e}")
                        return {"error": "Error al verificar el almacenamiento: " + str(e)}
            
            
                return result #  Retorna el resultado al final del try...except
                # ... (otras acciones)
                
            except Exception as e:  #  Captura excepciones de la API de Gmail/Drive
                print(f"Error en gmail_tool (acciones): {e}")
                return {"error": str(e)}
            
        except Exception as e: # Excepci贸n para la creaci贸n de credenciales
            print(f"Error al crear credenciales: {e}")
            return {"error": str(e)}
    else:
        return {"error": "Credenciales incompletas."}

# ... (Integraci贸n con el prompt del sistema)