Update Facebook status using R? - facebook

Is it possible to update my facebook status from an R session?
EDIT 1: Reading the responses thus far, I would like to point out that I'm simply interested if a package already exists which provides this functionality, similar to how the lovely twitteR package does for twitter. Also, something doesn't have to be 'useful' in order to be 'fun', which is how I prefer to learn.
Edit 2: Sorry to anyone offended by me by not being more specific in how I asked my question. I have used R informally for 2 months and was told that SO was a nice place to ask questions (yes i have read the intro guide).

NB: The following only successfully logs you into facebook. I don't know why the status update at the end doesn't work, but maybe it is still of some value. It is based on a blog post over at Baratttalo back in March and which I thought would pass time on a friday afternoon.
I wasn't going to reply to this, but looking at some of the other responses and seeing as you helped me over at mathoverflow, I figured I'd give it a shot.
you'll need to install the RCurl and XML packages from http://www.omegahat.org/ (it's a pretty cool website to look at even just for fun i think).
Anyway copy and paste this:
library(RCurl)
library(XML)
log.into.facebook <- function(curl, id) {
curlSetOpt( .opts = list(postfields = paste('email=', URLencode(id$login.email), '&pass=', URLencode(id$login.password), '&login=', URLencode('"Login"'), sep=''),
post = TRUE,
header = FALSE,
followlocation = TRUE,
ssl.verifypeer = FALSE,
cookiejar = 'my_cookies.txt',
cookiefile = 'my_cookies.txt',
useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3'), curl = curl)
u <- "https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php"
doc <- getURL(u, curl = curl)
return(doc)
}
get.update.stutus.form.id <- function(curl, doc) {
curlSetOpt( .opts = list(post = FALSE), curl = curl)
doc <- getURL("http://m.facebook.com/home.php" , curl = curl)
html <- htmlTreeParse(doc, useInternal = TRUE)
# this gets the post_form_id value
form.id.node <- getNodeSet(html, '//input[#name="post_form_id"]')
form.id <- sapply(form.id.node, function(x) x <- xmlAttrs(x)[[3]])
# we'll also need the exact name of the form processor page
form.num.node <- getNodeSet(html, '//form[#method="post"]')
form.num <- sapply(form.num.node, function(x) x <- xmlAttrs(x)[[1]])
form.num <- strsplit(form.num, "/")[[1]][3]
return(list(form.id = form.id, form.num = form.num))
}
# This function doesn't work. I would love to know why though as it 'looks' right to me
update.status <- function(doc, curl, id) {
form <- get.update.stutus.form.id (curl, doc)
curlSetOpt( .opts = list(post = TRUE,
postfields = paste('post_form_id=', form$form.id, '&status=', URLencode(id$status), '&update=', URLencode('"Update status"'), sep = '')),
curl = curl)
u <- paste("http://m.facebook.com", form$form.num, sep = "/")
doc <- getURL(u, curl = curl)
return(doc)
}
and here's how you use the functions above (change id values to your log in details)
id <- list()
id$status <- "Hello world!"
id$login.email <- "YOUR LOGIN EMAIL"
id$login.password <- "YOUR LOGIN PASSWORD"
# log into facebook, seems to work fine
curl <- getCurlHandle()
doc <- log.into.facebook(curl, id)
# this is the bit that doesn't work, no idea why though.
update.status(doc, curl, id)
Hope that helps a little bit, maybe it will give you an idea. Also, I think the question you asked is fine, maybe just be a bit more specific next time and so maybe you'll avoid some of the comments you've gotten here :-)
Tony Breyal
P.S. I think there IS an api for all this somewhere, but if all you're interested in is updating the status, I quite like the idea of using the twitteR package and linking the updates to facebook.

I don't think so. It would require building a package to support the Facebook API, and nobody's done that for R. (And, really, why would they? It's not the best tool for the job! And it's not like you can pull large amounts of data from Facebook to do data analysis...)
What you could do is to use the twitteR package, update your status on Twitter, then connect your Twitter and Facebook accounts to get the update into Facebook.

I must admit I would never imagine someone would ask a question like this but.. :)
Use the httpRequest package (http://cran.fiocruz.br/web/packages/httpRequest/index.html) to update your status. It's just a POST. I can't find an example in R but here is an example in PHP - it's not difficult to see what being done: http://fbcookbook.ofhas.in/2009/02/07/facebook-reveals-status-api-how-to-use-it/

Right now (December 2013) it is possible to update Facebook status using R. You only need to use RFacebook package (http://cran.r-project.org/web/packages/Rfacebook/). All You need is to set up everything (here you have tutorial - http://thinktostart.wordpress.com/2013/11/19/analyzing-facebook-with-r/) and after that there is updateStatus function, for example:
updateStatus("Here is my new status", token)

Sure, study the API and create a package.
If your question really was "has anybody already done the work for me?" then the answer may be no.
In response to the comment, the classic "This is R. There is no if. Only how." still applies. Quoting from the fortunes package:
> library(fortunes)
> fortune("Yoda")
Evelyn Hall: I would like to know how (if) I can extract some of the
information from the summary of my nlme.
Simon Blomberg: This is R. There is no if. Only how.
-- Evelyn Hall and Simon 'Yoda' Blomberg
R-help (April 2005)
>
So in short, download the twitteR package, see how it uses the RCurl package to access the Web API and do likewise for Facebook's API. Or pay someone to do it for you.

Related

POST request using Power Query

I'm trying to collect data from the major electronic components distributors using their API with Power Query.
I was able to do it easily with ARROW and FARNELL as they use a GET request but now I'm trying to do the same thing with MOUSER but it's a POST request.
Here's the code I've written so far but it's not working :
edit
Can someone please help me and tell me what's wrong ?
The API documentation is here:
https://api.mouser.com/api/docs/ui/index#/SearchApi/SearchApi_SearchByPartNumber
Thanks for your help !
edit
My first attempt was really awful, I've made a few changes but it's still not working:
let
url = "https://api.mouser.com/api/v1.0/search/partnumber?apiKey=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
body = Json.FromValue({[SearchByPartRequest = ""], [mouserPartNumber = "LL4148"], [partSearchOptions = "3"]}),
Source = Json.Document(Web.Contents(url, [Headers=[#"Content-
Type"="application/json"], Content = body]))
in
Source
edit
I get the following error:
error message (from Power Query or the API ?)
The answer you're looking for is in the Web.Contents() function.
You can read more information here, here, and here.

Facebook Graph API Scheduled Posts created but not published

I'm using django-facebook's Open Facebook API to try to defer a post with an image to a facebook page. The (relevant part of the) code is:
graph_api = OpenFacebook(integration.long_lived_page_token)
message = "something"
picture = "http://example.com/image.jpg"
d = datetime.datetime.strptime('07-25-2014 06:40 pm UTC', '%m-%d-%Y %I:%M %p %Z')
timestamp = timestamp = int(time.mktime(d.timetuple()))
try:
facebook_response = graph_api.set('/{0}/feed'.format(
facebook_page_id), message=message,
link=picture, picture=picture,
scheduled_publish_time=timestamp, published=0)
except:
...
This seems to work fine (I get the post id on facebook_response) but when the time comes to post this scheduled post nothing happens. When I check at the facebook page I see an error saying 'Sorry, something went wrong publishing this scheduled post' and offers to delete it or post it then. So, I can't seem to figure out what am I doing wrong.
I found a similar question but it does not offer a good answer.
Oh, I forgot to say when I remove timestamp and published=0 parameters (i.e. I post on that exact moment), the post gets created and published on the page's feed.

Get the first product id in a magento system via soap api (2)?

Question: Is there a way (api call) to get the first product id in a magento install via the soap api.
I'm attempting to download all the products from a magento system and insert them into a different database (I do the conversion myself so that's not a bother) What is hard to understand though is how do I get a list of the product id's without getting all of them, if all I know is that the site is up.
Here's the info I have.
soap end point
soap username
soap apikey (aka password)
Here's what I don't know.
the id of any of the products
the date any of the products were created on or last edited.
For my initial load, I have to do a where product id in, because I expect 20 to 40k product lists won't come back in one soap call.
So I call
where id in (1 -> 100) Nope
where id in (101-> 200) Nope..
Now as you can imagine that code smells something fierce. It works, but I have to think there is a better way..
To expand my question: Is there a better way?
I can post the XML that I'm sending if that helps. The language I'm using to create the soap(xml) is vim, so I don't have code I can paste.
Try This
$client = new SoapClient('http://localhost/magento8/index.php/api/soap/?wsdl');
$session = $client->login('soap username', 'soap apikey');
$filters=array('entity_id'=>array(array('lt'=>'1','gt'=>'100')));//get fist 100 result
$result = $client->call($session, 'catalog_product.list',array($filters));
var_dump($result);
for more attributes check this
http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/using_collections_in_magento

Accessing data using facebook graph API in fb_graph [rails]

I encounter something annoying while playing around with the facebook graph API. I'm using fb_graph which is a ruby wrapper for the facebook sdk. I'm not sure if this issue I encounter is a limitation of the facebook sdk or I should contact the owner of fb_graph.
So, using fb_graph, this is how I would connect to a user:
jane = FbGraph::User.fetch('janeid', :access_token => "janeaccesstoken")
jane.friends will list all of jane's friends. However, if I try to get jane's friends birthday or email, it returns nil. In other words,
jane.friends[0].birthday => nil
But, I can access friends[0] birthday this way:
bill = FbGraph::User.fetch(jane.friends[0].id, :access_token => "janeaccesstoken")
In other words, if I wanted a list of all jane's friends' birthdates, I cannot do this:
#jane.friends.each do |friend|
puts friend.birthday
end
instead, it will have to be something like this
#jane.friends.each do |friend|
friendname = FbGraph::User.fetch(friend.id, :access_token => "janeaccesstoken")
puts friendname.birthday
end
I guess it's not too bad but it does make me wonder why this is the case, because actually only some info is nil. Name, for example, is not.
#jane.friends.each do |friend|
puts friend.name # => works!
end
The answer is here:
https://github.com/nov/fb_graph/issues/237.

Nothing except "None" returned for my Python web.py Facebook app when I turn on "OAuth 2.0 for Canvas"

I am a beginning Facebook app developer, but I'm an experienced developer. I'm using web.py as my web framework, and to make matters a bit worse, I'm new to Python.
I'm running into an issue, where when I try to switch over to using the newer "OAuth 2.0 for Canvas", I simply can't get anything to work. The only thing being returned in my Facebook app is "None".
My motivation for turning on OAuth 2.0 is because it sounds like Facebook is going to force it by July, and I might as well learn it now and now have to rewrite it in a few weeks.
I turned on "OAuth 2.0 for Canvas" in the Advanced Settings, and rewrote my code to look for "signed_request" that is POSTed to my server whenever my test user tries to access my app.
My code is the following (I've removed debugging statements and error checking for brevity):
#!/usr/bin/env python
import base64
import web
import minifb
import urllib
import json
FbApiKey = "AAAAAA"
FbActualSecret = "BBBBBB"
CanvasURL = "http://1.2.3.4/fb/"
RedirectURL="http://apps.facebook.com/CCCCCCCC/"
RegURL = 'https://graph.facebook.com/oauth/authorize?client_id=%s&redirect_uri=%s&type=user_agent&display=page' % (FbApiKey, RedirectURL)
urls = (
'/fb/', 'index',
)
app = web.application(urls, locals())
def authorize():
args = web.input()
signed_request = args['signed_request']
#split the signed_request via the .
strings = signed_request.split('.')
hmac = strings[0]
encoded = strings[1]
#since uslsafe_b64decode requires padding, add the proper padding
numPads = len(encoded) % 4
encoded = encoded + "=" * numPads
unencoded = base64.urlsafe_b64decode(str(encoded))
#convert signedRequest into a dictionary
signedRequest = json.loads(unencoded)
try:
#try to find the oauth_token, if it's not there, then
#redirect to the login page
access_token = signedRequest['oauth_token']
print(access_token)
except:
print("Access token not found, redirect user to login")
redirect = "<script type=\"text/javascript\">\ntop.location.href=\"" +_RegURL + "\";\n</script>"
print(redirect)
return redirect
# Do something on the canvas page
returnString = "<html><body>Hello</body></html>"
print(returnString)
class index:
def GET(self):
authorize()
def POST(self):
authorize()
if __name__ == "__main__":
app.run()
For the time being, I want to concentrate on the case where the user is already logged in, so assume that oauth_token is found.
My question is: Why is my "Hello" not being outputted, and instead all I see is "None"?
It appears that I'm missing something very fundamental, because I swear to you, I've scoured the Internet for solutions, and I've read the Facebook pages on this many times. Similarly, I've found many good blogs and stackoverflow questions that document precisely how to use OAuth 2.0 and signed_request. But the fact that I am getting a proper oauth_token, but my only output is "None" makes me think there is something fundamental that I'm doing incorrectly. I realize that "None" is a special word in python, so maybe that's the cause, but I can't pin down exactly what I'm doing wrong.
When I turn off OAuth 2.0, and revert my code to look for the older POST data, I'm able to easily print stuff to the screen.
Any help on this would be greatly appreciated!
How embarrassing!
In my authorize function, I return a string. But since class index is calling authorize, it needs to be returned from the class, not from authorize. If I return the return from authorize, it works.