I'm making a bot that let my students get a school meal menu. I'd like it to send a list of menu to students 10 minutes before the lunch time.
How should I make a code for this in JavaScript?
The main problem I encountered with was how to check the time so that my bot can send a message at that time.
I also wonder if its code always runs on the Facebook server, so I can use while loop that always check a time.
I'd appreciate an advice. (I use MongoDB and node)
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var hey = ["Yeah! 😃"]
var reply;
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
app.get("/", function (req, res) {
res.send("Deployed!");
});
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
if (data.object === 'page') {
if(d.getHours() === 10 && d.getMinutes() === 5)
sendTextMessage(senderID, "Success!");
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if(event.postback){
receivedPostback(event);
}
else {
console.log("Webhook received unknown event: ", event);
}
});
});
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
psid = senderID;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
switch (messageText) {
case 'Check':
sendTextMessage(senderID, "isSub: " + isSub);
sendTextMessage(senderID, "gamerNumber: " + gamerNumber);
sendTextMessage(senderID, "psid: " + senderID);
break;
----(and more)
function sendGenericMessage(recipientId, payload) {
var titlee
var subs
var image
switch(payload){
case "pmorning":
titlee = "Breakfast"
subs = //***this is the part where the db value goes in.***
image = "https://cdn.arstechnica.net/wp-content/uploads/sites/3/2016/10/Oculus-Rift-vs-HTC-Vive-vs-PlayStation-VR-1.jpg"
break;
---and more
}]
}]
}
}
}
};
sendTypingOn(recipientId);
callSendAPI(messageData);
}
Take a look at node-cron, which enables you to schedule jobs for running at specific times, specified by a CRON expression
Related
So I have your average Discordie node.js code, but I have no idea how to make this send messages in other channels.
The idea is, when a user requests something, it will go into a channel called requests.
var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
//make this send in a request channel.
e.message.channel.sendMessage("pong");
});
var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
var channels = e.message.channel.guild.textChannels;
var channel = null;
for(int i = 0; i < channels.length; i++) {
channel = channels[i];
if(channel.name == "YOUR CHANNEL NAME")
break;
}
channel.sendMessage("pong");
});
I am working in mean stack application and now I required to make chatting module using the XMPP protocol.
I am new with XMPP,
I have used "node-xmpp-server" and "node-xmpp-client" in node js
and "Strophe.js" in angular js.
My code is as below:
app.js (server side file)
"use strict";
var express = require("express");
var https = require('https');
var http = require("http");
var fs = require('fs');
var app = express();
var xmppClient = require('node-xmpp-client');
var xmppServer = require('node-xmpp-server');
var AES = require("crypto-js/aes");
var CryptoJS = require("crypto-js");
/**
* #description all process variables
*/
require("./config/vars")(app);
var hostName = global.hzConfig.qualifiedHostName;
var config = require("./config/config.js")(app, express);
var friendsArr = [];
var server = null
var startServer = function(done) {
// Sets up the server.
console.log("start server.....");
console.log('xmpp server is listening on port ' + global.hzConfig.xmppServerPort + " on " + process.pid + ' !');
server = new xmppServer.C2S.BOSHServer({
port: global.hzConfig.xmppServerPort,
domain: 'localhost'
})
console.log("server");
console.log(server);
// On connection event. When a client connects.
server.on('connection', function(client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
console.log('connection');
client.on('register', function(opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function(opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === '') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
} else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function() {
console.log("client");
console.log(client.jid);
console.log('server:', client.jid, 'ONLINE');
friendsArr.push(client.jid);
console.log("friendsArr================>>>>>>>>>>>>>");
console.log(friendsArr);
//client.send(new xmppClient.Message({ type: 'chat' }).c('body').t("Hello there, little client."));
})
// Stanza handling
client.on('stanza', function(stanza) {
console.log(stanza);
console.log('server:', client.jid, 'stanza', stanza.toString())
var body = stanza.getChild('body');
var message = body.getText();
console.log("body===========>>>>>");
console.log(body);
console.log("message===========>>>>>");
console.log(message);
var from = stanza.attrs.from;
stanza.attrs.from = stanza.attrs.to;
stanza.attrs.to = friendsArr[0];
console.log("stanza.attrs");
var sendTo = "laxman#mailinator.com/";
friendsArr.map(function(obj) {
if (obj["user"] === "laxman") {
console.log(obj["_resource"]);
sendTo = sendTo + obj["_resource"];
}
});
//client.send(stanza)
// client.send(stanza)
//console.log("stanza.attrs.from");
//console.log(stanza.attrs.from);
console.log("sendTo++++++++++ ::::: " + sendTo);
var stanza = new xmppClient.Element('message', { to: sendTo, type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin1');
client.send(stanza);
console.log(stanza);
//client.send(new xmppClient.Message({to : sendTo, type: 'chat' }).c('body').t("Hello there, little client."));
})
// On Disconnect event. When a client disconnects
client.on('disconnect', function() {
console.log('server:', client.jid, 'DISCONNECT')
})
})
server.on('listening', function() {})
}
startServer();
message_service.js (clien side file)
(function() {
'use strict';
angular
.module("myApp")
.factory("HzXMPPService", ['$rootScope', '$cookies', '$location', 'HzServices',
function($rootScope, $cookies, $location, HzServices) {
console.log("*****************************************");
return {
OnConnectionStatus: function(conn, obj) {
console.log("conn");
console.log(conn);
console.log("Strophe.Status");
console.log(Strophe.Status);
this.OnConnected(conn);
},
OnConnected: function(conn) {
console.log("OnConnected call");
//Callback fired when availability status of your's or your friends changes.
conn.addHandler(this.OnPresenceStanza, null, "presence");
//callback fired while receiving message
conn.addHandler(this.OnMessageStanza, null, "message");
//callback fired when a friend/authorize request is received
conn.addHandler(this.OnSubscribeStanza, null, "presence", "subscribe");
//callback when your friend/authorize request is responded by another user.
conn.addHandler(this.OnSubscribedStanza, null, "presence", "subscribed");
//send presence to all who have added you to their contact list i.e., send online status to other clients. We are sending "available" status
//conn.send($pres());
},
OnPresenceStanza: function(stanza) {
console.log("OnPresenceStanza call");
var sFrom = $(stanza).attr('from');
console.log("sFrom");
console.log(sFrom);
var sBareJid = Strophe.getBareJidFromJid(sFrom);
console.log("sBareJid");
console.log(sBareJid);
var sTo = $(stanza).attr('to');
console.log("sTo");
console.log(sTo);
var sType = $(stanza).attr('type');
console.log("sType");
console.log(sType);
var sShow = $(stanza).find('show').text();
console.log("sShow");
console.log(sShow);
//OnSubscribeStanza();
//OnSubscribeStanza();
//sendAuthorizeRequest();
sendMessage();
return true;
},
//callback is also fired when other user is typing or paused.
OnMessageStanza: function(stanza) {
console.log("OnMessageStanza call");
console.log(stanza);
var STo = $(stanza).attr('to');
console.log("to");
console.log(STo);
var sType = $(stanza).attr('type');
console.log("sType");
console.log(sType);
var sBareJid = Strophe.getBareJidFromJid(STo);
console.log("sBareJid");
console.log(sBareJid);
var sBody = $(stanza).find('body').text();
console.log("sBody");
console.log(sBody);
if (sBody) {
console.log("A Message Received: " + sBody + " From " + STo);
}
return true;
},
OnSubscribeStanza: function(stanza) {
console.log("OnSubscribeStanza call");
if (stanza.getAttribute("type") == "subscribe") {
var from_id = stanza.getAttribute("from");
console.log("from_id");
console.log(from_id);
//send back authorize request to accept it.
conn.send($pres({ to: from_id, type: "subscribed" }));
}
return true;
},
OnSubscribedStanza: function(stanza) {
console.log("OnSubscribedStanza call");
if (stanza.getAttribute("type") == "subscribed") {
var from_id = stanza.getAttribute("from");
//send back confirm authorize request.
conn.send($pres({ to: from_id, type: "subscribed" }));
}
return true;
},
//make a friend request
sendAuthorizeRequest: function() {
conn.send($pres({ to: "rahul#mailinator.com", type: "subscribe" }));
},
//disconnect from XMPP server
disconnect: function() {
console.log("connected disconnect");
conn.flush();
conn.sync = true;
conn.disconnect();
},
//send a message.
sendMessage: function(conn, msg) {
console.log("Friends call .....");
console.log("conn.jid");
console.log(conn.jid);
//return false;
var message = $msg({ to: "laxman#mailinator.com", from: conn.jid, type: "chat" }).c("body").t(msg);
conn.send(message.tree());
},
onMessage: function(message) {
console.log('service message = ');
console.log(message);
return true;
},
createAccount: function() {
conn = new Strophe.Connection("localhost");
conn.register.connect("localhost", OnConnectionStatus, 60, 1);
}
}
}
]);
}());
For testing, I have used static user for sending a message to Laxman in the server side file.
My main issue is that message can not broadcast to my friends.
I have developed a REST api using node.js. My api is running on my macbook. I am trying to access MS SQL server running on another machine using node-mysql module, but while trying to create a connection I am getting the following error:
GET /contacts/ 200 12.467 ms - -
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
at Protocol._validateEnqueue (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Protocol.handshake (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/Connection.js:123:18)
at read_json_file (/Users/abc/Desktop/NodeProjects/MyWebsite/models/contacts.js:15:14)
at Object.exports.list (/Users/abc/Desktop/NodeProjects/MyWebsite/models/contacts.js:29:22)
at /Users/abc/Desktop/NodeProjects/MyWebsite/app.js:38:44
at Layer.handle [as handle_request] (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/route.js:112:3).
I have no Clue what this is saying, Can some one guide me through this?
The code of my two scripts is given below for understanding the problem?
I am trying to connect to the MS Sql server through contacts.js scripts's "function read_json_file()" function.
App.js script code:
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var url = require('url');
var routes = require('./routes/index');
var contacts = require('./models/contacts');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//app.use('/contacts', contacts);
// catch 404 and forward to error handler
app.get('/contacts',function(request, response){
var get_params = url.parse(request.url, true).query;
if (Object.keys(get_params).length == 0)
{
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.list()));
}
else
{
response.setHeader('content-type', 'application/json');
stringify(contacts.query_by_arg(get_params.arg, get_params.value));
}
});
app.get('/contacts/:number', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.query(request.params.number)));
});
app.get('/groups', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.list_groups()));
});
app.get('/groups/:name', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(
contacts.get_members(request.params.name)));
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
module.exports = app;
contacts.js script code:
var fs = require('fs');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.***.***', //Ip address of the server machine
port : '****', //Port number
user : 'ab',
password : 'abc',
database : 'MyDataBase'
});
//Read Json file
function read_json_file() {
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
var file = './data/contacts.json';
return fs.readFileSync(file);
}
//Parse the the file da
exports.list = function() {
return JSON.parse(read_json_file());
};
exports.query = function(number) {
console.log('contact Number is:: '+number);
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact.primarycontactnumber === number) {
return contact;
}
}
return null;
};
exports.query_by_arg = function(arg, value) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact[arg] === value) {
return contact;
}
}
return null;
};
exports.list_groups = function() {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
var resultArray = [];
for (var i = 0; i < result.length; i++) {
var groups = result[i].groups;
for (var index = 0; index < groups.length; index++) {
if (resultArray.indexOf(groups[index]) === -1) {
resultArray.push(groups[index]);
}
}
}
return resultArray;
};
exports.get_members = function(group_name) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
var resultArray = [];
for (var i = 0; i < result.length; i++) {
if (result[i].groups.indexOf(group_name) > -1) {
resultArray.push(result[i]);
}
}
return resultArray;
};
Use mussel module https://github.com/patriksimek/node-mssql . Follow the samples.
After scraping an image I'm able to download to a folder using request. I would like to pass along the location of this image to my Mongoose collection.
In the callback I think there should be a way to save the location so I can pass this along when saving my model object.
exports.createLook = function(req, res) {
var url = req.body.image;
var randomizer = '123456';
var download = function(url, filename, callback) {
request(url)
.pipe(fs.createWriteStream(filename))
.on('close', callback);
};
download(url, '../client/assets/images/' + randomizer + '.jpg', function() {
console.log('done');
// do something?
});
// now get model details to save
var newLook = new Look();
newLook.title = req.body.title;
newLook.image = // image location
newLook.save(function(err, look) {
if(err) return res.send(500);
} else {
res.send(item);
}
}
Assuming that 'randomizer' will be generated I would do:
exports.createLook = function(req, res) {
var url = req.body.image;
var randomizer = getSomthingRandom();
var download = function(url, filename, callback) {
request(url)
.pipe(fs.createWriteStream(filename))
.on('close', callback(filename);
};
download(url, '../client/assets/images/' + randomizer + '.jpg', function(filename) {
console.log('done');
// now get model details to save
var newLook = new Look();
newLook.title = req.body.title;
newLook.image = filename;
....
});
My current application poll using MEAN stack and in controller I have a function vote() and API route defined as follow:
"/api/polls/pollID/pollChoiceID"
(ex. http://localhost:3001/api/polls/5587ad060a9e110816f9f1a8/5587ad060a9e110816f9f1a9)
I have the app working fine as it's but now I'm looking to implement socket.io on this app so that when client #2 connected and vote the voting result graph of client #1 will update in real time. I did some research about socket.io but I'm still stuck on implementing it.
For instance, in controller.js and inside the vote() I need to add:
socket.emit('send:vote', poll);
and over the routes/index.js I'll need to handle the socket.emit from controller so I wrap existing router.post codes with socket.on :
socket.on('send:vote', function(data){
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
//existing code here
}
}
However, Ii'm not sure if I'm taking the right steps so that they will work with my existing API route. Any inputs would be great! Thanks
/*
controller.js
*/
var voteObj = { poll_id1: pollSelected, choice1: pollChoiceSelected };
$scope.votedPollID = voteObj.poll_id1;
$scope.votedPollChoiceID = voteObj.choice1;
$scope.vote = function()
{
$http.post('/api/polls/' + $scope.votedPollID + '/' + $scope.votedPollChoiceID)
.success(function (data)
{
console.log(data);
$scope.poll = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
/*
routes/index.js
*/
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
var testpollid = req.params.poll_id2;
var testpollchoiceid = req.params.poll_choice2;
var ipCounter = 0;
PollModel.findById({_id: req.params.poll_id2}, function(err, poll)
{
if(poll)
{
var choice = poll.choices.id(testpollchoiceid);
choice.votes.push({ ip: ip });
var ipCounter = ipCounter++;
poll.save(function(err, doc)
{
if(err)
{
return (err);
}
else
{
var theDoc = {
question: doc.question, id: doc._id, choices: doc.choices,
userVoted: false, totalVotes: 0
};
for(var i = 0, ln = doc.choices.length; i< ln; i++)
{
var choice = doc.choices[i];
for(var j= 0, jLn = choice.votes.length; j< jLn; j++)
{
var vote = choice.votes[j];
theDoc.totalVotes++;
theDoc.ip = ip;
if(vote.ip === ip)
{
theDoc.userVoted = true;
theDoc.userChoice = { _id: choice._id, text: choice.text };
}
}
}
poll.userVoted = theDoc.userVoted;
}
});
return res.json(poll);
}
else
{
return res.json({error:true});
}
});
});
});
});