I am working on a Discord bot which could extract datas from an Excel sheet. For example when I will ask the bot : "!adress paul", I would like the bot to look for "paul" value in the column A of a sheet and return the value of the column B (of the row where the value Paul is) in the discord app.
So far, I succeeded to read data from the Excel sheet and report the datas in the console.log (when I call the console.log inside the function). However each time I call the value out of the function I have a 'Promise {}' that appears... I made many many research on the web, without finding the solution.
const discord = require('discord.js');
const {google} = require('googleapis');
const keys = require('./identifiants.json');
// Creation of the Spreadsheet client
const client1 = new google.auth.JWT(keys.client_email, null,
keys.private_key, ['https://www.googleapis.com/auth/spreadsheets']);
client1.authorize(function(err, tokens)
{
if(err)
{
console.log(err);
return;
}
else
{
console.log('Connected to Google Sheets');
}
});
// Creation of the Discrod client
const client2 = new discord.Client();
client2.on('ready', () =>
{
console.log('Connected to Discord');
});
// Create an event listener for messages
client2.on('message', message =>
{
if (message.content === '!address')
{
console.log("OK 1");
let paul = address(client1);
console.log(paul);
console.log("OK2");
}
});
async function address(client)
{
const gsapi = google.sheets({version:'v4',auth: client });
const opt1 = {spreadsheetId: 'ID OF MY SPREADSHEET', range: 'Sheet1!A1:B3'};
let data = await gsapi.spreadsheets.values.get(opt1);
return data.data.values;
}
client2.login("MY CLIENT LOGIN")
In the console the message "Promise {pending}" appears between "OK1" and "OK2". Can someone help me on that case please? I would be very grateful
Your address
function is an async function so it will return a promise.
Therefore, you will need to use then
to get the value:
client2.on('message', message => {
if (message.content === '!address') {
address(client1)
.then(paul => {
console.log(paul);
});
}
});
Alternatively, you could use async-await:
client2.on('message', async (message) => {
if (message.content === '!address') {
let paul = await address(client1);
console.log(paul);
}
});