Discord bot 无法访问 Google Sheets 获取错误请求缺少有效的 API 密钥 [英] Discord bot unable to get access to the Google Sheets getting error The request is missing a valid API key

查看:64
本文介绍了Discord bot 无法访问 Google Sheets 获取错误请求缺少有效的 API 密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Discord 机器人在尝试访问 Google Sheets API v4.0 时遇到问题.我希望它读取、写入和更新工作表中的数据.我的代码适用于 Node.js 应用程序,但是当我将代码放入 Discord 机器人时,它给了我这个错误:

I am having problem with my Discord bot trying to access the Google Sheets API v4.0. I want it to read, write, and update data in the sheet. My code work fine for Node.js application but when I put my code in a Discord bot, it gives me this error:

UnhandledPromiseRejectionWarning:错误:请求缺少有效的 API 密钥

我不明白为什么我会收到这个错误.我什至为我的 Discord 机器人创建了一个服务帐户.

I don't understand why I am getting this error. I even made a service account for my Discord bot.

这是 Discord 机器人的代码.

Here is the Discord bot's code.

require('dotenv').config();

const sheet = require('./sheet');
const { Client } = require('discord.js');
const { sheets } = require('googleapis/build/src/apis/sheets');
const client = new Client();

工作表文件代码:

const {google} = require('googleapis');
const keys = require('./keys.json');

const client  = new google.auth.JWT(
    keys.client_email,
    keys.private_key_id,
    keys.private_key,
    ['https://www.googleapis.com/auth/spreadsheets']
);

client.authorize(function(err,tokens){

    if(err){
        console.log(err);
        return;
    }
    // else{
    //     console.log('Connected');
    //     gsrun(client);
    // }
});

const getdata = async function gsrun(cl){

    const gsapi = google.sheets({version:'v4',auth:cl});

    const opt = {
        spreadsheetId:'1LzdhD4rb2FdElTyQCAkgb5oyeGeu0d9rT2abS4n_4i8',
        range: 'A2:B5'
    };

    let data =  await gsapi.spreadsheets.values.get(opt);

    console.log(data.data.values);
}
exports.getdata = getdata;

我已授予访问机器人电子邮件 ID 的权限,该表单为 discordbotapi@nodejs-api-testing-discordbot.iam.gserviceaccount.com.我还启用了 Google Sheets API.我哪里出错了?

I have given access to bot email id to sheet which is discordbotapi@nodejs-api-testing-discordbot.iam.gserviceaccount.com. I have also enabled the Google Sheets API. Where am I making error?

推荐答案

当你在没有 Discord.js 的 Node.js 中尝试它时,你没有导出任何东西,你只是调用了 gsrun(client) 授权成功后,运行正常.问题是现在您尝试在没有任何授权的情况下使用 getData.尽管您的代码中有 client.authorize,但您从不使用它.

When you tried it in Node.js without Discord.js, you didn't export anything and you simply called gsrun(client) after the authorisation was successful, so it worked fine. The problem is that now you try to use getData without any authorisation. Although you have client.authorize in your code, you never use it.

为了解决这个问题,我会在这里至少做两个不同的函数;一个用于生成客户端,另一个用于获取请求本身并将它们都导出.

To solve this, I would make at least two different functions here; one for generating the client and one for the get request itself and export them both.

为了生成客户端,我会将其包装在一个 Promise 中.这样我以后就可以使用 async/await 了.此函数将使用 JWT 创建一个客户端,执行授权,并根据 client.authorize() 的结果与客户端解析或拒绝承诺.

To generate a client I’d wrap this in a promise. This way I could use async/await later. This function will create a client with the JWT, perform the authorisation, and either resolve with the client or reject the promise depending on the results of client.authorize().

function connect() {
  return new Promise((resolve, reject) => {
    const scope = ['https://www.googleapis.com/auth/spreadsheets'];
    const { client_email, private_key, private_key_id } = keys;
    const client = new google.auth.JWT(
      client_email,
      private_key_id,
      private_key,
      scope,
    );

    client.authorize((err) => {
      if (err) {
        reject(err);
      } else {
        resolve(client);
      }
    });
  });
}

现在您可以使用const client = await connect()简单地连接并获取客户端.

Now you can simply connect and get the client by using const client = await connect().

第二部分是从电子表格中获取一些数据.再一次,我会把它包装在一个承诺中.此函数将接受客户端(我们刚刚在上面创建)以及带有电子表格 ID 和范围的选项.在承诺中,您只需使用以下选项调用 API 端点:

The second part is to get some data from the spreadsheet. Again, I'd wrap it in a promise. This function will accept the client (we’ve just created above) and the options with the spreadsheetId and range. Inside the promise you just call the API endpoint with the options:

function getData(client, options) {
  return new Promise((resolve, reject) => {
    const endpoint = google.sheets({ version: 'v4', auth: client });

    endpoint.spreadsheets.values.get(options, (err, data) => {
      if (err) {
        reject(err);
      } else {
        // or resolve with data.data.values if you only want the values
        resolve(data.data);
      }
    });
  });
}

您可以将这两个导出到一个对象中.这是完整的 sheet.js 文件:

You can export both of these in an object. Here is the full sheet.js file:

const { google } = require('googleapis');

const keys = require('./keys.json');

function connect() {
  return new Promise((resolve, reject) => {
    const scope = ['https://www.googleapis.com/auth/spreadsheets'];
    const { client_email, private_key, private_key_id } = keys;
    const client = new google.auth.JWT(
      client_email,
      private_key_id,
      private_key,
      scope,
    );

    client.authorize((err) => {
      if (err) {
        reject(err);
      } else {
        resolve(client);
      }
    });
  });
}

function getData(client, options) {
  return new Promise((resolve, reject) => {
    const endpoint = google.sheets({ version: 'v4', auth: client });

    endpoint.spreadsheets.values.get(options, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data.data);
      }
    });
  });
}

module.exports = { connect, getData };

然后,您可以将其导入到您的机器人文件中,并在其中使用它先进行连接,然后获取值:

Then, you can import it in your bot's file and use it in there to connect first and then get the values:

const { Client } = require('discord.js');
const { connect, getData } = require('./sheet');

const client = new Client();

client.on('message', async (message) => {
  if (message.author.bot) return;

  const auth = await connect();

  const options = {
    spreadsheetId: '1LzdhD4rb2FdElTyQCAkgb5oyeGeu0d9rT2abS4n_4i8',
    range: 'A2:B5',
  };
  const { values } = await getData(auth, options);

  message.channel.send(values);
});

这篇关于Discord bot 无法访问 Google Sheets 获取错误请求缺少有效的 API 密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆