How to use botkit with facebook and wit.ai - facebook

I am a novice in chatbot development and I would like some help.
While it seems quite simple to connect botkit with facebook messenger and wit.ai in orger to use NLP. I haven't managed to do so. My initial goal is to have a simple conversation like hello-hello but using wit.ai as middleware.
Below I attach the code. What it should do is receive a "hello" message, pass it to wit.ai and then respond "I heard hello!" as a reply (without using wit at this stage). Instead I just receive
debug: RECEIVED MESSAGE
debug: CUSTOM FIND CONVO XXXXXXXXXXXXXX XXXXXXXXXXXXXX
debug: No handler for message_received
after every message I send to facebook messenger bot. In wit it seems like I am getting the messages since I receive messages in my inbox to update the intents.
If there is any code much simpler than the one below I would be very happy to have it so that I can start with something much simpler :).
Thanks
<pre><code>
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}
var Botkit = require('./lib/Botkit.js');
var wit = require('./node_modules/botkit-middleware-witai')({
token: process.env.wit,
minConfidence: 0.6,
logLevel: 'debug'
});
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');
const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);
if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}
var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});
var bot = controller.spawn({
});
controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});
tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});
controller.middleware.receive.use(wit.receive);
controller.hears(['hello'], 'direct_message', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}

Make sure you have a few conversations in Wit.ai beforehand so for example hello there and highlight the hello in that statement as something like, greetings.
Now i'm not sure what your intents are called in wit.ai but in your statement controller.hears(['hello'] you're actually listening to the wit.ai intents. So in the example i mentioned above, we'd be using hears(['greetings']) since that's the intent in wit.ai.
Also, instead of using direct_message use message_received this is what it should look like:
controller.hears(['hello'], 'message_received', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
If you're struggling tracking down the problem you can stick a console statement in your controller so something like console.log("Wit.ai detected entities", message.entities); and see what you get back from that.
Let me know if you're still having any issues :)

Related

How we do Exception handling in protractor-cucumber and do a email notification

I am using Protractor-Cucumber framework with protractor 5.2.2 and cucumber 3.2. I have a requirement of posting in no.of locations. So I have written a script in a loop for it. But it randomly fails before completing the loop. So when the script ends abnormally, is there like an exception handling section that gets control before exiting.The script can be fail due to any of the reasons like web driver issue,NoSuchElementError,ElementIsNotIntractable,ElementIsNotVisible etc.So whatever be the issue I have to handle that, and if it fails, I have to do an email notification. I have tried try catch, as given below, but it does not work for me.
When(/^I login$/, function () {
try{
element(by.css(".signin")).click();
var count=post_details.length ;
for (var i=0; i<count; i++){
post();
}
}
catch(e){
console.log("failed");
}
});
How we can do this in protractor-cucumber.Thanks in advance
For the exception problem you can try this. ignoreUncaughtException
For the email part create a hooks.js file. Here you can setup the After() function, to check your scenario fails or not. Cucumber Docs.
Example:
After(function (scenario) {
if (scenario.result.status === Status.FAILED)
{
failed = true;
const attach = this.attach;
//creates a screenshot for the report
return browser.takeScreenshot().then(function(png) {
return attach(new Buffer(png, "base64"), "image/png");
});
}
});
Then you can use nodemailer to send messages. Nodemailer
In your AfterAll() function you can handle the send part.
Example:
AfterAll(function(callback){
console.log("AfterAll");
if (failed)
{
var transporter = nodemailer.createTransport(
{
host: 'host.com',
port: xx,
secure: false,
//proxy: 'http://10.10.10.6:1098',
auth: {
user: userMail,
pass: pw
}
});
var mailOptions = {
from: 'xx', // sender address (who sends)
to: xxxxxx#mail.com',
subject: 'your subject', // Subject line
text: 'Your test failed....', // plaintext body
/*attachments: [
{
filename: 'report.html',
path: htmlReport,
}]*/
};
transporter.sendMail(mailOptions, function(error, info)
{
if(error)
{
return console.log(error);
}
console.log('Email sent: ' + info.response);
console.log(info);
});
} else {
//do your stuff
}
setTimeout(callback, 2000);
});

Getting and "Error, wrong validation token" when trying to create a Facebook Chatbot

I'm trying to create a Facebook chatbot with NodeJS, Express, and a Heroku server.
I created my webhook on heroku and had it verified and saved by facebook. I then started adding code that would reply to the incoming messages and I can't seem to get it connected. It keeps saying "Error, wrong validation token" when I try to load my webhook in my browser. And when I try to send my bot a message I get no response. Even though I already had it verified and didn't change the code.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
//app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = <myToken>;
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So I'm confused as to why nothing is happening and why I'm getting that error. I feel like I'm missing a whole step. I am following this tutorial by the way: https://developers.facebook.com/docs/messenger-platform/quickstart
Any help is appreciated. Thanks!
Edit: Here are my heroku logs
Do not post your full access tokens here!
Have you tested the output of the challenge? Since it's just a GET and you know all values you can try it yourself: your-app-domain.com/your-callback-url?hub_mode=subscribe&hub_verify_token=the_token_you_set_in_your_app_config&hub_challenge=ping which sould print 'ping' if everything work fine.
Make sure you add sendStatus(200) to the hub challenge response, too.
You need to subscribe your page to the app first. To do so make a POST request to /your-page-id/subscribed_apps which should return "success". You can make a GET request to the same endpoint afterwards to double check your app is subscribed to your page
You did not mention which events you subscribed to (needs to be message_deliveries, messages, messaging_optins, messaging_postbacks)
Make sure the webhooks tab in your app dashboard now says "complete"
Test again
You are actually using "request" but you are never importing it anywhere. Here's how to fix it:
var request = require("request")
Once you have added that to your index.js or app.js file (basically whatever this file is), make sure you do:
npm install request --save
This should fix it. Unfortunately, Heroku doesn't error out and say that it does not know what "request" is and that's why it was so hard to figure this out in the first place!

Meteor: Restivus API call returns HTML template

I must be missing something patently obvious here, but I cannot for the life of me figure out what. I have configured Restivus like this:
Projects = new Mongo.Collection('projects');
Skills = new Mongo.Collection('skills');
Causes = new Mongo.Collection('causes');
Meteor.startup(() => {
let Api = new Restivus({
apiPath: 'api/',
auth: {
token: 'auth.apiKey',
user: function () {
return {
userId: this.request.headers['user-id'],
token: this.request.headers['login-token']
};
}
},
defaultHeaders: {
'Content-Type': 'application/json'
},
onLoggedIn: function () {
console.log(this.user.username + ' (' + this.userId + ') logged in');
},
onLoggedOut: function () {
console.log(this.user.username + ' (' + this.userId + ') logged out');
},
prettyJson: true,
useDefaultAuth: true,
version: 'v1'
});
// Add core models
Api.addCollection(Skills);
Api.addCollection(Causes);
Api.addCollection(Projects);
Api.addRoute('custom', {
get: function () {
return {
status: 'success',
data: 'get something different'
};
}
});
});
This is essentially copy-pasted from the documentation. The problem is that when trying to access either any of the auto-generated endpoints, or the custom endpoint custom, all I get is the HTML of the Meteor app itself (i.e. same as if I had navigated to the root URL of the app).
It is as if Restivus simply is not being run at all, yet a console.log at the end of the code block above verifies that it is at least being run. What am I doing wrong?
As I expected, it was something patently obvious. I am leaving this here just in case anyone else makes the same mistake.
The key is this line in the config:
version: 'v1'
this means that you will need to append /v1/ to your API path, so that the call itself has the format (for example):
mydomain.com/api/v1/myresource

Google Cloud Print from Web

I wrote a script that prints some test pages from url on Web-site,
and every time I press a print button, a dialog frame for choosing printer appears . But I want to avoid this because my account synchronized with printer.
window.onload = function() {
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(
cloudprint.Gadget.createDefaultPrintButton("print_button_container")); // div id to contain the button
gadget.setPrintDocument("url", "Test Page", "https://www.google.com/landing/cloudprint/testpage.pdf");
}
You could use oath and an html button rather than a gadget to accomplish this. This requires using the google developer console to get oauth permissions.
Then you need to authorize the cloud print service.
The following set of functions are specifically good for use in Google Apps Scripts, but can be adapted. The first thing to do is Log a url link that you can go to in order to Authorize the cloud print service.
function showURL() {
var cpService = getCloudPrintService();
if (!cpService.hasAccess()) {
Logger.log(cpService.getAuthorizationUrl());
}
}
In the following component of this set of functions, make sure to replace the client Id and Secret.
function getCloudPrintService() {
return OAuth2.createService('print')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId('**YOUR CLIENT ID FROM GOOGLE DEVELOPER CONSOLE**')
.setClientSecret('**YOUR CLIENT SECRET**')
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/cloudprint')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var isAuthorized = getCloudPrintService().handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('You can now use Google Cloud Print from Apps Script.');
} else {
return HtmlService.createHtmlOutput('Cloud Print Error: Access Denied');
}
}
Next, get the ID of the Cloud Print Printer that you want to use. This can be obtained in the settings menu of Chrome. Settings --> Show Advanced Settings --> Under Cloud Print " Manage" --> Select the Printer that you want to use "Manage" -->Advanced Details
To initiate cloud print, you need to add the details to a ticket:
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "LONG_EDGE"
},
copies: {copies: 1},
media_size: {
width_microns: 215900,
height_microns:279400
},
page_orientation: {
type: "PORTRAIT"
},
margins: {
top_microns:0,
bottom_microns:0,
left_microns:0,
right_microns:0
},
page_range: {
interval:
[{start:1,
end:????}]
}
}
};
There are many options that you can add to the ticket. See documentation
Finally, you need to initiate the Cloud Print Service. Here is where you get to define the specific printer that you want.
var payload = {
"printerid" : '**COPY YOUR PRINTER ID HERE**',
"title" : "Prep Print",
"content" : PUT YOUR CONTENT HERE...(e.g. If you do all of this using Google Apps Script...HtmlService.createHtmlOutput(VARIABLE).getAs('application/pdf')),
"contentType": 'text/html',
"ticket" : JSON.stringify(ticket)
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);}
var outcome = response.message;
}

Testing Angular $resource with external service

I'm trying to make some basic tests on REST requests I'm doing using Angular $resource.
The service code works just fine.
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['Settings', '$resource', '$http', function(Settings, $resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '#id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
I'm using the Device resource inside a directive and it works. The problems comes out
when I start making some tests on the services. Here is a sample test where I mock the
HTTP request using $httpBackend and I make a request to the mocked URL.
Unluckily it does not return anything, although the request is made. I'm sure about this
because if a request to another URL is made, the test suite automatically raises an error.
I've been spending lot of time, but no solutions. Here the test code.
'use strict';
var $httpBackend;
describe('Services', function() {
beforeEach(module('lelylan'));
beforeEach(inject(function($injector) {
var uri = 'http://localhost:3001/devices/50c61ff1d033a9b610000001';
var device = { name: 'Light', updated_at: '2012-12-20T18:40:19Z' };
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(uri).respond(device)
}));
describe('Device#get', function() {
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' });
expect(device.name).toEqual('Light');
}));
});
});
As the device is not loaded this is the error.
Expected undefined to equal 'Light'.
Error: Expected undefined to equal 'Light'.
I've tried also using the following solution, but it doesn't get into the function
to check the expectation.
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' }, function() {
expect(device.name).toEqual('Light');
});
}));
Any suggestion or link to solve this problem is really appreciated.
Thanks a lot.
You were very close, the only thing missing was a call to the $httpBackend.flush();. The working test looks like follows:
it('returns a JSON', inject(function(Device) {
var device = Device.get({ id: '50c61ff1d033a9b610000001' });
$httpBackend.flush();
expect(device.name).toEqual('Light');
}));
and a live test in plunker: http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview
You might also want to check docs for the $httpBackend mock.
In later versions of angular, I'm using 1.2.0rc1 you also need to call this within a $apply or call $digest on a scope. The resource call isn't made unless you do something like this:
var o, back, scope;
beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
o = TestAPI;
back = $httpBackend;
scope = $rootScope.$new();
}));
it('should call the test api service', function() {
back.whenGET('/api/test').respond({});
back.expectGET('/api/test');
scope.$apply( o.test());
back.flush();
});