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.
Related
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!
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const path = require('path');
const dotenv = require('dotenv');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
const restify = require('restify');
const { QnAMaker } = require('botbuilder-ai');
// 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');
// 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 talk to your bot, open the emulator select "Open Bot"');
});
// 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,
});
// Map knowledge base endpoint values from .env file into the required format for `QnAMaker`.
const configuration = {
knowledgeBaseId: process.env.QnAKnowledgebaseId,
endpointKey: process.env.QnAAuthKey,
host: process.env.QnAEndpointHostName
};
// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Create the main dialog.
const myBot = new MyBot(configuration, {});
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
streamingAdapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await myBot.run(context);
});
});
After creating the QnA bot using Microsoft azure using the editor VS code, I tried to test it in the emulator I get the following error " [onTurnError] unhandled error: TypeError: Cannot read property 'map' of undefined". Can someone help me with this?
I followed the SDK4 tutorial-
https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-tutorial-add-qna?view=azure-bot-service-4.0&tabs=javascript
Thanks,
Rujuta
I'm want to get data from the node/express server after send ajax query from any page of the nuxtjs app.
Usually, for getting and sending ajax query in PHP server, I'm do like this $_GET['var']; echo json_encode('Server got data');
Now I want to use node server express for saving data in mongodb.
When I trying to send a query, response return full code of file test.js.
File index.vue
methods: {
onServer() {
this.$axios.get('/server/test').then(res => {
console.log('res', res.data)
})
}
}
File test.js
var express = require('express');
var app = express();
app.get('*', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
File server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I'm a new user node, please help me!
Your main issue is that you are targeting "test.js" in your axios url. This is why it responds with the file rather than what the get route should respond with.
So try with:
this.$axios.get('http://nuxt-profi/server/test').then(...
and see what you get. You should also be able to access that in the browser, just go to your url http://nuxt-profi/server/test and it should show your "Hello World" reponse.
However I can't be sure how you have set all this up. Are you running this as development? In which case maybe you should access it as http://localhost:3000/server/test but maybe you have virtual hosts configured like this. Also, is this a separate backend api or are you trying this as server middleware?
If this doesn't help please give us more info about your project setup and we'll go from there.
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.
I was following the Viber Node.JS Bot Documentation and was creating an echo bot that would repeat the messages back to the user. But it does not work and the bot does not reply to my messages. Here is the code:
'use strict';
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot({
authToken: "api-key",
name: "Override API",
avatar: "https://cdn3.iconfinder.com/data/icons/customer-support-7/32/40_robot_bot_customer_help_support_automatic_reply-512.png" // It is recommended to be 720x720, and no more than 100kb.
});
// Perfect! Now here's the key part:
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
// Echo's back the message to the client. Your bot logic should sit here.
response.send(message);
});
// Wasn't that easy? Let's create HTTPS server and set the webhook:
const https = require('https');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
try this :
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
app.use('/viber/webhook', bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${webhookUrl}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
instead of:
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Source