How to get followers count from twitter - javascript

I want the followers count from twitter site , Already I used this query, its worked well, but its not worked now,because the twitter API was changed now.i used script for getting count in a span id ="spnTwitterFolowersCount".
<script>
$.getJSON("https://twitter.com/users/Obama.json?callback=?",
function (data) {
document.getElementById("spnTwitterFolowersCount").innerHTML = data.followers_count;
//alert('Obama has ' + data.followers_count + ' Followers');
});
</script>

As the followers count is accessible from anybody on a twitter profile you can use YQL:
var ttid = "twitterUsername";
var response = $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20content%20from%20html%20where%20url%3D%22https%3A%2F%2Ftwitter.com%2F"+ttid+"%22%20and%20xpath%3D'%2F%2Fli%5Bcontains(%40class%2C%22ProfileNav-item--followers%22)%5D%2Fa%2Fspan%5Bcontains(%40class%2C%22ProfileNav-value%22)%5D'&format=json&callback=");
return response.success(function (followers) {
return followers;
});

A lot has changed with the twitter API 1.1, for first, you cannot makes call directly to get data. You need to have some sort of authentication for making those calls.
Please read this documentation which states the need for authentication. You can have Oauth authentication or app-only authtentication based on your needs.
After you are done with the authentication, you can get the list of followers using this api
https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=sitestreams&count=5000
Read here for more information and complete set of parameters

Related

Get Google+ shares without API key for each page?

On a search result page I would like to get the count of Google+ shares for the URL of each search result item via Ajax. I already managed to set up counting functions for Facebook and Twitter:
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
});
$.getJSON('https://api.facebook.com/method/links.getStats?urls='+ url+'&format=json', function(data){
fblikes = data[url].shares;
});
For Google+ I also already found a solution, but this requires the API Key for each URL. Is there any way to retrieve the Google+ count without such a key? Using it for tons of dynamically loaded search results, of course I cannot create an API key for each search result URL.
Yes, it's possible to get Google +1 counts. They are retrieved via a JSON-RPC POST call.
POST URL:
https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ
POST Body:
[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"%%URL%%","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]
where %%URL%% is the desired URL.
Have a look at the following:
Getting google +1 Page shares via AJAX (hidden Api)
http://www.sharedcount.com/documentation.php

How to pass object argument to PlusDomains.Circles.list in Apps Script

Recently was enabled Google + Domains API For Apps Script, I have explored some options and it seems is going to work, but in the specific case of PlusdDomains.Circles.list I don't know how to pass the second argument what is an object, I can not obtain several fields in the response, this is my code.
function getProfile() {
var userId = 'me';
var post = { maxResults: 2, fields:"title"};
var profile = PlusDomains.Circles.list(userId, post);
Logger.log('all: %s', JSON.stringify(profile));
}
this is the output,all: {"title":"Google+ List of Circles"}
if I try to get another field I don't know if this is correct, I put this:
var post = { maxResults: 2, fields:["title", "items"]};
but I get the same result:all: {"title":"Google+ List of Circles"}
If I try to get the result value for items, I get undefined. I don't how to pass the object correctly or if this is a bug in the Apps Script, somebody has idea??
I'm trying to get this working too. From the public google+ domain api docs it looks that the fields property expects a string with field names comma separated, i.e.
var post = { maxResults: 2, fields:"title,items"};
I don't seem to get the items populated (all the properties are undefined) in my google apps script. But when I use the API explorer "try it" console with OAuth2 enabled for scopes https://developers.google.com/+/domains/api/circles/list and https://developers.google.com/+/domains/api/circles/list I do see the items populated, so I'm thinking there may be an issue with my scripts authorization scopes or a bug in the google apps google+ domain service.

How do I fetch a list of Facebook names from a list of Facebook IDs with one API call?

I have fetched about 100 Facebook IDs from my database and stored them in a Javascript array.
For each of these, I want to fetch some data like full name, but I don't want to make over 100 API calls to do that.
What I'm using right now:
$.get('https://graph.facebook.com/'+id+'?fields=id,name',function(d){ d.name; });
What I'm hoping exists:
$.get('https://graph.facebook.com/?fields=id,name&list='+myList.join(','),function(d){ d[0].name; });
Or something similar using the Javascript SDK. Thanks in advance.
One way is to just provide the ID's in the querystring: Like this for the early facebook employees:
https://graph.facebook.com/?ids=4,5,6,7,8
I you have a lot of ID's its a good idea to limit the response to speed things up. This one gives you name+gender only:
http://graph.facebook.com/?fields=name,gender&ids=4,5,6,7,8
I thought of a way to do this and it works great:
FB.api('fql', { q: 'select name from user where uid in ('+mylist.join(',')+')' }, function (response) { response.data[0].name; });

How to set access token on analytics API?

i was wondering, the documentation has tutorials for implementing use of the Analytics API in several languages.
Now in PHP they show how to store the access token and maintain it , now i assume the JS somehow mentains it in some sort of local storage but i don't wish the user to authenticate each time he visitis so my plan is to save the access & refresh token in my database and simply applying it to the client-side instead of going through the all pop up procress.
According to tutorial this :
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, result);
Fires the popup which returns the access token but i'll say again i'm intrested in submiting token from database.
How can that be done?
is there some gapi.auth.setToken(token) method which after i could make calls to Core Reporting API?
I arrived here looking for a solution using this after having already written PHP to do the auth using google's PHP client libraries. I wanted to share the stored token as you mentioned, and be able to use javascript without re-authenticating, and/or triggering the popup (there may be a solution to this using the .init(callback) method, see docs/links at end).
Is there some gapi.auth.setToken(token) method
It turns out you can, there is the exact setToken(token) function you mention, and, you can even share the auth token generated earlier in PHP. What I'm not sure about yet, is if we should do it :)
I'm using PHP to do the initial auth, but presumeably in the javascript client you'd be able to call setToken() on something that you'd stored with getToken() in the same manner as this example. There may also be better approaches to this, like CORS (see links at end) mentioned in the API Authentication docs that I haven't had a chance to investigate any of these yet, but, I can give an example to answer the question, and might be useful to others needing the same behaviour
I first found Google developer Dan Holevoet's blog post with some sample JS code.
http://googleappsdeveloper.blogspot.com.au/2011/12/using-new-js-library-to-unlock-power-of.html
It's great to be able to query the API directly with javascript, and dynamically load lists etc, but the thing that worried me about this of course was storing clientid etc in js..
// Snippet from Dan's post
var clientId = 'YOUR_CLIENT_ID';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
But, according to Dan in an answer to the same question:
The apiKey is used in conjunction with designated referrers, which you
must declare in the APIs Console. If the key is sent from an
unauthorized referrer, it will not work. You should make your accepted
referrer list as limited as possible to ensure that others do not use
your apiKey for their own requests.
Now, my example is for the calendar API, but it all seems pretty consistent with the other APIs as well.
Note: This snippet was for proof-of-concept purposes only, and probably shouldn't be used in production. I assume the referrer protection mentioned makes something like this OK to do, but more thought needs to be given. It could be done by hidden input, AJAX call etc.. But in the end, they're all going to be visible in the javascript.
What I did to test the concept was to:
Authenticate via PHP client libs, using the same script/URL as callback (see [API console][2] for these callbacks)
On sucessful auth, in callback, set a global javascript variable in the page to the stored PHP auth token
Once page is loaded, on your first click event to use the javascript (or even in document ready), call authMe() to set the token
Then proceed as normal, calling any javascript API methods that you have given scope to in the initial PHP authentication process (in this case makeApiCall())
Like so:
In the php callback routine, regardless of whether authenticated yet (assuming that your callback URL is the same script), make this var global
<script type="text/javascript">
// A place to stick PHP's auth token once the auth dance is done
var dodgey_global_access_token = {};
</script>
Now, in php callback routine once we've checked that we're authenticated, and $_SESSION['token'] = $client->getAccessToken(); has been called (IE storing the auth token somewhere for later), or at least $client->getAccessToken() has something meaningful:
<script type="text/javascript">
// Set the js var via PHP here.. Yeck... Note json encode in php and parse in jquery
dodgey_global_access_token = $.parseJSON (<?php echo json_encode ($client->getAccessToken() ); ?>);
// dodgey_global_access_token now contains the auth token structure
// Removed auth-related functions in Dan's code - we'll already have a token
// Dan's orig function to list events in 'primary' calendar
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
// My function to setToken with the token injected from PHP authentication
function authMe () {
// Stuff the token into the gapi object
gapi.auth.setToken( dodgey_global_access_token );
// Now call the original 'makeAPICall' function now that we're 'authenticated'
makeApiCall();
}
</script>
Note: I used jquery in my example to quickly parse the JSON, we're already using it in the project, but if not, you'll have to find another library to do so
Relevant/useful docs:
// Sorry, as a new poster I can only post 2 hyperlinks,
// so embedding this in code snippet
//
// http://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs#gapi
// http://code.google.com/p/google-api-javascript-client/wiki/Authentication
// http://code.google.com/p/google-api-javascript-client/issues/detail?id=22
// http://code.google.com/p/google-api-javascript-client/wiki/CORS
// https://code.google.com/apis/console
Let me know if anything's unclear, and can post a working sample to demo.
Google API documentation has changed a bit from when this answer was first provided. google-api-javascript-client is no longer the recommended library for accessing google api libraries and Google suggests using discovery documents to load specific libraries.
As a result, the workflow that you are looking for in order to load all the libraries and set the access token would look like this:
var token = 'someaccesstokenfromoauth2'
gapi.load('client:auth2', function(){
gapi.client.load(
'https://analyticsreporting.googleapis.com/$discovery/rest',
'v4'
).then(function(){
gapi.auth.setToken({ access_token: token })
// business logic with gapi.client.analyticsreporting()
})
})
Load gapi with:
<script src="https://apis.google.com/js/api.js"></script>

How to list all comments in my domain

I am using the HTML5 version of Facebook Comment in my website. I have my own Facebook APP Id.
Using Graph-API, and FQL (I think this is how to do it), I want to list all the Comments posted in my website.
Example -
Page Title1
--Comment1
--Comment2
--Comment3
Page Title2
--Comment1
--Comment2
--Comment3
Page Title3
--Comment1
--Comment2
--Comment3
etc.
Please help me out.
It is possible, in two different ways, as long as you have a fixed set of sub-pages you want to fetch comments from.
If you have a large amount of sub-pages, or a variable amount, then you don't have a good scalable solution - and many have been looking for one:
Facebook fb:comments Graph API
How to display recent comments from Facebook Comments social plugin?
Facebook FQL query to return all comments against an application
Retrieve all comments with FQL by application ID
Facebook FQL query to return all comments against an application
fql query to get comment count no longer working
http://facebook.stackoverflow.com/questions/10023179/retrieve-all-the-comments-posted-using-fql
For a Fixed set of sub-pages in your website, you can either use a batch request, or an FQL query.
Batch Request
First, you need your access token. Just enter the following as a url in a browser (credit to this website ):
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=APP_ID&client_secret=APP_SECRET
And this is the javascript jquery code to make a batch request to fetch comments from several urls at once:
$.ajax({
url: 'https://graph.facebook.com/',
type : "POST",
data: {
access_token : 'YOUR_APP_ACCESS_TOKEN',
batch : '[ \
{"method":"GET","relative_url":"URL1"}, \
{"method":"GET","relative_url":"URL2"} \
]'
},
success: function(data) {
jdata = JSON.parse(data);
$.each(jdata, function(index,value){
jdata[index].body = JSON.parse(value.body);
console.log(value.body);
});
// Do whatever you want with jdata
}
});
FQL
inspired from this post
FB.api({
method: 'fql.query',
query: 'select text from comment where object_id in (select comments_fbid from link_stat where url="URL1" or url="URL2")'
}, function(response) {
// Do something with results
});
Conclusion
Because of this limitation of Facebook, I plan to switch to disqus.com, which apparently supports this feature (As you can see from this blog, for example. (search for 'recent comments')
Rather than list all the comments on your site, Facebook wants you to implement code to get notified when a new comment is posted anywhere on your site.
To make this happen, you have to put some Javascript into the page where the comment is posted to also notify yourself:
window.fbAsyncInit = function(){
console.log("subscribing to comment create");
FB.Event.subscribe('comment.create',function(response){
console.log("facbeook comment created: " + JSON.stringify(response));
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
FB.Data.waitOn([commentQuery], function () {
console.log("Facebook comment: " + JSON.stringify(commentQuery));
});
});
};
Where rather than just logging the comment to the console, you would need to implement some AJAX that would send the comment back to your site where you could store the comment in your database, or send yourself an email notifying you that the comment has been posted.
Reference: Facebook Comments Plugin
Say your website is http://mywebsite.com/blog.php?id=3 and you have a facebook comments plugin on it,
you can access comments this way
https://graph.facebook.com/comments/?ids={YOUR_URL}.
{YOUR_URL} becomes http://mywebsite.com/blog.php?id=3
Example 1: (Comments plugin installed on developers facebook doc website )
website: http://developers.facebook.com/docs/reference/plugins/comments
fetch comments: https://graph.facebook.com/comments/?ids=http://developers.facebook.com/docs/reference/plugins/comments
Example 2:
website: http://techcrunch.com/2011/04/08/the-seven-most-interesting-startups-at-500-startups-demo-day/
fetch comments: https://graph.facebook.com/comments/?ids=http://techcrunch.com/2011/04/08/the-seven-most-interesting-startups-at-500-startups-demo-day/
Check this too
Sample code for pulling comments can be found on this blog post

Categories

Resources