【问题标题】:Unable to write to Google Spreadsheet from actions on google with dialogflow无法使用对话流从谷歌上的操作写入谷歌电子表格
【发布时间】:2019-03-14 03:54:54
【问题描述】:

我正在尝试使用 Dialogflow 从 Actions on Google 应用程序写入 Google 电子表格。我可以使用我的应用程序从工作表中读取。电子表格被授予公共编辑权限。

我在履行 webhook 中使用以下代码来读取和写入电子表格。我有我的 SPREADSHEET_ID 和 SPREADSHEET_API_KEY:

function welcome(agent) {
    const tabName = 'Sheet1';
    const startCell = 'B2';
    const endCell = 'D';

    appendDataToSpreadsheet(tabName, startCell, endCell);
    agent.add(`Appended`);
}

function appendDataToSpreadsheet(tabName, startCell, endCell) {
  const sheets = google.sheets({version: 'v4', auth: SPREADSHEET_API_KEY});
  return sheets.spreadsheets.values.append({
    auth: auth,
    spreadsheetId: SPREADSHEET_ID,
    range: `${tabName}!${startCell}:${endCell}`,
    valueInputOption: "USER_ENTERED",
    resource: {
      values: [ ["5", "Anis", "8", "React"], ["6", "Paul", "1", "Python"] ]
    }
  }, (err, response) => {
    if (err) {
        console.log('The API returned an error: ' + err);
        return;
      } else {
        console.log("Appended");
    }
  });
}

此代码不会将数据附加到电子表格中,在我的日志中我可以看到以下错误:

API 返回错误:
错误:请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。见https://developers.google.com/identity/sign-in/web/devconsole-project

应用程序要求提供身份验证凭据。任何有关如何进行此操作的指示都会有所帮助。

【问题讨论】:

  • 编写需要 OAuth2,如错误消息所述,并在相关问题中进行了说明。

标签: node.js google-sheets dialogflow-es google-sheets-api actions-on-google


【解决方案1】:

要写入工作表,您需要获得authorization 才能这样做,即使对于可公开写入的工作表也是如此,因为写入需要用户帐户来注释谁进行了更改。虽然 API 密钥足以读取工作表(因为没有审核日志),但您需要一个帐户才能实际写入。

如果您只是通过操作来执行此操作,则可以为单个用户维护身份验证令牌和刷新令牌并将其隐藏。不过,更好的是使用Google Sign In for AssistantOAuth2 flow 来准确跟踪编辑电子表格的人员。

【讨论】:

    【解决方案2】:

    我建议通过设置使用 JWT-OAuth2.0 的服务帐户进行身份验证:

    const spreadsheetId = 'INSERT_HERE'; 
    
    const serviceAccount = { INSERT_HERE };     // {"type": "service_account",...
    
    // Set up Google Calendar Service account credentials
    const serviceAccountAuth = new google.auth.JWT({
      email: serviceAccount.client_email,
      key: serviceAccount.private_key,
      scopes: 'https://www.googleapis.com/auth/spreadsheet'
    });
    

    您可以通过转到 Dialogflow 项目设置中的 Google Cloud Platform 链接 https://console.cloud.google.com/home/dashboard?project=INSERT_AGENT_NAME 来执行此操作。

    从那里转到 APIs & Services > Credentials > Create Credentials > Service Account Key > Project/Owner。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多