TrainHeartX commited on
Commit
24aa33f
verified
1 Parent(s): 2d9a52f

Update comunicacion_gmail.py

Browse files
Files changed (1) hide show
  1. comunicacion_gmail.py +68 -66
comunicacion_gmail.py CHANGED
@@ -5,7 +5,6 @@ from email.mime.text import MIMEText
5
  import pickle
6
  import os.path
7
  import base64
8
- import email
9
 
10
  # Define los 谩mbitos que necesitas (ajusta seg煤n tus necesidades)
11
  SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify']
@@ -24,73 +23,76 @@ def gmail_tool(accion, parametros={}):
24
  creds.refresh(Request())
25
  else:
26
  flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
27
- creds = flow.run_console()
28
- with open('token.pickle', 'wb') as token:
29
- pickle.dump(creds, token)
30
-
31
  service = build('gmail', 'v1', credentials=creds)
32
  result = {} # Inicializar result
33
-
34
- if accion == "leer_correos":
35
- # ... (implementaci贸n para leer correos) ...
36
- results = service.users().messages().list(userId='me', maxResults=10).execute()
37
- messages = results.get('messages', [])
38
- for message in messages:
39
- msg = service.users().messages().get(userId='me', id=message['id']).execute()
40
-
41
-
42
- # Decodificar el mensaje (puede ser multipart)
43
- payload = msg['payload']
44
- parts = payload.get('parts', []) # Verificar si hay partes
45
-
46
- body = ""
47
- if parts:
48
- for part in parts:
49
- if part.get('mimeType') == 'text/plain':
50
- data = part['body'].get('data', '')
51
- body += base64.urlsafe_b64decode(data).decode()
52
-
53
- else: # Si no hay partes, el cuerpo est谩 en payload['body']
54
- data = payload['body'].get('data','')
55
- body+= base64.urlsafe_b64decode(data).decode()
56
-
57
- print(body)
58
- result["message_id"] = send_message["id"] # Almacenar el ID del mensaje en el resultado
59
-
60
-
61
- elif accion == "enviar_correo":
62
- # ... (implementaci贸n para enviar correo) ...
63
- message = MIMEText('Este es el cuerpo del correo.') # Importa MIMEText de email.mime.text
64
- message['to'] = 'destinatario@example.com' #!CAMBIAR DESTINATARIO
65
- message['from'] = '[email protected]'#!CAMBIAR TU CORREO
66
- message['subject'] = 'Asunto del correo'
67
-
68
- create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
69
-
70
- send_message = service.users().messages().send(userId='me', body=create_message).execute()
71
-
72
- print(F'Message Id: {send_message["id"]}')
73
-
74
- elif accion == "verificar_almacenamiento":
75
- try:
76
- drive_service = build('drive', 'v3', credentials=creds)
77
- about = drive_service.about().get(fields="storageQuota").execute()
78
- storage_quota = about.get('storageQuota')
79
- # print(storage_quota) # Para depurar
80
- return storage_quota # Devuelve la informaci贸n del almacenamiento
81
-
82
- except Exception as e:
83
- print(f"Error al verificar el almacenamiento: {e}")
84
- return {"error": "Error al verificar el almacenamiento."}
85
-
86
-
87
-
88
- # ... (otras acciones)
89
-
90
- return result
 
 
91
 
92
-
93
-
94
-
 
95
 
96
  # ... (Integraci贸n con el prompt del sistema)
 
5
  import pickle
6
  import os.path
7
  import base64
 
8
 
9
  # Define los 谩mbitos que necesitas (ajusta seg煤n tus necesidades)
10
  SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify']
 
23
  creds.refresh(Request())
24
  else:
25
  flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
26
+ # Obtener URL de autorizaci贸n
27
+ auth_url, _ = flow.authorization_url(prompt='consent')
28
+ return {"auth_url": auth_url, "requires_auth": True} # Indicar que se requiere autorizaci贸n
29
+
30
  service = build('gmail', 'v1', credentials=creds)
31
  result = {} # Inicializar result
32
+
33
+ try:
34
+ if accion == "leer_correos":
35
+ # ... (implementaci贸n para leer correos) ...
36
+ results = service.users().messages().list(userId='me', maxResults=parametros.get("maxResults", 10)).execute() # Usa parametros para maxResults
37
+ messages = results.get('messages', [])
38
+ result["messages"] = [] # Inicializa una lista para almacenar los mensajes
39
+ for message in messages:
40
+ msg = service.users().messages().get(userId='me', id=message['id']).execute()
41
+ # Decodificar el mensaje (puede ser multipart)
42
+ payload = msg['payload']
43
+ parts = payload.get('parts', []) # Verificar si hay partes
44
+ body = ""
45
+ if parts:
46
+ for part in parts:
47
+ if part.get('mimeType') == 'text/plain':
48
+ data = part['body'].get('data', '')
49
+ body += base64.urlsafe_b64decode(data).decode()
50
+
51
+ else: # Si no hay partes, el cuerpo est谩 en payload['body']
52
+ data = payload['body'].get('data','')
53
+ body+= base64.urlsafe_b64decode(data).decode()
54
+
55
+ print(body)
56
+ result["messages"].append({"body": body, "id": message['id']}) # Asocia el ID al mensaje
57
+
58
+
59
+ elif accion == "enviar_correo":
60
+ # ... (implementaci贸n para enviar correo) ...
61
+ destinatario = parametros.get("destinatario")
62
+ asunto = parametros.get("asunto")
63
+ cuerpo_correo = parametros.get("cuerpo")
64
+
65
+ message = MIMEText(cuerpo_correo)
66
+ message['to'] = destinatario
67
+ message['from'] = '[email protected]' #!CAMBIAR TU CORREO
68
+ message['subject'] = asunto
69
+
70
+ create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
71
+
72
+ send_message = service.users().messages().send(userId='me', body=create_message).execute()
73
+
74
+ print(F'Message Id: {send_message["id"]}')
75
+ result["message_id"] = send_message["id"] # Almacenar el ID
76
+
77
+ elif accion == "verificar_almacenamiento":
78
+ try:
79
+ drive_service = build('drive', 'v3', credentials=creds)
80
+ about = drive_service.about().get(fields="storageQuota").execute()
81
+ storage_quota = about.get('storageQuota')
82
+ # print(storage_quota) # Para depurar
83
+ return storage_quota # Devuelve la informaci贸n del almacenamiento
84
+
85
+ except Exception as e:
86
+ print(f"Error al verificar el almacenamiento: {e}")
87
+ return {"error": "Error al verificar el almacenamiento."}
88
+
89
+
90
+ return result # Retorna el resultado al final del try...except
91
+ # ... (otras acciones)
92
 
93
+ except Exception as e:
94
+ print(f"Error en gmail_tool: {e}")
95
+ result["error"] = str(e)
96
+ return result
97
 
98
  # ... (Integraci贸n con el prompt del sistema)