【问题标题】:How to use google-spreadsheet in nodejs如何在 nodejs 中使用谷歌电子表格
【发布时间】:2020-11-02 20:30:32
【问题描述】:

我想使用 google-spreadsheet API 来获取数据并将数据写入我的 Discord 机器人中的工作表(使用 discord.js)。出于某种原因,我无法让它工作。这是我的代码:

const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')

module.exports = {
    /...
    execute(message, args) {
        accessSpreadsheet()
    }
}

async function accessSpreadsheet() {
    const doc = new GoogleSpreadsheet('<id was here>')
    doc.useServiceAccountAuth(creds)
        .then(() => {
            doc.getInfo()
                .then(info => {
                    console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
                    const sheet = info.worksheets[0]
                    console.log(
                        `sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
                    )
                })
        })
}

这是我不断收到的错误:

 (node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
     at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
     at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
     at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
     at IncomingMessage.emit (events.js:327:22)
     at endReadableNT (_stream_readable.js:1221:12)
     at processTicksAndRejections (internal/process/task_queues.js:84:21)
 (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
 (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

  • 您尝试使用的 ID 似乎有问题
  • @Cloud 我怎么知道?我在工作表 URL 中使用了长 ID...
  • 我以前没有使用过这个特定的 API,但是阅读错误消息,这是我首先要研究的。由于电子表格是私有的,因此可能是身份验证问题,因此 Google 表现得好像它对外部用户不存在。
  • 请问您使用的是google-spreadsheet的版本吗?
  • 该工作表确实是私有的,但已与服务帐户共享。 (现在是编辑器)@Tanaike 我使用的是 3.0.11 版

标签: node.js discord.js google-sheets-api


【解决方案1】:

我实际上应该使用 async/await 来实现这一点。我的代码变成了:

async function accessSpreadsheet(message, args, msg) {
    const doc = new GoogleSpreadsheet('<id was here>')
    await doc.useServiceAccountAuth(creds)

    await doc.loadInfo()
    console.log(doc.title) //whatever you want to log goes here
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多