How to make a post using WATSON and Node js? - node.js

I want to make a POST (add a new task) through chatting with Watson.
I have the POST function which works very well, I tested it on Postman. And I have the Watson nodes created.
Here is my endpoint from the POST in Node js:
MainRouter.post('/welcome', (req, res) => {
TaskPost.postTask(req.body).then(message => {
return res.json(message);
}).catch((error) => {
return res.status(404).json(error);
});
});
Here is my conversation with Watson (is working very well):
I also included this in the main.js and changed the password and url:
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');
const assistant = new AssistantV2({
authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
serviceUrl: 'https://api.us-south.assistant.watson.cloud.ibm.com',
version: '2018-09-19'
});
How do I make this connection ? What do I have to include?

I would recommend the official Node.js SDK for the IBM Watson services. It includes support for Watson Assistant and is easy to use.
If you still want to use the V2 API directly, then take a look at how the SDK utilizes the API. As alternative, the API docs for Watson Assistant have code snippets for Node.js.
The basic flow is that you authenticate, then establish a session, and finally send messages with the user input to Watson Assistant.
To get to your dialog node with the task, the user (or your code) would need to send the right intents and entities for navigating from the root node to that specific subnode.

Related

React native and IBM Watson

I have been using expo to build a react native app and would like to integrate an IBM Watson chatbot onto my platform. When I import the module however I receive a lot of error messages as core node modules such as os and fs seem to be missing, but aren't downloaded with node.js for some reason. When I try and add these manually, the HTTPS module is missing the index.js file. Is there any way for me to find this file or resolve this problem another way?
It's not completely clear from your question but I shall assume that you are using the Node SDK for Watson Assistant. This is designed to be run in a Node.js environment which a react native JavaScript bundle is not (with or without expo). That's why you are missing key libraries like os and fs which the Node SDK expects. Installing fs won't resolve your problem because it also expects a Node.js environment to work, hence why there are react native specific fs libraries that are able to use ios and android code to interact with the file system of the phone.
What you should be attempting is running the Node SDK on an independent server and running simple api requests using libraries like axios or for more robust production systems graphql so that your architecture will approximate this high level design.
a high level architecture diagram which shows a phone connected by an arrow reading axios api request to another box labelled cloud hosted server. From this box another arrow labelled Node SDK is pointing to another box labelled Watson Assistant
Web applications are similarly limited. The code run on the user's browsers can't directly use the Watson Assistant SDK, these requests to Watson Assistant need to be run by a server. There is an example starter Watson Assistant web application that does this. If you run or host this application you can use the same server for your requests (although bear in mind this simple app and shared traffic probably isn't scalable for anything but a proof of concept).
So rather than running the api requests to Watson Assistant directly you run them to this domain of the server and then the necessary endpoint. The server in the example app is set up to accept requests to start the session at <your domain>/api/session and to send messages at <your domain>/api/message
You optionally can run direct api calls to Watson Assistant from a react native app without the SDK. It's not advisable because you would need to store your private keys on the device where they could be viewed by anyone.
Here is a functional component that is able to complete api calls direct to Watson Assistant using the v1 of the message tool without the SDK. BUT IT IS NOT ADVISED BECAUSE I MUST STORE MY KEYS INSECURELY.
import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import axios from 'axios';
import base64 from 'react-native-base64';
const workspace = ''; //replace with your own workspace id
const key = ''; //replace with your own key
const encodedKey = base64.encode(`apikey:${key}`);
// the following url will be different depending on where you host your Watson Assistant
// this is for Frankfurt as an example hence eu-de in the domain name
const assistantInstance =
'https://api.eu-de.assistant.watson.cloud.ibm.com/instances/<This is your own>/v1'; //replace with your own
const ExampleComponent = () => {
const [response, setResponse] = useState('');
const sendMessage = () => {
axios
.post(
`${assistantInstance}/workspaces/${workspace}/message?version=2018-09-20`,
{
input: { text: 'This is the message' },
},
{
headers: {
Authorization: `Basic ${encodedKey}`,
'Content-Type': 'application/json',
},
},
)
.then((data: any) => {
console.log(data);
setResponse('Got response');
})
.catch((err: any) => {
console.log(err);
setResponse('Got an error');
});
};
return (
<View>
<Text>{response}</Text>
<TouchableOpacity
onPress={() => {
sendMessage();
}}
>
Send message
</TouchableOpacity>
</View>
);
};
export default ExampleComponent;
The next complication you will find is that you will need to add code to store the context returned in the response otherwise your state is lost. Your body would end up looking something like
{
input: { text: 'This is the message' },
context: savedContextObject
},
The newer version of the API has a stateful version which you may want to use instead. You can use this axios as a pattern for constructing whatever requests your prefer.
For the third and final time PLEASE DO NOT SAVE TO THE JS FILE YOUR API KEY as I do here. This is just as an example and for proof of concepts. Anyone who downloads your app will be able to unzip your apk and read these strings in your generated JS bundle unencrypted!

How can I deploy a discord.js bot to Cloud Functions?

I want to deploy a Discord bot running on discord.js to Firebase Cloud Functions but I can't get the bot to run in Firebase. If I use nodemon it runs perfectly but if I use firebase deploy it will not start the bot.
Here is my current code:
const functions = require('firebase-functions');
require('dotenv').config();
const token = process.env.TOKEN
const Discord = require('discord.js')
const Client = new Discord.Client();
Client.on('ready', () => {
Client.channels.find(x => x.name === 'main-cannel').send('bot is deployed')
Client.user.setGame(`The Cult | ${Client.guilds.size} servers`)
Console.log('test')
});
Client.login(token);
//is is not working but de basic
//export.App = functions.... {Client}
exports.app = functions.https.onRequest((request, response) => {
response.send("Test");
});
This may not be the best combination of google cloud platform services, since cloud functions where not designed with this in mind. You can just host your Discord bot on a compute engine machine.
If you want to use the dynamic scaling have a look at Discord Microservice Bots where DasWolke describes what microservices are. Hey also included his javascript code to split up the different services for Discord.
What you can do on Google cloud platform specifically, is creating a VM with the Gateway running. This needs to run 24/7 and should be lightweight. You can use an f1-micro (which is free) for this though google recommends a g1-small for the task.
The gateway should filter the events you are looking for (because Discord sends a lot of events and you don't need most) and send the data to cloud function or cloud run (you can send the data via pub/sub). In my experience, a cloud run has much shorter startup times so I went with that.
Inside your function, you receive the data do with it what you want. If you want something in Discord (send a message, manage channels, ...) you can use SnowTransfer for that. SnowTransfer just calls the rest API on discord.
Put client.login(token) into where response.send("Test"); is. This will prompt your bot's code to execute upon an HTTP request.
In https://us-central1-<your project ID>.cloudfunctions.net/app, replace <your project ID> with your project's ID.
If Firebase Hosting gives you the URL example-123.web.app, your project ID is example-123. You can also get your project ID through the console: open the Firebase console, select your project, click the settings icon, go to "Project settings," and its ID is on the second line of the table.
For this to work, you have to move your token straight into the code. You can't use a shell file like .env.
In the end, your code will be:
const functions = require('firebase-functions');
const token = 'whatever the token is';
const Discord = require('discord.js')
const Client = new Discord.Client();
Client.on('ready', () => {
Client.channels.find(x => x.name === 'main-cannel').send('bot is deployed')
Client.user.setGame(`The Cult | ${Client.guilds.size} servers`)
Console.log('test')
});
exports.app = functions.https.onRequest((request, response) => {
response.send("Test"); // Do not delete this! Your request will time out if you do.
Client.login(token);
});
As Gabber235 noted, this is probably not the best Google Cloud Platform service to use for this, and you should probably use Compute Engine.

How to test http request on Dialogflow Fulfillment with the Inline Editor

I am testing Dialogflow Fulfillment with the Inline Editor.
What I am trying to do is a http request using que 'request' library.
Here is the code I am using:
const requesthttp = require('request');
requesthttp('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body.url);
console.log(body.explanation);
});
But It returns me an error of not found.
I also noticed an alert on my Dialogflow with the following message:
"Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions."
So... Probably I can't test this piece of code without configuring a billing account.
My question is... Is there a url that I can use to test this code?
Or the only way for me to test this code is configuring a billing account and paying for it?
Thanks in advance
There are a number of approaches to testing your code.
If you want to continue to use Dialogflow's Inline Editor, you will need to setup Firebase to use a payment plan. However, the Blaze plan is "pay as you go" after a basic level of use. This level of use should be sufficient to cover most testing (and even very light production) uses of the service without imposing a charge. Once your Action has been approved, you're able to receive credits for the Google Cloud Platform, which can be applied to this use in case you go over the minimum level.
You can also use Firebase Cloud Functions, which the Inline Editor is based on, and your own local editor. One advantage of this is that you can serve the function locally, which has many of the same features as deploying it, but doesn't have the URL restriction (it is your own machine, after all). You can use a tool such as ngrok to create a secure tunnel to your your machine during testing. Once you have tested, you can deploy this to Firebase with a paid plan.
You can, of course, choose to use any other hosting method you wish. Google and Dialogflow allow you to run your fulfillment webhook on any server, as long as that server can provide an HTTPS connection using a valid, non-self-signed, certificate. If you're using node.js, you can continue to use these libraries. If you wish to use another language, you will need to be able to parse and return JSON, but otherwise you have no restrictions.
There are a lot of ways to create your own server like using NodeJS client with Express.JS which you can expose to the internet using NGROK as webhook for fulfilment.
Develop a webhook. You can use different client libraries in NodeJS (AoG Client or Dialogflow Client) or in Python (Flask-Assistant or Dialogflow Client) or can create your own just using JSON request/response with Dialogflow and Action-on-Google.
Once the webhook is ready, run it locally and expose to the internet using NGROK.
Start with following code for Actions-on-Google with Express.JS
'use strict';
const {dialogflow} = require('actions-on-google');
const express = require('express');
const bodyParser = require('body-parser');
const app = dialogflow();
app.intent('Default Welcome Intent', conv => {
conv.ask('Hi, Welcome to Assistant by Express JS ');
});
express().use(bodyParser.json(), app).listen(8080);
Since DF uses firebase cloud functions you can use https as in nodejs. But requesting domains outside of the google/firebase universe will require the paid version of firebase.
const https = require('https');
return new Promise((resolve, reject) => {
const hostname = info.hostname;
const pathname = info.pathname;
let data = '';
const request = https.get(`https://${hostname}${pathname}`, (res) => {
res.on('data', (d) => {
data += d;
});
res.on('end', resolve);
});
request.on('error', reject);
});

Cloud Functions for Firebase and third party api

My problem is to make use of an API along with Firebase Functions, the API in question is Coinbase, I use the API with node, if I test in the terminal with the node command it works, however when I use it with Firebase Functions Does not work at all, I've been trying to solve the problem for almost a week now.
The code is as follows>
var functions = require('firebase-functions');
var Client = require('coinbase').Client;
var client = new Client({
"apiKey": "xxxxxxxxxxxx",
"apiSecret": "xxxxxxxxxxxxxxxxxxxxxxx"
});
exports.helloWorld = functions.https.onRequest((request, response) => {
this.client.getAccounts({}, function(err, accounts) {
if(accounts){
response.send(accounts);
}else{
response.send(err);
}
});
});
The error: https://us-central1-investimentos-b7406.cloudfunctions.net/helloWorld
The Coinbase API: https://developers.coinbase.com/docs/wallet/guides/bitcoin-wallet
There's a warning in the docs:
Firebase projects on the Spark plan can make only outbound requests to
Google APIs. Requests to third-party APIs fail with an error. For more
information about upgrading your project, see Pricing.
So you'll need to upgrade to a paid plan to use external APIs.

Calling Watson Conversation API from behind a Proxy server using Node.js

I am using Watson Node.js SDK https://www.npmjs.com/package/watson-developer-cloud to send a message to Watson Conversation service, but I'm behind a http proxy and not able to reach to the Watson service. How might we configure proxy details (either inside or outside of Node.js) so that the the outbound API call can be made?
var Watson = require( 'watson-developer-cloud/conversation/v1' ); // watson sdk
// Create the service wrapper
var conversation = new Watson( {
username: '<username>',
password: '<password>',
url: 'https://gateway.watsonplatform.net/conversation/api',
version_date: '2016-09-20',
version: 'v1'
});
conversation.message( payload, function(err, data) {
...
});
Not completely sure about this but can you set the environment variable for http_proxy? I believe that this should force the use of the proxy regardless of the what the developer cloud module does.
process.env.http_proxy = "https://YOUR_PROXY_HOST:YOUR_PROXY_PORT";
If that works you should set the variable using:
npm set <key> <value>

Resources