TrainHeartX commited on
Commit
2d9a52f
verified
1 Parent(s): 6ca45ef

Update comunicacion_gmail.py

Browse files
Files changed (1) hide show
  1. comunicacion_gmail.py +95 -95
comunicacion_gmail.py CHANGED
@@ -1,96 +1,96 @@
1
- from googleapiclient.discovery import build
2
- from google_auth_oauthlib.flow import InstalledAppFlow
3
- from google.auth.transport.requests import Request
4
- 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']
12
-
13
-
14
- def gmail_tool(accion, parametros={}):
15
- """Interact煤a con la API de Gmail."""
16
- creds = None
17
-
18
- if os.path.exists('token.pickle'):
19
- with open('token.pickle', 'rb') as token:
20
- creds = pickle.load(token)
21
-
22
- if not creds or not creds.valid:
23
- if creds and creds.expired and creds.refresh_token:
24
- creds.refresh(Request())
25
- else:
26
- flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
27
- creds = flow.run_local_server(port=0)
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'] = '[email protected]' #!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)
 
1
+ from googleapiclient.discovery import build
2
+ from google_auth_oauthlib.flow import InstalledAppFlow
3
+ from google.auth.transport.requests import Request
4
+ 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']
12
+
13
+
14
+ def gmail_tool(accion, parametros={}):
15
+ """Interact煤a con la API de Gmail."""
16
+ creds = None
17
+
18
+ if os.path.exists('token.pickle'):
19
+ with open('token.pickle', 'rb') as token:
20
+ creds = pickle.load(token)
21
+
22
+ if not creds or not creds.valid:
23
+ if creds and creds.expired and creds.refresh_token:
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'] = '[email protected]' #!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)