如何创建Google Apps脚本?

时间:2017-04-19 09:05:05

标签: python google-apps-script

我使用服务帐户,这是我的代码:

test.py

import httplib2
from apiclient import discovery
from googleapiclient.http import MediaFileUpload
from oauth2client.service_account import ServiceAccountCredentials

SCOPE = 'https://www.googleapis.com/auth/drive'
KEY_DICT = {...}
credentials = ServiceAccountCredentials.from_json_keyfile_dict(KEY_DICT, SCOPE)
http = credentials.authorize(httplib2.Http())
drive = discovery.build('drive', 'v3', http=http)
script = discovery.build('script', 'v1', http=http)

file_name = 'test.gs'
file_metadata = {
    'name': file_name,
    'mimeType': 'application/vnd.google-apps.script'
}
media = MediaFileUpload(file_name, mimetype='text/plain')
file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()
script_id = file.get('id')

request = {
    "function": 'getFoldersUnderRoot',
}
response = script.scripts().run(body=request, scriptId=script_id).execute()
print response['response'].get('result')

test.gs

function getFoldersUnderRoot() {
  var root = DriveApp.getRootFolder();
  var folders = root.getFolders();
  var folderSet = {};
  while (folders.hasNext()) {
    var folder = folders.next();
    folderSet[folder.getId()] = folder.getName();
  }
  return folderSet;
}

然后我收到以下错误:

Traceback (most recent call last):
  File "./test.py", line 37, in <module>
    response = script.scripts().run(body=request, scriptId=script_id).execute()
  File "site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "site-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://script.googleapis.com/v1/scripts/1LI...4y0:run?alt=json returned "Request contains an invalid argument.">

我做错了什么?也许我应该部署脚本?也许这只适用于Web UI。我没有通过开发控制台找到如何做到这一点。

1 个答案:

答案 0 :(得分:0)

不幸的是,使用服务帐户和Google App Scripts API存在已知问题。您可以阅读有关此问题的更多信息here

解决方法是用户客户端凭据手动生成刷新令牌,然后使用刷新令牌作为获取授权令牌的方法。