You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Apps Script API创建定时触发事件

实现自动创建定时触发的Google Apps Script

要实现每10分钟自动记录日志且无需手动添加触发器,你需要对原代码做以下几处修改:

1. 更新权限范围

原权限仅能操作脚本项目,创建触发器需要额外权限,将SCOPES修改为:

SCOPES = [
    "https://www.googleapis.com/auth/script.projects",
    "https://www.googleapis.com/auth/script.scriptapp"
]

2. 调整日志输出方式

原代码用console.log在触发器执行时无法在脚本网站查看,改为Logger.log:

function helloWorld() {
  Logger.log("Hello, world!");
}

3. 添加自动创建触发器的代码

在更新完脚本内容后,调用Google Apps Script API创建每10分钟触发的定时触发器。

修改后的完整代码

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient import errors
from googleapiclient.discovery import build

# 更新权限范围,添加创建触发器所需权限
SCOPES = [
    "https://www.googleapis.com/auth/script.projects",
    "https://www.googleapis.com/auth/script.scriptapp"
]

# 修改日志输出方式,确保在脚本网站可查看
SAMPLE_CODE = """
function helloWorld() {
  Logger.log("Hello, world!");
}
""".strip()

SAMPLE_MANIFEST = """
{
  "timeZone": "Asia/Taipei",
  "exceptionLogging": "CLOUD"
}
""".strip()


def main():
  creds = None
  if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(
          "credentials.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w") as token:
      token.write(creds.to_json())

  try:
    service = build("script", "v1", credentials=creds)
    # 创建脚本项目
    request = {"title": "My Script1"}
    response = service.projects().create(body=request).execute()
    script_id = response["scriptId"]
    
    # 更新脚本内容
    request = {
        "files": [
            {
                "name": "hello", 
                "type": "SERVER_JS", 
                "source": SAMPLE_CODE
            },
            
            {
                "name": "appsscript",
                "type": "JSON",
                "source": SAMPLE_MANIFEST,
            },
        ]
    }
    service.projects().updateContent(body=request, scriptId=script_id).execute()
    
    # 创建每10分钟触发的定时触发器
    trigger_request = {
        "trigger": {
            "type": "CLOCK",
            "function": "helloWorld",
            "schedule": {
                "minute": "*/10",  # 每10分钟触发
                "timeZone": "Asia/Taipei"
            }
        }
    }
    service.projects().createTrigger(scriptId=script_id, body=trigger_request).execute()
    
    print(f"脚本已创建,链接:https://script.google.com/d/{script_id}/edit")
    print("每10分钟执行一次的触发器已自动添加")

  except errors.HttpError as error:
    # 捕获API错误并输出
    print(error.content)


if __name__ == "__main__":
  main()

验证效果

  1. 运行代码后,打开输出的脚本链接
  2. 点击左侧「触发器」图标(闹钟形状),即可看到已自动创建的每10分钟触发的定时任务
  3. 查看日志:点击「查看」>「日志」,就能看到每10分钟记录的"Hello, world!"

内容的提问来源于stack exchange,提问作者AndyLinOuO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:08:12