Trying to log all incoming requests from Facebook so I can inspect the object I get back to do some stuff with the built in NLP Facebooks implemented.
I, however, can't seem to find anywhere where it tells me I can console.log incoming requests.
in the server.post('/api/messages', connector.listen()); method I'm trying to pass in a console.log but nothing happens.
const express = require('express');
const builder = require('botbuilder');
const server = express();
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD,
});
server.post('/api/messages', connector.listen());
server.listen(process.env.PORT || 5000, () => {
console.log('Running on port 5000');
});
You might want to use middleware to access to the incoming/outgoing messages.
Take a look at the Middleware and Logging with BotBuilder Node SDK sample.
Capturing User Input
botbuilder: function (session, next) {
console.log(session.message.text);
next();
}
Capturing bot output to a user
send: function (event, next) {
console.log(event.text);
next();
}
In particular, since you want to check things coming from Facebook, you might have to log the sourceEvent property, which is where channels send their native information.
Related
I have a REST API backend. I'm trying to send WebSocket messages back to the client app when a site administrator invokes a route (i.e. updates user credentials);
let express = require("express");
let router = express.Router();
//update user credentials
router.put('/admin/user/:id', (req, res)=>{
// 1. Admin updates target user's profile/credentials
// 2. WebSocket message sent to target user client
// 3. Route sends res.status(200) to admin
});
I've seen a few WebSocket examples using 'ws', 'net', 'websocket' libraries, but they all show a simple event handling socket server that responds to socket messages outside of any express routes - let alone responds to a separate client.
Also, the event notification should be visible only to the target user and not all the other users connected to the socket server.
Figured it out. The WebSocket server is independent of the route.
const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 5555});
// handle socket communications
wss.on('connection', (session)=> {
session.send("HELLO SESSION: "+ session.userid);
session.on('message', (message)=> {
console.log(`MSG: "${message}" recived.`);
session.send("Got it.");
});
});
// close
wss.on('close', function close() {
clearInterval(interval);
});
module.exports = wss;
Then, in the route, just include the service and use it to iterate through web socket connections like so:
let wss = require('./mysocketservice')
...
function sendAMessageTo(user, msg) {
wss.clients.forEach(function each(s) {
if(session.user = user)
session.send("still there?.. ");
}
}
I'm trying to host the default MS Bot Framework echo bot using Node.js via IIS. However, it does not seem to be working. Do I need to change anything in the code to make it work?
I've tried changing the port from 3987 to 80, but it doesn't start. I'm new to node so I don't exactly know what the problem is.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { MyBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
console.log(`\nTo test your bot, see: https://aka.ms/debug-with-emulator`);
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
console.error(`\n [onTurnError]: ${ error }`);
// Send a message to the user
await context.sendActivity(`Oops. Something went wrong!`);
};
// Create the main dialog.
const myBot = new MyBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
I already have HTTPS setup on my IIS and I should be able to test it once I get it to work.
Thank you very much.
I have tried to understand the Microsoft SDK reference in how to communicate with the bot but there is simply no clear way shown of interacting with it.. From the documentation this is what I could put down so far:
const { BotFrameworkAdapter } = require('botbuilder');
const adapter = new BotFrameworkAdapter({
appId: '123',
appPassword: '123'
});
// Start a new conversation with the user
adapter.createConversation()
Any ideas ?
The Microsoft Bot Framework makes use of the restify server to create an API endpoint for the bot. A bot is simply a web service that will send and receive messages to and from the Bot Connector. You will have to use the following steps to communicate with the bot:
Install Restify
npm install --save restify
Include the restify module
const restify = require('restify');
Set up the restify server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978,
function () {
console.log(`\n${ server.name } listening to ${ server.url }`);
}
);
Create the main dialog (here the example uses Echo Bot)
const bot = new EchoBot();
Create a POST endpoint for your server and hook up the adapter to listen for incoming requests
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// route to main dialog.
await bot.run(context);
});
});
Hope this helps.
Can I send a message to all the users who spoke with the bot? It would be a message and it would be for all users. (Broadcast)?
botbuilder 3.14.0 - nodejs
You can use proactive messages for that as it allows you to send the user a message that is not directly related to the current topic of conversation.
Here's a sample on how to send an ad-hoc proactive message:
'use strict';
var restify = require('restify');
var builder = require('botbuilder');
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// setup bot credentials
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Bot Storage: Here we register the state storage for your bot.
// Default store: volatile in-memory store - Only for prototyping!
// We provide adapters for Azure Table, CosmosDb, SQL Azure, or you can implement your own!
// For samples and documentation, see: https://github.com/Microsoft/BotBuilder-Azure
var inMemoryStorage = new builder.MemoryBotStorage();
var bot = new builder.UniversalBot(connector).set('storage', inMemoryStorage); // Register in memory storage
// send simple notification
function sendProactiveMessage(address) {
var msg = new builder.Message().address(address);
msg.text('Hello, this is a notification');
msg.textLocale('en-US');
bot.send(msg);
}
var savedAddress;
server.post('/api/messages', connector.listen());
// Do GET this endpoint to delivey a notification
server.get('/api/CustomWebApi', (req, res, next) => {
sendProactiveMessage(savedAddress);
res.send('triggered');
next();
}
);
// root dialog
bot.dialog('/', function(session, args) {
savedAddress = session.message.address;
var message = 'Hello! In a few seconds I\'ll send you a message proactively to demonstrate how bots can initiate messages.';
session.send(message);
message = 'You can also make me send a message by accessing: ';
message += 'http://localhost:' + server.address().port + '/api/CustomWebApi';
session.send(message);
setTimeout(() => {
sendProactiveMessage(savedAddress);
}, 5000);
});
You can also find a complete sample that shows how to send proactive messages using the Bot Builder SDK for Node.js here
I've created a simple chatbot using bot framework and i'm trying to save the bot's chat history locally on my device for now. I've used fs to save the values/arguments the user enters, into a file. For e.g.: their name.
However, I want to include the whole chat conversation i.e. the message the user sends and the reply the bot gives. I tried using fs.appendFile(filename, session, function(err) to capture those dialogs but it just displays [Object object] in the file.
How can I capture the whole chat history? Or at least whatever the user has sent?
My code sample:
var restify = require('restify');
var builder = require('botbuilder');
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: ''
appPassword: ''
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
server.get('/', restify.serveStatic({
directory: __dirname,
default: '/index.html'
}));
var fs = require("fs");
var filename = 'chathistory.json';
//=========================================================
// Bots Dialogs
//=========================================================
var test="test";
bot.dialog('/', new builder.IntentDialog()
.matchesAny([/hi/i, /hello/i], [
function (session) {
session.send('Hi, I am your chatbot.');
session.beginDialog('/step2')
},
bot.dialog('/step2', [
function (session) {
builder.Prompts.text(session,'What is your name?');
},
function(session, args, next) {
test=" , " +args.response;
fs.appendFile(filename, test, function(err){
});
session.send('Hello, ' + args.response + '. How may I help you today?');
name = args.response;
session.endConversation();
}
])
])
);
One way to capture user input and bot input is using middleware. Take a look at the middlewareLogging sample, where the logging scenario is being showcased.