deploying my inline editor code in Dialogflow Essentials to show webpage - actions-on-google

I want my app to show a webpage when I start my AoG, but I could not figure out how to make it possible with my code. Here's my code :
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const {dialogflow, HtmlResponse} = require('actions-on-google');
const CANVAS_URL = 'http://www.example.com';
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
agent.add(new Canvas({
url: CANVAS_URL,
}));
}
function fallback(agent) {
agent.add(`Fullfillment_Fallback`);
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
agent.handleRequest(intentMap);
});

Hey it seems like you're mixing a few programming libraries together in a way that doesn't work. Let's simplify this to only using actions-on-google. Note that some similar concepts are named differently.
In the actions-on-google library, the Canvas element is named HtmlResponse.
'use strict';
const functions = require('firebase-functions');
const {dialogflow, HtmlResponse} = require('actions-on-google');
const CANVAS_URL = 'http://www.example.com';
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
const app = dialogflow({debug: true});
app.intent('Default Welcome Intent', conv => {
conv.ask('Welcome to my agent!');
conv.ask(new HtmlResponse({
url: CANVAS_URL,
});
});
app.intent('Default Fallback Intent', conv => {
conv.ask('Fullfillment_Fallback');
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

Related

phantomjs unable to open local file

I am able to get the content of http://example.com but not the index.html which is in my code with phantomjs. I see the filePath is correct.
'use strict';
const express = require('express');
const phantom = require('phantom');
const path = require('path');
// Constants
const PORT = 8888;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open(getFileUrl('index.html'));
const content = await page.property('content');
console.log(content);
await instance.exit();
})();
});
function getFileUrl(str) {
var pathName = path.resolve( str );
if (pathName[0] !== "/") {
pathName = "/" + pathName;
}
return encodeURI("file://" + pathName);
};
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
Output
Running on http://0.0.0.0:8888
Requesting file:///home/codex/code/target-data-app/index.html
<html><head></head><body></body></html>

Why axios doesn't work with static nodejs server?

I'm having trouble getting my axios .get in production with React.
I created a nodeJS server with express to render my react page each time I want to refresh my page. That work.
But the problem is that it block my axios .get(). So, my page show normaly without the data I normaly get in dev mode.
BackEnd => server.js with sequelize module to manage my database
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
db.sequelize.sync().then(() => {
app.listen();
});
BackEnd => GovernmentCreate.js
const express = require('express');
const router = express.Router();
const { GovernmentCreate } = require('../models');
router.get("/", async (req, res) => {
const listOfGovernments = await GovernmentCreate.findAll({
include: {all: true}
});
res.json(listOfGovernments);
});
FrontEnd => Part of code inside my GouvernmentWall.js that is called with url https://www.mon-gouvernement.fr/gouvernement-galerie
const [governmentList, setGovernmentList] = useState([]);
axios.get(`https://www.mon-gouvernement.fr/GovernmentCreate`)
.then((res) => {
console.log(res.data);
const resData = res.data;
setGovernmentList(sortResData);
}).catch((err) => {
console.log(err);
});
After multi-searching I'm thinking that the problem come from these lines in my server.js :
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
But if I remove it, when I try to refresh my page I'm getting a white page diplay Cannot GET /gouvernement-galerie.
So I'm stocking with this issu. I need your help to move forward.
Problem solve !
As #jonrsharpe mentioned, I have to switch my .get('/*' to the bottom of my routes. My server.js look like :
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
//************************************************
// ROUTES
//************************************************
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
db.sequelize.sync().then(() => {
app.listen();
});

Make an OAuth request using flutter

I'm working with bricklink api http://static.bricklink.com/alpha/default/api_wiki.html
I'm unable to implement it in flutter, due to lack of expertise. Here is the request implementation in node.js and I want to replicate this in flutter.
const OAuth = require('oauth');
const fs = require('fs');
const http = require('http');
const host = '127.0.0.1';
const port = '7070';
const server = http.createServer((_req, res) => {
var oauth = new OAuth.OAuth('', '', 'consumer_key', 'consumer_secret', '1.0', null, 'HMAC-SHA1');
oauth.get('https://api.bricklink.com/api/store/v1/categories', 'token_value', 'token_secrete', function(error, data, res) {
if (error) return false;
var json = JSON.parse(data);
saveData(json);
});
function saveData(data) {
const jsonData = JSON.stringify(data);
fs.writeFileSync('inventory.json', jsonData);
res.statusCode = 200 || 201;
// res.setHeader('Content-Type', 'text/plain');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.end('Done');
console.log('Done');
}
});
I want to implement this request in flutter.
Thank You

agent.add not working but console.log working

In below code, "agent.add" is not working but "console.log" is working. I have added promise with resolve and reject, but still its not working. I have tried different ways but multiple response from firestore, not able to send it to user. Able to see logs in firebase but not in dialogflow.
const {Firestore} = require('#google-cloud/firestore');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging
statements
const firestore = new Firestore();
const settings = {/* your settings... */
timestampsInSnapshots: true};
firestore.settings(settings);
exports.dialogflowFirebaseFulfillment =
functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' +
JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
const db = admin.firestore();
```
function welcome(agent) {
agent.add(`Welcome to my agent!`); // not working
console.log("Welcome Agent");
const num = agent.parameters.number;
let usersRef = db.collection('add');
let query = usersRef.where('Number', '==', num);
return new Promise((resolve,reject)=>{ // not working
return query.get()
.then(querySnapshot => {
if (querySnapshot.empty) {/*
const timestamp = querySnapshot.get('created_at');
const date = timestamp.toDate();*/
console.log('No matching documents.');
agent.add(`No Matching Documents`);
return;
}
querySnapshot.forEach(doc => {
const line1 = doc.get('Line1');
const line2 = doc.get('Line2');
const explain = doc.get('explanation');
console.log('Line1: ', line1); //this works
console.log('Line2: ', line2); //this works
console.log('explain: ', explain); //this works
agent.add(`your response is ` +doc.get('Line1')); //not working
agent.add(`Final Response - ${line2}`); //not working
agent.add(doc.get('explanation')); //not working
});
resolve('resolved');
})
.catch(err => {
console.log('Error getting documents', err);
reject(err);
});
});
}
Issue is resolved now. Added return statement in the last agent.add and it is working. Thanks.
agent.add(your response is +doc.get('Line1'));
agent.add(Final Response - ${line2});
return agent.add(doc.get('explanation'));

How to use mockgoose (or any other db mocking) in express app integration test

Using mockgoose in a simple unit test is quite straight-forward. However I'm a bit fuzzy as to how one would go about using mockgoose or other mocking solutions in an acceptance or integration test.
Given a simple express/MongoDB app like the following:
/*app.js*/
const express = require('express')
const app = express()
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var greetingSchema = mongoose.Schema({
greeting: String
});
var Greeting = mongoose.model('Greeting', greetingSchema);
app.get('/', function (req, res) {
Greeting.find({greeting: 'Hello World!'}, function (err, greeting){
res.send(greeting);
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
and a simple integration test like this:
/*test.js*/
const app = require('app.js');
const request = require('supertest');
it('sends "Hello World!" on the response body', (done) => {
request(app)
.get('/')
.expect(200, 'Hello World!', done);
});
});
By using the actual app in the request, we are connecting to the app's database ('mongodb://localhost/test'). How then can one use mockgoose, or any other solution, to mock the MongoDB database and still run an integration test like the one shown above?
I had the same problem as you. In my case, I solved using chai + chai-http and breaking the db connection and app in different files:
db.js:
const mongoose = require('mongoose');
const config = require('../../config');
mongoose.Promise = global.Promise;
mongoose.set('debug', process.env.DEBUG != undefined);
function open(){
return new Promise((resolve, reject) => {
if(process.env.DEBUG != undefined) {
let Mockgoose = require('mockgoose').Mockgoose;
let mockgoose = new Mockgoose(mongoose);
mockgoose.helper.setDbVersion("** your mongodb version **");
mockgoose.prepareStorage().then(function() {
mongoose.connect(config.db_test, (err, res) => {
if (err) return reject(err);
resolve();
});
}).catch(reject);
}else{
mongoose.connect(config.db, (err, res) => {
if (err) return reject(err);
resolve();
});
}
});
}
function close(){
return mongoose.disconnect();
}
module.exports = { close, open };
app.js:
const express = require('express');
const bodyParser = require('body-parser');
const api = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api', api);
module.exports = app;
test.js (for test):
const chai = require('chai');
const chaiHttp = require('chai-http');
const expect = chai.expect;
const conn = require('./../utils/db'); // <-- db.js
const app = require('../../app'); // <-- app.js
chai.use(chaiHttp);
describe('# Test', function(){
before(function(done) {
conn.open().then(() => done()).catch(done);
});
after(function(done){
conn.close().then(() => done()).catch(done);
});
it(`test something`, function(done){
chai.request(app) // <-- pass the app here
.get('/path/to/test')
.then((res) => {
// expects
done();
})
.catch((err) => {
done(err);
});
});
});
index.js (for development or production):
const conn = require('./utils/db'); // <-- db.js
const app = require('./app'); // <-- app.js
const config = require('./config');
conn.open().then(() => {
app.listen(config.port, () => {
// OK!
});
});
I hope it works for you or anyone.