How to send and receive a reply to the bot - node.js

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.

Related

Error while running slack-web api and express server

I am trying to integrate WhatsApp and Slack for developing a chatbot. I am using WATI as my WhatsApp API provider and Slack Web API in Node.js
For testing locally I am ngrok to generate a webhook URL. But I am unable to receive WhatsApp incoming messages as it gives the following error:
process.nextTick(function () { throw userError; });
Error: Slack request signing verification failed
server.js
require('dotenv').config('/.env')
const express = require("express")
const app = express()
const PORT = process.env.PORT || 8000
const token = process.env.SLACK_BOT_TOKEN
const eventsApi = require('#slack/events-api')
const slackEvents = eventsApi.createEventAdapter(process.env.SLACK_SIGNING_SECRET)
const { WebClient, LogLevel } = require("#slack/web-api");
const client = new WebClient(token, {
logLevel: LogLevel.DEBUG
});
app.use('/', slackEvents.expressMiddleware())
//Route for WhatsApp
app.post('/wa-slack', async (req, res) => {
console.log(req)
});
slackEvents.on("message", async (event) => {
console.log(event)
// if (!event.subtype && !event.bot_id)
// client.chat.postMessage({
// token,
// channel: event.channel,
// thread_ts: event.ts,
// text: "Hello World!"
// })
})
app.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`)
})
The signing secret for slack is correct because the server runs successfully if I remove the following block
app.post('/wa-slack', async (req, res) => {
console.log(req)
});
Is there a way I can use the express server for handling both Slack and WhatsApp incoming requests?
Or do I need to create separate servers?
Any help or advice is appreciated, Thank you!

How to setup a viberbot webhook for heroku deployed nodejs bot?

I have problem of setting up web hook for my chat bot i made using nodejs. Which is deployed on Heroku.
The app uses the following architecture :
const http = require('http');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;
// I have used this as Heroku app name with https://dyno-125-92.herokuapp.com
http.createServer(ot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Please, help me to setup a webhook using express or anything that can work with my bot?
I'm stuck.
Try this:
const express = require('express');
const app = express();
// contains relative URL path, like: "/viber/webhook"
const webhookUrl = process.env.WEBHOOK_URL;
// ...
app.use(webhookUrl, bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}${webhookUrl}`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
If it doesn't work, use - full code example to check.

How to host node.js MS Bot Framework Chatbot using IIS

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.

Logging incoming requests in BotBuilder

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.

Why does the bot message not send?

I am using c9 as my dev environment and when running under development the bot does not actually send the message through even though sending.batch was called.
var bot = new builder.UniversalBot(connector);
bot.dialog('/', function (session) {
session.send('Alec said ' + session.message.text);
});
function status(request,reply){
connector.listen(request.raw.req,request.raw.res);
return reply("ok");
}
if (useEmulator) {
var restify = require('restify');
var server = restify.createServer();
server.listen(8080, function() {
console.log('test bot endpont at http://localhost:8080/api/messages');
});
server.post('/api/messages', connector.listen());
} else {
module.exports = { default: connector.listen() }
}
That is the code use to implement server, as taken from azure bot setup, i edited the port as c9 cant use the default port.
results after sending a message through emulator
It seems using cloud 9 server would not allow me to send out a response message my solution was to ssh into my own server at which point the app would work as intended.

Resources