-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_read.py
More file actions
executable file
·123 lines (95 loc) · 3.56 KB
/
agent_read.py
File metadata and controls
executable file
·123 lines (95 loc) · 3.56 KB
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
#!/usr/bin/env python3
"""
Exemplo: Ler email específico usando Gmail CLI (Modo Agente)
Este script demonstra como um agente de IA pode:
- Ler o conteúdo completo de um email
- Extrair informações estruturadas do JSON
- Processar o corpo do email
"""
import json
import subprocess
import sys
from typing import Optional, Dict
def read_email(message_id: str) -> Optional[Dict]:
"""
Lê um email específico usando o Gmail CLI.
Args:
message_id: ID da mensagem (obtido via gmail search)
Returns:
Dicionário com detalhes do email ou None em caso de erro
"""
try:
# Executar comando gmail read com flag --json
result = subprocess.run(
["gmail", "read", message_id, "--json"],
capture_output=True,
text=True,
check=True
)
# Parsear JSON da saída
email = json.loads(result.stdout)
return email
except subprocess.CalledProcessError as e:
print(f"❌ Erro ao executar comando: {e}", file=sys.stderr)
print(f"Stderr: {e.stderr}", file=sys.stderr)
return None
except json.JSONDecodeError as e:
print(f"❌ Erro ao parsear JSON: {e}", file=sys.stderr)
return None
except FileNotFoundError:
print("❌ Comando 'gmail' não encontrado. Instale com: pipx install gmail-cli", file=sys.stderr)
return None
def extract_keywords(text: str, keywords: list) -> Dict[str, bool]:
"""
Verifica presença de palavras-chave no texto.
Args:
text: Texto para análise
keywords: Lista de palavras-chave
Returns:
Dicionário com presença de cada palavra-chave
"""
text_lower = text.lower()
return {keyword: keyword.lower() in text_lower for keyword in keywords}
def main():
"""Exemplo de uso do agente."""
if len(sys.argv) < 2:
print("Uso: python agent_read.py <MESSAGE_ID>")
print("\nObtenha o MESSAGE_ID usando:")
print(" gmail search 'sua query' --json")
sys.exit(1)
message_id = sys.argv[1]
print(f"📧 Lendo email {message_id}...\n")
email = read_email(message_id)
if email is None:
print("❌ Falha ao ler email. Verifique se você está autenticado:")
print(" gmail auth login --credentials /caminho/para/credentials.json")
sys.exit(1)
# Exibir informações estruturadas
print("="*60)
print(f"ID: {email.get('id', 'N/A')}")
print(f"De: {email.get('from', 'Unknown')}")
print(f"Assunto: {email.get('subject', 'No Subject')}")
print(f"Data: {email.get('date', 'N/A')}")
print("="*60)
print("\nCorpo:")
print(email.get('body', 'Sem conteúdo'))
print("="*60)
# Exemplo: Análise de palavras-chave
keywords = ["urgente", "importante", "fatura", "pagamento", "reunião"]
body = email.get('body', '')
if body:
print("\n🔍 Análise de Palavras-Chave:")
keyword_presence = extract_keywords(body, keywords)
found_keywords = [k for k, v in keyword_presence.items() if v]
if found_keywords:
print(f"✅ Palavras-chave encontradas: {', '.join(found_keywords)}")
else:
print("ℹ️ Nenhuma palavra-chave encontrada")
# Exemplo: Verificar tamanho do corpo
if body:
word_count = len(body.split())
print(f"\n📊 Estatísticas:")
print(f" - Caracteres: {len(body)}")
print(f" - Palavras: {word_count}")
if __name__ == "__main__":
main()