node twitter npm package - javascript

I've installed node-twitter via npm and have created an index.js file with the code below. When I run node index.js in the console I'm not getting any response. I've included my own keys and secrets so that doesn't appear to be the issue.
var Twitter = require('twitter');
var client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
client.stream('statuses/filter', {track: 'nyc'}, function(stream){
stream.on('data', function(tweet) {
console.log(tweet.text);
});
stream.on('error', function(error) {
console.log(error);
});
});

You're connecting to one of Twitter's streaming endpoints, so you will only see updates if someone posts a tweet with the text 'nyc' in it at that precise moment.
I suspect this is not your intention, and you instead wish to search for the most recent tweets containing the text 'nyc', as below:
client.get('/search/tweets.json?q=nyc', function(error, tweets, response){
if(error) throw error;
console.log(tweets);
});
The Twitter search API documentation is here. If you actually do wish to stream tweets, I recommend using something like forever.js to keep your script running long enough to listen for tweets and output them.
Edit: Since you would like to stream the tweets as they come in, you can use forever.js to keep your script running, as below:
var forever = require('forever-monitor');
var child = new (forever.Monitor)('twitter.js', {
max: 1,
silent: false,
args: []
});
child.on('exit', function () {
console.log('twitter.js has exited after 3 restarts');
});
child.start();
Where twitter.js is the file posted in the question. If you want to search backwards or forwards from a specified time, you can find details on how to do so in the Twitter API docs.

Related

Does third party authorized application have access to private tweet? i am having issue with user timeline REST API

I am not sure about whether third party authorized application have access to private tweet in twitter b/c i am getting error with {} (with status 200) when i used user timeline REST API.
I am using Twitter-npm.
//Initialise twitter client object-Twitter with keys
var client = new Twitter({
consumer_key: config.twitter.consumer_key,
consumer_secret: config.twitter.consumer_secret,
access_token_key: config.twitter.access_token_key,
access_token_secret: config.twitter.access_token_secret
});
client.get('statuses/user_timeline', tparam, function (error, tweets, response) {
if (error) {
console.log("error : " + JSON.stringify(error)); // error: {}
// i am getting error here {}
} else {
// data
}
});
It does not even get proper error message, so how can i get, why i am not getting tweets.
When i analysed i saw :
if the Protect your tweet is true in setting i am getting 200 with
error {}.
if the protect your tweet is false in setting i am getting 200 with
tweets.
i have also asked in twitter-community about this issue , but did not get fully response.
i also tried it using Postman , i get
{"request":"\/1.1\/statuses\/user_timeline.json","error":"Not authorized."}
and if any other error come it give error with code and message for example.
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
why it's not giving such in my case?

How to create Microsoft Account Sign-in to my website, similar to Google?

I'm working on a web project (HTML, CSS, JavaScript, with back-end in PHP). I've successfully got a Google Sign-in working, using their simple API, but can't get the Microsoft equivalent to function. The official online solutions to this seem to rely on .NET or PHP Composer. I'll try composer if that's the only way but a pure JS/PHP method would be easiest.
I've tried to use the following:
https://github.com/microsoftgraph/msgraph-sdk-javascript
https://github.com/AzureAD/microsoft-authentication-library-for-js
The code below is the closest I've come to a working solution. I can get some kind of user ID (which appears to be unique and constant for each user). This might be enough to set up the login system I want, but it would be ideal if I could also fetch their name and profile picture.
<script class="pre">
var userAgentApplication = new Msal.UserAgentApplication("MY CLIENT ID", null, function (errorDes, token, error, tokenType) {
// this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
})
userAgentApplication.loginPopup(["user.read"]).then(function (token) {
var user = userAgentApplication.getUser(); //this is good
//user.userIdentifier seems to be a unique ID
//I will store this and use it for future verification
console.log(user);
//START
// get an access token
userAgentApplication.acquireTokenSilent(["user.read"]).then(function (token) {
console.log("ATS promise resolved");
}, function (error) {
console.log(error);
// interaction required
if (error.indexOf("interaction_required") != -1) {
userAgentApplication.acquireTokenPopup(["user.read"]).then(function (token) {
// success
console.log("s2");
}, function (error) {
console.log("e2");
// error
});
}
});
//END
// signin successful
}, function (error) {
console.log(error);
// handle error
});
</script>
(this code won't run as I've pasted it because it relies on the MSAL script from the second github link, and needs an application client ID)
After getting the access token with scope user.read , you could call microsoft graph api to get sign-in user's profile information such as displayName , businessPhones :
https://graph.microsoft.com/v1.0/me
Content-Type:application/json
Authorization:Bearer {token}
To get user's profile photo :
GET https://graph.microsoft.com/v1.0/me/photo/$value
In addition , if you are using Microsoft Graph JavaScript Client Library in first link , you could get user's displayName and profile photo by :
client
.api('/me')
.select("displayName")
.get((err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res);
});
// Example of downloading the user's profile photo and displaying it in an img tag
client
.api('/me/photo/$value')
.responseType('blob')
.get((err, res, rawResponse) => {
if (err) throw err;
const url = window.URL;
const blobUrl = url.createObjectURL(rawResponse.xhr.response);
document.getElementById("profileImg").setAttribute("src", blobUrl);
});
Please refer to code sample here .

Error 401 when tweets using node-twitter

I am using Twitter API by the package Twitter for Node.js.
Right now I succeed reading tweets using stream, but I failed to write tweets. I got 401 error which means Unauthorized according to Twitter Developer Documentation.
The code is here:
const Twitter = require('twitter');
const twitterClient = new Twitter({
consumer_key: TwitterConsumerKey,
consumer_secret: TwitterConsumerSecret,
access_token_key: TwitterAccessTokenKey,
access_token_secret: TwitterAccessTokenSecret
});
twitterClient.post('statuses/update', { status: 'Hello World!' }, (err, tweet, res) => {
if (err) throw err;
console.log(tweet);
console.log(res);
});
I did give write access. What could be other reasons causing this? Thanks
I made it work. Before I changed my access from "read" to "read, write, and direct messages". And I did regenerate my "consumer key and secret", also "access token and token secret" several times.
It should work, but it wasn't.
At last I totally delete the app on Twitter and recreated it, then it works!
Hope this can help people who met this weird issue.

Twitter Stream API run in background on OpenShift

I am looking to work with the twitter stream api in javascript and have a script that run successfully pulling from the streaming API. My question is what would be the best way for me to set this up so it can run constantly. Or would it be better to switch to the search API instead? I am just trying to collect tweets based on a few keywords, but I want to collect a load of them and store them into Mongolab. Would a Cron job be best for this? I am going to use openshift to handle the streaming and processing.
I think I am looking for guidance on the best route so I don't have to constantly monitor and check that it is collecting tweets.
Thank you!
var Twit = require('twit');
var MongoClient = require('mongodb').MongoClient;
var T = new Twit({
consumer_key: '***',
consumer_secret: '***',
access_token: '***',
access_token_secret: '***'
});
var url = "***";
MongoClient.connect(url, function (err, db) {
var col= db.collection('test');
// filter public stream on keywords
var stream = T.stream('statuses/filter', {track: ['#food', 'drinks']
});
stream.on('tweet', function (data) {
console.log("tweet: " + data);
col.insert(data, function (err, result) {
if (!err) {
console.log("insert successful on tweet: " + data.id);
} else {
console.log(err);
}
});
});
});
Someone else might be able to provide a better answer but, I think using the cronjob add-on cart would be the way to go. You could set it up to execute jobs on your cartridge in timed intervals and thus would keep you from having to pull things manually. Here's a OpenShift blog article that can help you get started https://blog.openshift.com/getting-started-with-cron-jobs-on-openshift/.

socket.io disconnect after emitting to specific client NODE javascript

Hello I am currently working on some kind of "Chat"-system.
Server: NodeJs with express - https
Communication: Socket.io#1.0
client:
var socket = io.connect();
socket.emit('HELLO', {user:'someuserid'});
socket.on('WELCOME', function(data){
socket.emit('REGISTER', {});
});
socket.on('SIGNED', function(data){
console.log(data.user);
socket.emit('GO', {});
});
socket.on('message', function(data){
console.log(data.somedata);
});
server:
io.sockets.on('connection', function(socket){
socket.on('HELLO', function(data){
socket.user = data.user;
socket.emit('WELCOME', socket.user);
});
socket.on('REGISTER', function(data){
console.log('room: '+socket.user);
socket.join(socket.user);
socket.emit('SIGNED', socket.user);
console.log('SIGNED IN: '+socket.user);
});
socket.on('GO', function(data){
//some logic happens where a list of users gets loaded
//which is identical to the socket.user and its room
//... loop
io.in(partners[i].user).emit('message', { somedata: 'asd' });
}
socket.on('disconnect' ..... blaaa blaa)
So, basicly what I tried to do here is create a workaround to sending a message to a specific user by sending a message to a specific room.
this:
io.in(partners[i].user).emit('message', { somedata: 'asd' });
and this:
partners[i].socket.emit('message', { somedata: 'asd' });
result in the same:
room: 540246a3e4b0a64a28e1ec59
SIGNED IN: 540246a3e4b0a64a28e1ec59
room: 540504ba0b526b274398480e
SIGNED IN: 540504ba0b526b274398480e
to: 540246a3e4b0a64a28e1ec59
disconnected:540246a3e4b0a64a28e1ec59
the user registers, gets connected and wants to emit a message to specific chatpartners in the array partners[i].
once the emit is fired the user, the message is supposed to be emitted to disconnects...
what am I doing wrong?
(the script is obviously not complete.. i pasted the most important parts)
Thanks for your help.
I think I have found the solution:
sometimes using google is more effort than debugging by yourself.
After scrolling through the debug log in firefox I found out that this problem actually had to do with the code inside my socket 'message' handler. A snippet that might help others to find errors with their sockets:
socket.on('error', function (err) {
if (err.description) throw err.description;
else throw err; // Or whatever you want to do
});
I think this is an issue in socket.io
although it was my wrong code - the socket.io errorhandler should have passed that through.
Have fun

Categories