当前位置: 首页 > Skill >

Gsuite Sdk

Gsuite Sdk

Gsuite Sdk

使用 gsuite-sdk 与 Google Workspace API(Gmail、日历、Drive、表格)交互。

0.1.3 2026.11.19 484
获取Skill文件查看使用说明
作 者:陆知 许可证: 更新时间:2026.11.19
本文目录展开

Google Suite Skill

Skill para interactuar con Google Workspace APIs (Gmail, Calendar, Drive, Sheets) usando gsuite-sdk.

Instalación

pip install gsuite-sdk

Con extras opcionales:

pip install gsuite-sdk[cloudrun]  # Para Secret Manager
pip install gsuite-sdk[all]       # Todas las dependencias

Autenticación

Primera vez (requiere navegador)

El usuario debe obtener credentials.json de Google Cloud Console y luego autenticarse:

# Via CLI
gsuite auth login

# O via Python (abre navegador)
from gsuite_core import GoogleAuth
auth = GoogleAuth()
auth.authenticate()

Ver GETTING_CREDENTIALS.md para guía completa.

Sesiones siguientes

Una vez autenticado, los tokens se guardan localmente y se refrescan automáticamente:

from gsuite_core import GoogleAuth

auth = GoogleAuth()
if auth.is_authenticated():
    # Listo para usar
    pass
else:
    # Necesita autenticarse (abre navegador)
    auth.authenticate()

Gmail

Leer mensajes

from gsuite_core import GoogleAuth
from gsuite_gmail import Gmail, query

auth = GoogleAuth()
gmail = Gmail(auth)

# Mensajes no leídos
for msg in gmail.get_unread(max_results=10):
    print(f"De: {msg.sender}")
    print(f"Asunto: {msg.subject}")
    print(f"Fecha: {msg.date}")
    print(f"Preview: {msg.body[:200]}...")
    print("---")

# Buscar con query builder
mensajes = gmail.search(
    query.from_("notifications@github.com") & 
    query.newer_than(days=7)
)

# Marcar como leído
msg.mark_as_read()

Enviar email

gmail.send(
    to=["destinatario@example.com"],
    subject="Asunto del email",
    body="Contenido del mensaje",
)

# Con adjuntos
gmail.send(
    to=["user@example.com"],
    subject="Reporte",
    body="Adjunto el reporte.",
    attachments=["reporte.pdf"],
)

Calendar

Leer eventos

from gsuite_core import GoogleAuth
from gsuite_calendar import Calendar

auth = GoogleAuth()
calendar = Calendar(auth)

# Eventos de hoy
for event in calendar.get_today():
    print(f"{event.start.strftime('%H:%M')} - {event.summary}")

# Próximos 7 días
for event in calendar.get_upcoming(days=7):
    print(f"{event.start}: {event.summary}")
    if event.location:
        print(f"  📍 {event.location}")

# Rango específico
from datetime import datetime
events = calendar.get_events(
    time_min=datetime(2026, 2, 1),
    time_max=datetime(2026, 2, 28),
)

Crear eventos

from datetime import datetime

calendar.create_event(
    summary="Reunión de equipo",
    start=datetime(2026, 2, 15, 10, 0),
    end=datetime(2026, 2, 15, 11, 0),
    location="Sala de conferencias",
)

# Con asistentes
calendar.create_event(
    summary="Sync semanal",
    start=datetime(2026, 2, 15, 14, 0),
    end=datetime(2026, 2, 15, 15, 0),
    attendees=["alice@company.com", "bob@company.com"],
    send_notifications=True,
)

Drive

Listar y descargar archivos

from gsuite_core import GoogleAuth
from gsuite_drive import Drive

auth = GoogleAuth()
drive = Drive(auth)

# Listar archivos recientes
for file in drive.list_files(max_results=20):
    print(f"{file.name} ({file.mime_type})")

# Buscar
files = drive.list_files(query="name contains 'reporte'")

# Descargar
file = drive.get("file_id_aqui")
file.download("/tmp/archivo.pdf")

Subir archivos

# Subir archivo
uploaded = drive.upload("documento.pdf")
print(f"Link: {uploaded.web_view_link}")

# Subir a carpeta específica
uploaded = drive.upload("data.xlsx", parent_id="folder_id")

# Crear carpeta
folder = drive.create_folder("Reportes 2026")
drive.upload("q1.pdf", parent_id=folder.id)

Sheets

Leer datos

from gsuite_core import GoogleAuth
from gsuite_sheets import Sheets

auth = GoogleAuth()
sheets = Sheets(auth)

# Abrir spreadsheet
spreadsheet = sheets.open("SPREADSHEET_ID")

# Leer worksheet
ws = spreadsheet.worksheet("Sheet1")
data = ws.get("A1:D10")  # Lista de listas

# Como diccionarios (primera fila = headers)
records = ws.get_all_records()
# [{"Nombre": "Alice", "Edad": 30}, ...]

Escribir datos

# Actualizar celda
ws.update("A1", "Nuevo valor")

# Actualizar rango
ws.update("A1:C2", [
    ["Nombre", "Edad", "Ciudad"],
    ["Alice", 30, "NYC"],
])

# Agregar filas al final
ws.append([
    ["Bob", 25, "LA"],
    ["Charlie", 35, "Chicago"],
])

CLI

Si instalaste gsuite-cli:

# Autenticación
gsuite auth login
gsuite auth status

# Gmail
gsuite gmail list --unread
gsuite gmail send --to user@example.com --subject "Hola" --body "Mundo"

# Calendar
gsuite calendar today
gsuite calendar list --days 7

# Drive
gsuite drive list
gsuite drive upload archivo.pdf

# Sheets
gsuite sheets read SPREADSHEET_ID --range "A1:C10"

Notas para agentes

  1. Primera autenticación requiere navegador - El usuario debe completar OAuth manualmente la primera vez
  2. Tokens persisten - Después de autenticar, los tokens se guardan en tokens.db y se refrescan automáticamente
  3. Scopes - Por defecto pide acceso a Gmail, Calendar, Drive y Sheets. Se puede limitar con --scopes
  4. Errores comunes:
    • CredentialsNotFoundError: Falta credentials.json
    • TokenRefreshError: Token expiró y no se pudo refrescar (re-autenticar)
    • NotFoundError: Recurso no existe o sin permisos

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,016
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,004
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,002
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,001
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,001
PHP集成RabbitMQ实现消息队列的完整步骤

使用 php-amqplib 库,通过建立连接、声明交换机与队列并绑定,即可在 PHP 中实现消息的发送与消费。

2026.05.24 1,001
Skill 文件
  • SKILL.md
    • Google Suite Skill
    • Instalación
    • Autenticación
      • Primera vez (requiere navegador)
      • Sesiones siguientes
    • Gmail
      • Leer mensajes
      • Enviar email
    • Calendar
      • Leer eventos
      • Crear eventos
    • Drive
      • Listar y descargar archivos
      • Subir archivos
    • Sheets
      • Leer datos
      • Escribir datos
    • CLI
    • Notas para agentes
  • 项目或源文件

相关 Skill

更多
Gog Local Gog Local Google Workspace 命令行工具,支持 Gmail、日历、云端硬盘、联系人、表格和文档。
Composio Composio 将AI助手连接到500+应用,发现工具、管理连接并在Gmail、Slack、GitHub、Notion、Google Workspace等平台执行操作。
Openstoa Skill Openstoa Skill 基于零知识的门控社区,人类与AI代理共存。使用Google(OIDC)设备流登录,验证组织身份(Google Workspace、Microsoft等)。
Api Gateway 1 Api Gateway 1 连接到100+ API(Google Workspace、Microsoft 365、Notion、Slack、Airtable、HubSpot等),使用托管OAuth。当用户想要交互时使用此技能。
Backup Gog 20260213 121122 Backup Gog 20260213 121122 Google Workspace 命令行工具,支持 Gmail、日历、云端硬盘、联系人、表格和文档。