I am trying to access the [object Promise] data from my fb messenger chat bot response. When I send the url to scrape via the chat bot the response comes back [object Promise] how do I resolve this and get access to my data?
The code below is what I have tried but to no avail. The getProductInfo()
returns the data I need in an object. And sendText()
function is called in app.post()
that sends the data to chat bot. What am I missing?
const puppeteer = require('puppeteer');
const $ = require('cheerio');
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
const VERIFY_TOKEN = "verify_token";
const ACCESS_TOKEN = "access_token";
var productInfo = {};
app.set('port', (process.env.PORT || 5000))
// Allows us to process the data
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.get('/webhook/', function(req, res) {
if (req.query['hub.verify_token'] === VERIFY_TOKEN) {
res.send(req.query['hub.challenge'])
}
res.send("Wrong token")
})
app.post('/webhook/', function(req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = messaging_events[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let url = event.message.text
let result = getProductInfo(url)
sendText(sender, "Text echo: " + result)
}
}
res.sendStatus(200)
})
function sendText(sender, text) {
let messageData = {text: text}
request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs : {access_token: ACCESS_TOKEN},
method: "POST",
json: {
recipient: {id: sender},
message : messageData,
}
}, function(error, response, body) {
if (error) {
console.log("sending error")
} else if (response.body.error) {
console.log("response body error")
}
})
}
async function getProductInfo(url) {
try{
const browser = await puppeteer.launch(
{ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1920,1080','--user-agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'] }
);
const page = await browser.newPage();
await page.goto(url);
await page.waitForSelector('body');
let productTitle = await page.evaluate(() => document.body.querySelector('#productTitle').innerText);
productInfo.title = productTitle;
return productInfo;
}
catch(error){
console.log('Catch an error: ', error)
}
}