I want to trigger my bot with http request (for example just entering http://localhost:3978/api/messages/http) so after triggering it, it will send every user that is connected to this bot some message.
I have seen this topic: How to send message later in bot framework?
And this is what I have so far:
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);
});
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector);
bot.dialog('/',function (session) {
var reply = session.message; // address: reply.address
reply.text = 'Wake up!'
console.log(reply.text);
bot.send(reply);
});
// Create response function
function respond(req, res, next) {
res.send('hello ' + req.params.name);
bot.send(reply);
next();
}
server.get('/api/messages/:name', respond);
Unfortunately, it doesn't send any messages while I am acessing my http://localhost:3978/api/messages/http. I also tried to use
connector.send('message');
But it always throughs me "ERROR: ChatConnector: send - message is missing address or serviceUrl."
UPDATE:
I have announced a global var for the reply with
var globalreply;
bot.dialog('/',function (session) {
globalreply = session.message; // address: reply.address
globalreply.text = 'Wake up!'
console.log(globalreply.text);
bot.send(globalreply);
});
// Create response function
function respond(req, res, next) {
res.send('hello ' + req.params.name);
bot.beginDialog;
bot.send(globalreply);
next();
}
But now it throughs me an error:
TypeError: Cannot read property 'conversation' of undefined.
At my bot.send(globalreply); line.
Looking forward your help.
Best regards.
If you want to set up a normal HTTP API route, I suggest using the Restify API style routing, rather than the bot's /api/messages route handler.
For example:
function apiResponseHandler(req, res, next) {
// trigger botbuilder actions/dialogs here
next();
}
server.get('/hello/:name', apiResponseHandler);
Related
I decided to make a janky chat site type thing to get me started working with requests and such.
My approach was to create an express.js server that takes in requests when the '/messageReciever' is posted to.
app.post("/messageReciever", (req, res) => {
logMessage(req.body.message);
});
The next step was to make a 'client' that could send information to this end point:
var XMLHttpRequest = require("XMLHttpRequest").XMLHttpRequest;
function makePostRequest(url, json)
{
let http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/json");
http.send(JSON.stringify(json));
}
function sendMessage(url, message)
{
makePostRequest(url, {message: message});
logMessage(message);
}
Both of these are fine. The issue I'm running into is, once I receive the post request I want to refresh the main page of my site (to show the messages)
app.get('/', (req, res) => {
res.render('index', data = retrieveMessages());
});
I've tried basically everything I've found online:
res.redirect('back');
res.redirect(req.get('referer'));
res.redirect(req.originalUrl)
I used res.redirect('back') previously in my code, and it works. The issue is that I'm trying to refresh someone's connection to a site based on someone else's connection; meaning I can't use the response information like I normally could.
I've tried looking for ways to refresh pages from outside functions but I can't find anything.
(I realize that there are easier ways to make a chat site that don't include weirdly sending data back and forth between two server's)
You can use a package called socket.io. Socket.io allows you to send requests to a client once the server has some data.
Example:
Server:
// Define express
const express = require('express');
const app = express();
// Create the server
const http = require('http');
const server = http.createServer(app);
// Define socket.io
const io = require('socket.io')(server);
// Define the port for the server to listen on
let port = 3000;
function logMessage(message, id) {
...
io.emit('message_sent_' + id, { message }); // Emit that a message was sent to the clients
}
function recieveMessages(id) {
// Get the messages somehow
}
app.post('/messageReciever', (req, res) => {
// req.body.message is your message and req.cookies.id is the clients random ID
logMessage(req.body.message, req.cookies.id);
});
app.get('/', (req, res) => {
res.cookie('id', 'some-generated-id'); // Set a cookie for the unique ID to fetch user messages
res.render('index', { data: retrieveMessages() });
});
// Get the server listening to incoming requests
server.listen(port, () => console.log('my app is online');
Client:
<!doctype html>
<html>
<body>
...
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io.connect();
socket.on('message_sent_' + 'some-id', function(data) {
// Do something with the data
});
</script>
</html>
References:
https://socket.io/docs/v4/
http://expressjs.com/
https://marques-robinson-project.medium.com/chat-app-with-socket-io-and-express-using-node-js-2293b87f47c3
I am trying to get the data my nodeJS server is receiving from a form on the front end to send that data to my email. I have tried to use nodemailer and haven't succeeded much. Can someone tell me perhaps what I am doing wrong with the following code?
const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
const PORT = process.env.PORT || 4000;
app.use(express.static(__dirname + "/front-end"));
app.get("/", (req, resp) => {
resp.sendFile(__dirname + "/front-end/index.html");
});
app.use(express.json());
app.use(express.urlencoded());
app.post("/formData", (req, resp) => {
const data = req.body;
var transport = nodemailer.createTransport(
smtpTransport({
service: "Gmail",
auth: {
user: "user#gmail.com",
pass: "123456",
},
})
);
transport.sendMail(
{
//email options
from: "Sender Name <email#gmail.com>",
to: "Receiver Name <receiver#email.com>", // receiver
subject: "Emailing with nodemailer", // subject
html: data, // body (var data which we've declared)
},
function (error, response) {
//callback
if (error) {
console.log(error);
} else {
console.log("Message sent:");
resp.send("success!");
}
transport.close();
}
);
});
app.listen(PORT, () => {
console.log(`server running on port ${PORT}`);
});
Your code, at a glance, looks fine to me. I think the problem is (since you’re not stating you have set that up), that you want to send email with GMail. If you want to send email from your own app or web service via Gmail, you should set up a project in the Google Cloud Platform. Read more here.
Alternatively, you could use a service like Postmark, which you can configure to send emails via a domain that you own. There’s a free trial. Mailgun is a similar service. (I’m not affiliated to either).
My use case:
My case is that i'm making a bot for listening podcast in which user will make call to twilio number and bot will ask what type of podcast would you like to listen then record for 10 seconds
when recording finish, it say user to please wait while we are finding podcast
I want that recording in my webhook so i will figure out caller mood and find appropriate podcast mp3 file from my database and play to caller
Issue I'm Facing:
I'm getting empty body in all of my webhooks
My code:
var express = require("express");
var bodyParser = require("body-parser");
var VoiceResponse = require('twilio').twiml.VoiceResponse;
var app = express();
var port = (process.env.PORT || 4000);
app.use(bodyParser.json())
// helper to append a new "Say" verb with alice voice
function say(text, twimlRef) {
twimlRef.say({ voice: 'alice' }, text);
}
// respond with the current TwiML content
function respond(responseRef, twimlRef) {
responseRef.type('text/xml');
responseRef.send(twimlRef.toString());
}
app.post("/voice", function (request, response, next) {
console.log("request: ", request.body); //body is comming as empty object
var phone = request.body.From;
var input = request.body.RecordingUrl;
var twiml = new VoiceResponse();
console.log("phone, input: ", phone, input);
say('What type of podcast would you like to listen. Press any key to finish.', twiml);
twiml.record({
method: 'POST',
action: '/voice/transcribe',
transcribeCallback: '/voice/transcribe',
maxLength: 10
});
respond(response, twiml);
});
app.post("/voice/transcribe", function (request, response, next) {
console.log("request: ", request.body); //body is comming as empty object
var phone = request.body.From;
var input = request.body.RecordingUrl;
var twiml = new VoiceResponse();
var transcript = request.body.TranscriptionText;
console.log("transcribe text: ", transcript);
//here i will do some magic(Ai) to detect user mood and find an
//appropriate mp3 file from my database and send to twilio
var mp3Url = 'https://api.twilio.com/cowbell.mp3'
say('start playing.', twiml);
twiml.play(mp3Url);
respond(response, twiml);
});
app.listen(port, function () {
console.log('app is running on port', port);
});
API Test with postman:
added url as webhook on twilio:
Heroku Logs:
Twilio developer evangelist here.
You are using body-parser which is good. However, you are using the JSON parser. Twilio makes requests in the format of application/www-x-form-urlencoded so you should change:
app.use(bodyParser.json())
to
app.use(bodyParser.urlencoded({ extended: false }))
Then you should see the parsed body as part of the request.body object.
As an extra note, the transcribeCallback is sent asynchronously to the call. So returning TwiML in response to that request won't affect the call at all. You will need to modify the call in flight, by redirecting it to some new TwiML when you get the result of transcription. An example of updating a call with Node.js is below:
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.calls('CAe1644a7eed5088b159577c5802d8be38')
.update({
url: 'http://demo.twilio.com/docs/voice.xml',
method: 'POST',
})
.then((call) => console.log(call.to));
I've built a simple RESTful API using NodeJS, Mongoose, and Express. I am using the database to store simple string quotes and am not planning to allow access to any other users to the database nor to the api.
I've read up on securing my RESTful API but it seems as if most methods focus on using a username and password to limit access. However, that seems like an overkill for such a simple API especially since i do not consider on allowing anyone else access except for requests that come from the server itself.
So I want to make it so that if anyone else tries to access the API he would be denied access. The only way the API should be accessible is from requests from the server itself i.e from the JavaScript files on the server.
I am currently learning all those things so sorry if i am not using the proper technical terminology :)
I am considering doing something like checking the IP of the person/thing trying to access the API and if that is not the ip of the server then deny access. Would something like this work and how would I got about implementing it.
EDIT: I am looking for something simple since I dont think that most people will take the time to 'hack' the API just so they can access a database of quotes.
Here is my server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Quote = require('./mongodb/models/mainModel.js');
mongoose.connect('mongodb://localhost:27017/myappdb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
function grantAccess(req) {
if(req.ip === '::1' ||
req.ip === '127.0.0.1' ||
req.ip === '::ffff:127.0.0.1') {
return true;
}
return ["IP Address Unknown " + req.ip]
}
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/maindb')
.post(function(req, res) {
var quote = new Quote();
quote.name = req.body.name;
quote.severity = req.body.severity;
quote.createdAt = new Date();
quote.updatedAt = new Date();
quote.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Quote created!' });
});
})
.get(function(req, res) {
if(grantAccess(req) !== 'boolean')
Quote.find(function(err, quotes) {
if (err)
res.send(err);
res.json(quotes);
});
});
router.route('/maindb/:quote_id')
.get(function(req, res) {
Quote.findById(req.params.quote_id, function(err, quote) {
if (err)
res.send(err);
res.json(quote);
});
})
.put(function(req, res) {
Quote.findById(req.params.quote_id, function(err, quote) {
if (err)
res.send(err);
quote.name = req.body.name;
quote.severity = req.body.severity;
quote.updatedAt = new Date();
// save the bear
quote.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Quote updated!' });
});
});
})
.delete(function(req, res) {
Quote.remove({
_id: req.params.quote_id
}, function(err, quote) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
you can add apiKey in your project. It will be required if anyone hits any of your api.
exmaple:
"apiKeys": {
"web": "7fe642cabe6855cd4175937fa8fadd876c1af6b499ab941db6a8a362c0f30f97"
}
similarly you can set apikey for mobile user or accordance to requirment of project.
Link to genrate RandomKey
By this you will allow only those users who have your api key.As api key is shared by you so you will provide it to only appropriate user.
Api key checking:
You can check api key as first middleware before any request to server
example:
router.use(function(req,res,next){
var apiKey = req.get('api_key'); // assuming user will send api key in headers
// code to check api key basic comparison
})
I'm trying to register TAKE_A_NOTE with the 'mirror-api-subscription' event listener. I'm not having any luck: I can launch take a note with "my app", however, there's no console log that the event has been recognized.
I would like to recognize when the TAKE_A_NOTE function has occurred or finished, and handle the response afterwards. I do not know whether the subscription should be on a stream or if I am implementing the EventListener in a faulty manner. Your help would be greatly appreciated.
The code I am utilizing is:
// references
// http://www.recursiverobot.com/post/57348836217/getting-started-with-the-mirror-api-using-node-js
// https://www.npmjs.org/package/mirror-api-subscription
var express = require('express')
, http = require('http')
, https = require('https')
, fs = require('fs')
, googleapis = require('googleapis')
, OAuth2Client = googleapis.OAuth2Client;
var app = express();
var oauth2Client = new OAuth2Client(process.env.MIRROR_DEMO_CLIENT_ID,
process.env.MIRROR_DEMO_CLIENT_SECRET, process.env.MIRROR_DEMO_REDIRECT_URL);
// all environments
app.set('port', 8888);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
var gotToken = function () {
googleapis
.discover('mirror', 'v1')
.execute(function (err, client) {
if (!!err) {
failure();
return;
}
insertContact(client, failure, success);
insertSubscription(client, failure, success);
});
};
var insertContact = function (client, errorCallback, successCallback) {
client
.mirror.contacts.insert({
"id": "myapp",
"displayName": "myApp",
"priority": 100,
"acceptCommands": [
{"type": "TAKE_A_NOTE"}
],
"speakableName":"my app"
})
.withAuthClient(oauth2Client)
.execute(function (err, data) {
if (!!err)
errorCallback(err);
else
successCallback(data);
});
};
var insertSubscription = function (client, errorCallback, successCallback) {
client.mirror.subscriptions.insert({
"callbackUrl":"https://localhost:7777/notification",
"collection":"timeline",
"userToken":"001",
"verifyToken":"secret",
"operation":["INSERT"]
});
}
var subscription = require('mirror-api-subscription')(
function () {
})
subscription.on('locations#UPDATE',
function (notification, user, payload) {
console.log('location of user %s updated', user.id)
})
subscription.on('timeline#INSERT:LAUNCH',
function (notification, user, payload) {
console.log('subscription timeline#INSERT:LAUNCH')
})
subscription.on('timeline#UPDATE:CUSTOM',
function (notification, user, payload) {
console.log('subscription timeline#UPDATE:CUSTOM')
})
app.post('/notification', subscription.dispatcher())
app.get('/', function (req, res) {
if (!oauth2Client.credentials) {
// generates a url that allows offline access and asks permissions
// for Mirror API scope.
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/glass.timeline'
});
res.redirect(url);
} else {
gotToken();
}
res.write('Glass Mirror API with Node');
res.end();
});
app.get('/oauth2callback', function (req, res) {
// if we're able to grab the token, redirect the user back to the main page
grabToken(req.query.code, failure, function () {
res.redirect('/');
});
});
app.post('/reply', function(req, res){
console.log('replied',req);
res.end();
});
var options = {
key: fs.readFileSync('./ssl/key.pem'),
cert: fs.readFileSync('./ssl/cert.pem'),
};
https.createServer(options, app).listen(7777, function() {
console.log('https listening on 7777');
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
There are at least two potential problems with your code:
The callbackUrl must be an internet accessible HTTPS address. "Localhost" isn't good enough, since Google's servers need to be able to resolve it. You can provide an IP address, if you have a public IP address, or use a tunnel.
You don't do anything with the result of the call to client.mirror.subscriptions.insert(). Typically, you should call it the same way you call client.mirror.contacts.insert(), which is to chain it with withAuthClient() and execute(). You'll need to call execute() if you expect it to register with the Mirror service. See https://github.com/google/google-api-nodejs-client/ for documentation about the "googleapis" package and discovery service
Possibly related to #2, but I'm not familiar with the package you're including with require('mirror-api-subscription'), which seems to handle things differently than the "googleapis" package and discovery service it offers. From the reference documentation for it, however, it isn't clear that it actually sets up the callback anywhere and is just there to verify the callbacks and dispatch to functions that do the work.
var insertSubscription = function (client, errorCallback, successCallback) {
client.mirror.subscriptions.insert({
"callbackUrl":"https://mirrornotifications.appspot.com/forward?url=callbackURL",
"collection":"timeline",
"userToken":"001",
"verifyToken":"secret",
"operation":["INSERT"]
}).withAuthClient(oauth2Client).execute(function (err, data) {
if (!!err)
errorCallback(err);
else
successCallback(data);
});
};