GMAIL / comunicacion_gmail.py
TrainHeartX's picture
Update comunicacion_gmail.py
8cc55ce verified
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)