英文:
Google Sheets Api authentication for Discord.js without .json
问题
我正在使用一个Discord机器人来访问Google Sheets文档。我已经创建了一个Google服务帐户,并为该服务帐户提供了对Sheets文档的访问权限,并生成了私钥.json
文件。我在我的机器人中创建了一个命令来查找表格中的记录。当我在本地运行机器人时(无论是在调试模式内还是外部),这似乎都能正常工作。我认为这是因为.json
配置是项目的一部分。
我不想将.json
文件检入存储库(因为这不合适)。我也不完全确定如果我将其检入存储库,功能是否会正常工作,因此我也不想将其检入存储库。
有没有其他的方法可以进行身份验证,而不需要将私钥.json
中的10个新值放入.env
文件中(然后将它们添加到Heroku)。
当前代码(摘录):
const { google } = requires('googleapis');
async run(message, searchText)
{
const auth = new google.auth.GoogleAuth({
keyFile : "credentials.json",
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
// create client instance for auth
const client = await auth.getClient();
// create instance of google sheets api
const googleSheets = google.sheets({version: "v4", auth: client});
/* other code here */
}
英文:
I am using a Discord bot to access a Google Sheets document. I have created a Google Service Account and provided this Service Account access to the Sheets document and generated the private key .json
file. I have created a command in my bot to find records in the sheet. This appears to be working fine when I run the bot locally (in or out of Debug mode). I assume this is because the .json
configuration is part of the project.
I don't want to check the .json
file into the repository (because that's not appropriate anyway). I'm also not 100% sure the functionality would work if I were to check it into the repository, and because of this I also don't want to check it in.
What is an alternate way to authenticate without putting the 10 new values from the private key .json
into the .env
file (and subsequently adding them to Heroku).
Current code (excerpt):
const { google } = requires('googleapis');
async run(message, searchText)
{
const auth = new google.auth.GoogleAuth({
keyFile : "credentials.json",
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
// create client instance for auth
const client = await auth.getClient();
// create instance of google sheets api
const googleSheets = google.sheets({version: "v4", auth: client});
/* other code here */
}
答案1
得分: 0
为了解决这个问题,我将我的.json
文件添加到一个环境变量中,然后将该环境变量读入一个JSON.parse()
函数中,并将其传递给GoogleAuth
的credentials
属性。看起来像这样:
const auth = new google.auth.GoogleAuth({
credentials: JSON.parse(credentials_env_variable),
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
英文:
To fix this, I added my .json
file to an environment variable, and then read that environment variable into a JSON.parse()
function and passed it into the credentials
property of GoogleAuth
. Looks something like this:
const auth = new google.auth.GoogleAuth({
credentials: JSON.parse(credentials_env_variable),
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论