javascriptnode.jsdiscord.jsgoogle-apis-explorer

Where can I put an async function so I can use await to send a discord response?


I am pulling data from a Google Sheet and after some help, I have reached the point where the discord bot is responding to the inquiry, with the correct data, but it responds with each row of the map array in separate responses rather than gathering the data and sending it in one message. So I believe I need to use an async function and the await feature. I just can't seem to figure out where or how to put it in. I've been stuck on this for a few hours now and can't seem to get it to work?

Here is my code:

const { google } = require('googleapis');
const { sheets } = require('googleapis/build/src/apis/sheets');
const keys = require('../Data/client_secret.json');
const { Team, DiscordAPIError } = require('discord.js');
const Command = require("../Structures/Command");

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


module.exports = new Command({
    name: "freeagents",
    description: "Potential free agents for next season.",
    async run(message, args, client) {

        gclient.authorize(function(err,tokens){

            if(err){
                console.log(err);
                return;
            } else {
                console.log("Connected!");
                gsrun(gclient);
            }
        
        });

    async function gsrun(cl){

        const gsapi = google.sheets({version:'v4', auth: cl });
        gsapi.spreadsheets.values.get({
            spreadsheetId: "11e5nFk50pDztDLngwTSmossJaNXNAGOaLqaGDEwrbQM",
            range: 'Keepers!C1:F',
            
        }, (err, res) => {
            if (err) return console.log('The API returned an error: ' + err);
            const rows = res.data.values;
    
            if (rows.length) {
              const cells = rows.filter(cell => cell[3])
              cells.map((cell) => {
                
                console.log(`${cell[0]}, ${cell[1]}`);
                console.log(`${cells}`);
                return message.reply(`${cell[0]}, ${cell[1]}`);
              });
            } else {
              console.log('No data found.');
            }
    
           
        })
    
    };
}
});

Any help would be greatly appreciated!


Solution

  • You're receiving multiple messages because you're sending the message inside cells.map((cell) => {}). That method will call a function on each member of the array. You should instead iterate over the cells array to produce a single string that you can then send as a message, for example:

    const strings = [];
    
    for (let cell of cells) {
        strings.push(`${cell[0]}, ${cell[1]}`);
    }
    
    return message.reply(strings.join("\n"));