You want to create a script to read messages and post status updates to your own Facebook account, but you find the official documentation confusing and you aren’t sure where to start. Search no more because here you’ll find the easiest way to do just this.
The process is actually fairly simple, and recent updates to the Graph API explorer have made it dead easy:
-
If you haven’t done so, visit your applications page on Facebook to create a new application. The default settings are fine, so you can leave them unchanged.
-
Visit the Graph API explorer and on the top right corner choose your application. Click on the “Get access token” button, select the permissions you want to give to your application (depending on what you want to do you’ll probably need
offline_access
,read_stream
andpublish_stream
), then confirm to get your access token. Copy and paste this value into the example code bellow. -
That’s it! Now you can go and call any of the allowed methods from the Facebook Graph API. Also make sure to understand the difference between /home, /posts, /feed, and /statuses.
The following example code shows how to read posts from your news feed and post a new message to your own wall:
Note that code bellow uses some utf8 strings, this is basically to show that the script works with special characters as well. Make sure that your script is properly saved with utf8 encoding or, alternatively, remove the apostrophes within the example text strings.
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
use YAML::Tiny;
use JSON;
use URI;
use open qw(:std :utf8);
use utf8;
my $access_token = 'YOUR_ACCESS_TOKEN';
# Fetch your News Feed from Facebook
my $resp = graph_api('me/home', { access_token => $access_token });
for my $post (@{ $resp->{data} }) {
# do something with each $post
print Dump($post);
}
# Publish a new message to your own wall
graph_api('me/feed', {
access_token => $access_token,
message => 'Hello World! I’m posting Facebook updates from a script!',
link => 'http://nokyotsu.com/qscripts/2011/02/post-to-your-own-facebook-account-from.html',
picture => 'http://nokyotsu.com/qscripts/images/open-share-icon.png',
name => 'Post to your own Facebook account from a script',
caption => 'qscripts.blogspot.com',
description => 'You want to create a script to read messages and post status updates to your own '
. 'Facebook account, but you find the official documentation confusing and '
. 'you aren’t sure where to start. Search no more because here you’ll find '
. 'the easiest way to do just this.',
method => 'post'
});
exit 0;
sub graph_api {
my $uri = new URI('https://graph.facebook.com/' . shift);
$uri->query_form(shift);
my $resp = get("$uri");
return defined $resp ? decode_json($resp) : undef;
}
Note that, to be able to make secure https requests, you’ll also need to have installed either Net::SSL or LWP::Protocol::https. Finally, if everything works, you should be able to see something like this posted on your wall.
You’re welcome.