Use a Firestore Database in Dialogflow project - firebase

I want to integrate my Firestore using data I got in my Dialogflow project.
I was searching in the net and I found just some random things.
I wrote some console.log inside, because I want to understand how does it work, but nothing seems happening, and I don't even know where I can find my logs.
Here it is my index.js Dialogflow code:
'use strict';
// Import the Dialogflow module from the Actions on Google client library.
//const {dialogflow} = require('actions-on-google');
const {dialogflow,Permission,SimpleResponse,Image,Carousel,BrowseCarousel,BasicCard,Button,BrowseCarouselItem,Suggestions,List,MediaObject} = require('actions-on-google');
// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
admin.initializeApp(functions.config().firebase);
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
console.log('Request headers: ');
});
Is there something I am missing?
Sorry, but it's my first time using Dialogflow.

Since you're using the built-in editor, your logs will be in the Firebase Cloud Functions logs section. To get there
Go to https://console.firebase.google.com/ and select your project.
Select "Functions" on the left navigation.
Select "Logs" in the navigation towards the top.

Related

How to use Telegraf (Telegram) in Firebase?

I'm trying use Telegraf library with Firebase Functions but it's not working as I expected.
I follow these this article and instructions as appear in webhooks (as appears for express example) and webhookcallback as appear in telegraf docs.
const Telegraf = require('telegraf')
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions')
// The Firebase Admin SDK to access the Firebase Realtime or Firestore Database.
const admin = require('firebase-admin')
// set telegraf and responses.
const BOT_TOKEN = 'my-telegram-bot-token'
const bot = new Telegraf(BOT_TOKEN)
bot.start((ctx) => ctx.reply("Start instructions"))
bot.help((ctx) => ctx.reply("This is help"))
bot.hears('hi', (ctx) => ctx.reply('Hola'))
bot.on('text', (ctx) => ctx.reply('Response to any text'))
bot.catch((err, ctx) => {
console.log(`Ooops, ecountered an error for ${ctx.updateType}`, err)
})
// initialize bot
bot.launch() // <-- (2)
//appends middleware
exports.ideas2coolBot = functions.https.onRequest(bot.webhookCallback(`/my-path`));
In firebase server I need add bot.launch() (2) to get worked, but it works just for max timeout set in Firebase Function. I need to recall Telegram "setWebhook" API to get work again and it works for the same time. It's like it's generate one function instance and shut down when time is over.
I noted the telegraf.launch() have options to start in poll or webhook mode but its not pretty clear for me how to use this options.
How should I use telegram.launch() to get worked in webhook mode in Firebase?
Edit:
When I used getWebhookInfo I get this result:
{
"ok": true,
"result": {
"url": "https://0dbee201.ngrok.io/test-app-project/us-central1/testAppFunction/bot",
"has_custom_certificate": false,
"pending_update_count": 7,
"last_error_date": 1573053003,
"last_error_message": "Read timeout expired",
"max_connections": 40
}
}
and console shows incoming conection but do nothing...
i functions: Beginning execution of "ideas2coolBot"
i functions: Finished "ideas2coolBot" in ~1s
Edit2:
I've been trying adding Express too...
app.use(bot.webhookCallback('/bot'))
app.get('/', (req, res) => {
res.send('Hello World from Firebase!')
})
exports.ideas2coolBot = functions.https.onRequest(app);
it's works '/' path but got nothing with '/bot'. POST to '/bot' not response.
By the way, I tried a express standalone version and works prefect, but using it with firebase doesn't respond ("Read timeout expired").
delete
bot.launch()
try add this
exports.YOURFUNCTIONNAME = functions.https.onRequest(
(req, res) => bot.handleUpdate(req.body, res)
)
then set ur webhook manually
https://api.telegram.org/bot{BOTTOKEN}/setWebhook?url={FIREBASE FUNCTION URL}'

Dialogflow fullfilment on firebase function if ask from telegram

I wrote function which work on firebase function and which take an answer on request if request come from the dialog console or the Google Assistant emulator. But if I ask from Telegram this function doesn't work.
Answer like Say that one more time? or if I filled the form Responses on web I have this response.
How connect firebase function with Telegram?
'use strict';
const {
dialogflow,
Permission,
Suggestions,
BasicCard,
} = require('actions-on-google');
const firebase = require('firebase');
const functions = require('firebase-functions');
const app = dialogflow({debug: true});
app.intent('simple word', (conv) => {
conv.ask(`it's ok`);
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
The problems is that you're using the actions-on-google library, which is specifically designed to send results to the Assistant.
If you want to be able to send results to Telegram, you need to use the dialogflow-fulfillment library, which handles things slightly differently.

Integrate Firebase with 3rd party API

I'd like to integrate my firebase project with some 3rd party API's, like the twitter API.
3rd party API
The following code will listen to new tweets containing the certain text 'little rocket man':
var Twitter = require('twitter');
// setup new twitter client
var client = new Twitter({
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
// open new twitter stream
let stream = this.client.stream('statuses/filter', { track: 'little rocket man' });
stream.on('data', (event: any) => {
let tweetText = event && event.text; // this should be written to the firebase db
});
Firebase Cloud Functions
The following firebase cloud functions listens to incoming HTTP GET requests on a specific route and saves data back to the firebase db:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'; // Firebase Admin SDK
admin.initializeApp(functions.config().firebase);
// this example uses a HTTP trigger, but how can I trigger it whenever new tweets containint 'little rocket man' are detected??
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.database().ref('/messages').push({original: original}).then(snapshot => {
res.redirect(303, snapshot.ref);
});
});
Question
How can I write the tweets I'm recieving from the twitter client back to the firebase db? If possible, I'd like to run all the code on firebase cloud functions.
Disclaimer:
I'm new to firebase and although googling around for a few hours I wasn't able to find the solution to my problem on the net. I'd like to apologize in advance, should I have overseen it.
You can't use streaming APIs like this in Cloud Functions. A function may only respond to some distinct event, such as an HTTP request, or some change in your database. Functions can't run indefinitely.
If you want to collect tweets that match some query into your database, you can use IFTTT to periodically send them to a function as they become available. I recently finished a small project that does exactly that.

Calling Google AppScript Web App from Cloud Functions for Firebase

I'm trying to get my Cloud Functions for Firebase to call a simple web app deployed using Google Apps Script. Can someone please point to any example or help figure out whats the reason for the error in my code below. Really appreciate your help.
--
I've created a simple webapp with Google Apps Script.
function doGet() {
return ContentService.createTextOutput('Hello world');
}
And I'm calling this using request-promise within my Firebase Cloud Function. I've tried to be as close to the Google Translate example given for Cloud Functions. However, I get the following error when the Cloud Function is invoked.
RequestError: Error: getaddrinfo ENOTFOUND script.google.com
script.google.com:443
Here is my Cloud Function code -
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const request = require('request-promise');
exports.makeUppercase =
functions.database.ref('/users/{userid}/logs/{logid}/mykey')
.onWrite(event => {
var url = `https://script.google.com/macros/s/.../exec`;
var retstr = request(url, {resolveWithFullResponse: true}).then(
response => {
if (response.statusCode === 200) {
const data = response.body;
return event.data.ref.parent.child('uppercase').set(data);
}
throw response.body;
});
});
Thanks in advance,
Regards
Rahul
I had the same issue and found this answer(https://stackoverflow.com/a/42775841).
Seems like calling Google Apps Script is considered external.

How Firebase Cloud functions handle HTTP post method?

I have created Firebase Cloud Functions app,
I created function with https.onRequest.
and get data with req.body but there is not data there.
Can Firebase Cloud Functions can handle HTTP POST method?
This is my sample code:-
var functions = require('firebase-functions');
exports.testPost = functions.https.onRequest((req, res) => {
console.log(req.body);
});
I tested by postman with POST method but didn't show result in Firebase log.
Functions built on Firebase can also use Express.js routers for handling GET/POST/PUT/DELETE, etc... is fully supported by Google, and is the recommended way to implement these types of functions.
More documentation can be found here:
https://firebase.google.com/docs/functions/http-events
Here's a working example built on Node.js
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');
const app = express();
// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
app.get('/hello', (req, res) => {
res.end("Received GET request!");
});
app.post('/hello', (req, res) => {
res.end("Received POST request!");
});
// Expose Express API as a single Cloud Function:
exports.widgets = functions.https.onRequest(app);
Then, run firebase deploy, and that should compile your code and create the new "widgets" function. Note: You can rename widgets to anything you want. Ultimately, it will generate a URL for calling the function.
I am planning to do the same thing. What I reckon the approach should be is to check the request.method in the function body. A probable approach can be:
if (request.method != "POST") {
respond.status(400).send("I am not happy");
return;
}
// handle the post request
Here's some reference to the details regarding what the request object holds: https://firebase.google.com/docs/functions/http-events
Firebase functions support GET, POST, PUT, DELETE, and OPTIONS method, and you can check what kind of methods that trigger your function.
// Check for POST request
if(request.method !== "POST"){
res.status(400).send('Please send a POST request');
return;
}
Then to get data from POST request (for example JSON type) will be in the header of your request.
const postData = request.body;
// for instance
const format = req.body.format;
// query string params
let format = req.query.format;
Maybe your project hasn't been setup to communicate with your firebase database. Try the following from your terminal:
npm install -g firebase-tools
Then inside your project folder, run the following and login using your credentials
firebase login
Then
firebase init functions
This will create a folder with index.js, package.json and node_modules
If you are using Postman correctly the rest of your code should work.

Resources