I'm trying to explore something about Facebook-chat-api provided on git and node.js. I know what I want but I can't find proper literature so please help me out.
I have a Facebook page and I have front-end html page with sockets + back-end node.js. On front-end I have text box. The idea is that I want to send whatever is in that text box to my page as a private message.
I know You can send message to a friend via this node plugin but I'm nut sure what to put as ID if You want to send a message to Yourself or page.
Using facebook-chat-api.
socket.on("REQ fmsgsend", function(mailData){
facebook({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => {
if(err) return console.error(err);
api.sendMessage(message.body, message.threadID);
});
});
I would put text box string in message.body but I'm not sure how to detect thread ID. Am I going wrong way?
Here is the solution:
var facbook = require("facebook-chat-api");
facbook({email: EMAIL#EMAIL.com, password: PASSWORD}, function callback (err, api) {
if(err) return console.error(err);
api.getUserID(FriendName, (err, dataF) => {
if(err) return console.error(err);
// Send the message to the best match (best by Facebook's criteria)
var msg = "Hello my friend!";
var threadID = dataF[0].userID;
api.sendMessage(msg, threadID);
api.logout(function(err){
if(err) return console.error(err);
console.log("logged out");
});
});
});
This code on node.js server sends a message to friend by name.
This code and it's functionalities are not approved by Facebook or Facebook-API.
Related
I'm new to development in general, so if the answer question seems very strightforward or if some of the terminology seems incorrect, then please allow some leeway. Also, I've spent the last few days trying to understand this, so, my part of due diligence has been done as well.
Goal:
Implement a chat application. After a user is authenticated, he / she is redirected to a room (unique to him), with a list of all the users in the DB.
Stack : Socket.io, Node JS, Express, EJS and Mongo DB
I've implemented an API which will check if the user exists in the DB and redirect successful users.
I believe I have an understanding of socket.io mechanics i.e. events can emitted and are consumed by either the server or the client.
The trouble I have is understanding how to tie the 2 (passing data from Express/EJS to socket.io) together
What I would like to have -
1. POST route will authenticate the user and redirect to the /chat GET route
(For now, I'm not using real authentication)
app.post("/login", (req, res) => {
db.User.findOne({ email: req.body.email }, (err, user) => {
if (!user) {
res.send("user not found");
} else if (err) {
console.log(err);
} else {
res.redirect("/chat");
}
});
});
This /chat GET route renders the page index.ejs
app.get("/chat", (req, res) => res.render("index"));
3.In the index.ejs, I would like to have the user information of the authenticated user, all the users in the DB. This, I believe would comes from the post route. I'm aware how to pass the data from Express to an EJS template, but not when socket.io is involved.
Socket.io code
ChatNsp.on("connection", client => {
console.log(`Client ${client.id} connected`);
client.emit("my event", { custom: "data" });
client.on("disconnect", () =>
console.log("Client " + client.id + " disconnected")
);
});
Any pointers would be appreciated. I've been trying to figure this out for the last few days.
Client code
const socket = io.connect("/chat");
socket.on("connect", function() {
alert("Connected to the server");
socket.on("my event", data => console.log(data));
});
This is a typical route in node.js that has a pseudo-code to connect to a database, get some data using a query and then pass them to a page to be rendered,
router.get('/', function(req, res){
db-connect(function(err, db) {
if (err) {
return console.log('error');
}
db.query('select * from table', function(err, results){
if (err) {
return console.log('error');
}
res.render('index',{
'title':'my title',
'pageHeader': 'my header',
'results': results //dynamic ???
});
});
}); //connect
});//router get
I am using this pseudo-code to ask a general question :
The results data are dynamic, maybe the query will take a while, so the results do not get to the page fast, so I guess the rendering will also take a while.
How can I render static data immediatly (title and pageHeader) and the dynamic part (results) as soon as it is ready ?
Do I have to use another function or another syntax?
Thank you
res.render populates your template and sends it to the client (browser). You cannot send "a bit more" when it's ready at a later stage.
Either make the client wait for the data, or send your title and header first, and use XHR (javascript) on the browser to get the rest.
I'm converting an MS Access database to a webapp. I'm using Angular JS, Node JS with the express framework and MySQL as database.
In ms access you don't have any edit/save features. When you edit something, the database changes instantly. I like this. Feels smooth. So I want to have this the same way in the web app. My question is. Will there be any problems with this approach in my webbapp?
This is a piece of my node js code which updates the database with a restcall:
/*
Post /api/products/ HTTP/1.1
*/
exports.editProduct = function(req, res) {
console.log(req.body);
var post = [{title_en: req.body.title_en},req.params.id];
if (connection) {
connection.query("UPDATE products SET ? WHERE id = ?", post, function(err, rows, fields) {
if (err) throw err;
res.contentType('application/json');
res.write(JSON.stringify(rows));
res.end();
});
}
};
And on the client side I use the a the $resource object
$scope.save = function(){
$scope.product.$save(function(){
console.log('Save successfull);
});
};
And in the view. I simply have inputs with ng-change:
<input ng-model="product.title_en" ng-change="save()".
Will this work good in production mode with a couple hundred users? Is the chances of blocking/crashing etc?
The only thing I see is if (err) throw err;
if there is an error the server crash so change it with a json response with a 500 status.
By the way express has a build-in way to output json
It's better off to validate title_en and id
exports.editProduct = function(req, res) {
console.log(req.body);
var post = [{title_en: req.body.title_en},req.params.id];
if (connection) {
connection.query("UPDATE products SET ? WHERE id = ?", post, function(err, rows, fields) {
if (err) {
return res.json(500,{ error: 'Cannot update the product' });
}
res.json(200,rows);
});
}
an other thing try to use restangular instead of resource it's a lot of fun :)
};
I'm trying to use app.render() to display a jade file in the browser. In the following code, the html is displayed to the console correctly, but the browser never shows the related file.
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
});
EDIT:
I have this handler:
app.get('/unavailable', display.unavailable);
Then beneath this code in the same file (app.js) I have this:
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
else
conn = sqlconn; //save the sql connection globally for all client's to use
});
So, what I want to happen is when the err happens with the SQL connection, the /unavailable handler is executed and a static html page is displayed that says the service is down. However, because the error occurs on the server, and not the client, I don't have access to a response object at that time. I'm trying to artifically manufacture the client 'redirecting' to /unavailable in their browser to see the message.
Obviously you don't send the html to the browser. Use res.render inside a route without callback, i.e.
res.render('unavailable', {title: 'Unavailable'});
or send the result of rendering like here:
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
res.send(html);
});
Read more about the difference here:
What's the difference between "app.render" and "res.render" in express.js?
save a global var sqlOK = false, set it in sql.open callback, and redirect to /unavailable if you get a request while sqlOK is not true. you were also missing brackets around the else statement.
var sqlOK = false;
app.get('/unavailable', display.unavailable);
app.get('*', function(req, res, next){
if(!sqlOK){
return res.redirect('/unavailable');
//return res.send(500)
};
next();
});
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
} else {
conn = sqlconn; //save the sql connection globally for all client's to use
sqlOK = true
}
});
I have an app that is built in AngularJS on top of Node/Express/MongoDB. Outgoing links are first sent to a page at /out/:item_id which is then looked up, saved to my database and redirected to the correct external URL.
For now the code looks like:
exports.outgoing = function (req, res) {
var id = req.params.id;
db.products.find({"_id": mongojs.ObjectId(id)}, function (err, record) {
if (err) {
console.log("Lookup Error: " + err);
} else{
console.log("Redirecting to " + record[0].infoLink)
res.redirect(record[0].infoLink);
}
});
};
I'd like to be able to track this event on Google Analytics so I can track what the outgoing link is, but don't know how, as the default code attaches itself to the window which isn't really feasible here. Very new to server side stuff.