简体   繁体   中英

How can I use google sheets api data in discord.js embed?

I'm setting up my first discord bot, which will be able to take data from a Google Spreadsheet, from the official API and bring it as a embed message in discord. The problem is at the level of the .addField(), where I can not enter the value of the cell. How can I do this?

const { Client, RichEmbed } = require('discord.js');
const client= new Client();
const GoogleSpreadsheet = require('google-spreadsheet');
const {promisify} = require('util');
const creds = require('./client_secret.json');

client.on('message', message => {
    if (message.content === '!bot'){

        async function accessSpreadsheet() {
            const doc = new GoogleSpreadsheet('1qA11t460-ceILmwu6RtfiPGb_n9MUD_7z6Ld7I_Z6yc');
            await promisify(doc.useServiceAccountAuth)(creds);
            const info = await promisify(doc.getInfo)();
            var sheet = info.worksheets[0];

            var cells = await promisify(sheet.getCells)({
                'min-row': 2,
                'max-row': 5,
                'min-col': 3,
                'max-col': 3,
                'return-empty': true,
            })
            for (var cell of cells) {
                message.author.send(cell.value)
            }
        }

        accessSpreadsheet();
        const embede = new RichEmbed()
    .setColor('#0099ff')
    .setTitle("My Title")
    .addBlankField()
    .setDescription('Some description')
    .addBlankField()
    .addField('Name', '•'+ cell[1].value , true)
    .setTimestamp();

        message.author.send(embede) }
})
client.login('xxx')

I expect the output "Terrassycup 3", but the actual output is "ReferenceError: cell is not defined" in console.log

A few issues I see with your code:

  • accessSpreadsheet() doesn't return any values it accesses.
  • accessSpreadhseet() returns a Promise since it's declared as async , but it's never awaited.
  • The scope of cell is within the for...of loop inside the accessSpreadsheet() function, yet you try to use it well outside of it.

Instead of sending each individual value to the user, you can add them as fields to the embed (the limit is 25) within the function you declare.

async function accessSpreadsheet(embed) {
  // Insert the code already being used up to the for loop.

  for (let i = 0; i < 25 && cells[i]; i++) embed.addField('Name', `•${cells[i].value}`, true);
}

var embed = new RichEmbed()
  .setColor('#0099ff')
  .setTitle('**Spreadsheet Info**')
  .setDescription('Showing as many values as possible...');

accessSpreadsheet(embed)
  .then(() => message.author.send(embed))
  .catch(console.error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM