Home >
Welcome back to our exciting Facebook ActionScript series. In this article we will discuss one of most important (and most exciting) features of the FB platform, it's the publishing of news. We all know when we log in to facebook, we see plenty of news about our friends. Some were sent by the users, some where sent by applications. In lots of cases, the action is initiated by applications. We see stuff like "FriendX has just completed level 5", "FriendY just left the building" or "John just sent something to his friends", I'm sure you saw a lot of news similar to this on FB. News are an integral part of application because it's one of the ways that the virality of applications is ensured. Suppose we have the fanciest application on FB, what value we have out of this application if we do not publish any news, if we dont make sure the friends are not notified about the action don't in the application? The application simply needs to "talk" and publish news if the application user performed some action. We need to make sure everybody knows that we just topped the high score of the player from Nigeria.
Like in the previous sample, we will make sure the PHP method AND the ActionScript methods are covered. Note that we need to know both methods in order to have all the necessary skills to develop demanding and stable facebook applications. What we need here is to complete the tutorial is the FLA we worked on previously, the facebook api key, secret etc. Beside that we will work in the Feed Preview console to create a valid feed template. All those factors are needed to complete the article. Now let's get our hands dirty, we don't want to waste time anymore.
First we need to go to to the feed template console that will allow us to create a sample console. First we need to go to this location:
http://developers.facebook.com/tools.php?feed
We need to log in, after that we see the following screen:
First we need to associate the feed with the application we are working on. In our case we will select the name of the current application. Unfortunately I really don't know what is the actual name of the test application on your side.
Ok, make sure you select the test application and click next, what happens next?
We see the default settings for news templates. Let's begin with the simple things.
{*actor*} likes one line templates.
{*actor*} in this case represents the name of the application user. Let's change it to match out needs. Here is how it can look like:
{* actor *} works hard learning from articles from InsideRIA
Type this sentence there and click next.
By clicking on the „Update preview“ button and we get the idea of how the line will appear in the news feed. We also see that the {*actor*} placeholder was replaced by the actual name of the user.
Ok, let's click next to move to the next screen.
The next screen is the optional short story template. This is only visible if the facebook user chooses to display short story templates as news rather then the simple one line news like discussed above. Even if it is optional, we still want to populate it. Populate the title with the previous one:
{*actor*} works hard learning from articles from InsideRIA
And the body should contain this:
{*actor*} received articles from InsideRIA from {*target*}.
The news line really do not make any sense now simce we just want the news to appear. Later we can modify the templates to match the application logic.
Click on the „Update preview“, here is how the result looks like:
We see the lines we created, and there is also the profile image of us, beside that there are 2 images that appear beside above the lines. Those are the default images provided by facebook and in order to change them, we need to modify the detault template data:
As we can see, we can pass as many images as want to the images array, in the following form:
images =
{"src": "http://myServer.com/image.jpg", "href":"http://www.linkToMySite.com"},
{"src": "http://myServer.com/image.jpg", "href":"http://www.linkToMySite.com"},
{"src": "http://myServer.com/image.jpg", "href":"http://www.linkToMySite.com"}
We simply pass a parameter of objects containing the path to the image and the link to the server. We can add as many images as we want, how sweet! But in our case, we just need one image, so here is how the array will look like:
{"images":[{"src":"http://www.insideria.com/upload/2009/04/fb_app_8.jpg", "href":"http://www.insideria.com"}]}
Added to the template box:
After hitting the update button, here is the result:
How sweet! The template is almost done.
The next thing we see is the action link. This is the simple link that appears right beside the one line news template. Type in the following values:
Hit the update button and the result should look similar to this:
As we can see this allows us to seamlessly integrate friends into the application experience.
Hit the „Next“ button, review the template once again and hit "Register template bundle“. We get the following result:
The template bundle is registered! Cool, now we will use this id in the application process every time we want to publish news. We can register a lot more templates and associate it with one application, but in this case we just need one. Let's move on to PHP, it really gets more and more exciting!
Let's see how this looks like in reality. We will use the template bundle id to identify the template in the code.
Open the index.php file where we usually host the swf on facebook. It should look similar to this:
<?php
//include facebook api etc.
require_once("facebook/client/facebook.php");
require_once("keys.php");
//create new facebook instance
$facebook = new Facebook(API_KEY, SECRET);
//propmpt the user to login
$fb_user = $facebook->require_login();
//check if the user has added the app
if (!$facebook->api_client->users_isAppUser()) {
//if not, redirect him to add it
$facebook->redirect($facebook->get_add_url());
}
?>
<fb:swf swfsrc='http://myServer.com/myFacebookApp/ria.swf' flashvars="<?= $_SERVER['QUERY_STRING'] ?>" allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='550' height='400'/>
Comment out the swf embed code:
<!--
<fb:swf swfsrc='http://myServer.com/myFacebookApp/ria.swf' flashvars="<?= $_SERVER['QUERY_STRING'] ?>" allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='550' height='400'/>
-- >
This is because we want to concentrate on the PHP code. Here is the complete PHP code at the top:
<?php
//include facebook api etc.
require_once("facebook/client/facebook.php");
require_once("keys.php");
//create new facebook instance
$facebook = new Facebook(API_KEY, SECRET);
//propmpt the user to login
$fb_user = $facebook->require_login();
//check if the user has added the app
if (!$facebook->api_client->users_isAppUser()) {
//if not, redirect him to add it
$facebook->redirect($facebook->get_add_url());
}
$tokens = array();
$target_ids = array();
$body_general = '';
$sent = $facebook->api_client->feed_publishUserAction(84654184238, json_encode($tokens), implode(',', $target_ids), $body_general);
?>
And the result is:
Cool, this are the news we created previously and finally they make they premiere appereance on Facebook. The lines of code:
$tokens = array();
$target_ids = array();
$body_general = '';
$sent = $facebook->api_client->feed_publishUserAction(84654184238, json_encode($tokens), implode(',', $target_ids), $body_general);
make the magic happen. First we define the tokens, in ur case it's the array of images. Since we do not want images to show up, the array will be left empty. The target id's are the ids of friends who take part in the action, but are only visible in the extended view. In this case, leave the body general empty too. The final line of code is the feed_publishUserAction which takes the tamplate id, the tokens, the target ids and the body as arguments to publish the news. Those are the steps that are required to publish the action in PHP, not that complicated. In reality, publishing news directly upon loading of application, like in this case, is forbidden by facebook because it violates the application terms of use.
Ok, now that we know how to publish an item, it's time to expand the idea. As we can see, every news story has it's own unique id. That is useful in scenarios when we have an application with lots of different actions the user can take. Let's say we have a small RPG. We could create an array of small news lines and use it in the code, like this example:
$oldtemplates = $facebook->api_client->feed_getRegisteredTemplateBundles();
$tokens = array();
$target_ids = array();
$body_general = '';
$sent = $facebook->api_client->feed_publishUserAction($oldtemplates[0]["template_bundle_id"], json_encode($tokens), implode(',', $target_ids), $body_general);
<div style="text-align: left;">With:</div>
$oldtemplates = $facebook->api_client->feed_getRegisteredTemplateBundles();
we receive an array of all registered template bundles we got for the application and we simply refrence it via:
$oldtemplates[0]["template_bundle_id"]
$oldtemplates[1]["template_bundle_id"],
$oldtemplates[2]["template_bundle_id"]
.
.
.
One cool thing that is available on the facebook platform is the ability to dynamically create feed stories without the mentioned feed preview console. It's a bit more complicated, but worth mentioning. Here is the sample code:
$one_line_story_templates = array();
$one_line_story_templates[] = '{*actor*} likes articles from InsideRIA’;
$short_story_templates = array();
$short_story_templates[] = array('template_title' => '{*actor*} likes articles from InsideRIA', 'template_body' => 'InsideRIA is the premier site for RIA development.'); $full_story_template = null;
$action_links = array();
$action_links[] = array('text'=>'Go to InsideRIA', 'href'=>'http://www.insideria.com/'); $id = $facebook->api_client->feed_registerTemplateBundle($one_line_story_templates, $short_story_templates, null, $action_links);
echo $id;
And the result should display the id of the newly created news template. Cool, we just created a one line story directly from the code! Now, we should go on and try to test it. Copy the news template id to the clipboard, remove the above code and place this:
$tokens = array();
$target_ids = array();
$body_general = '';
$sent = $facebook->api_client->feed_publishUserAction(yourNewTemplateID, json_encode($tokens), implode(',', $target_ids), $body_general);
and the result is:
Now we see that the newly created news template was just published. We see the text and the action link that links to InsideRIA. When we go to the list of registered template bundles, we see that the dynamically created news template is on the list:
ActionScript 3
Let’s try to accomplish the same using ActionScript library. First we want to try to publish the news, after that we will del with other things here like registering template bundles and publishing multiple story templates. The ActionScript FB api offers almost the same functionality compared to the PHP version. Of course I could start this article directly with the ActionScript version, but in that case we would miss a lot of basic information that become visible only when using the PHP version. Now with this knowledge we are equipped and ready for the ActionScript version.
Let’s begin with creating the session, here is the code:
import com.facebook.Facebook;
import com.facebook.net.FacebookCall;
import com.facebook.utils.FacebookSessionUtil;
import com.facebook.events.FacebookEvent;
import com.facebook.commands.feed.*;
import com.facebook.data.feed.*;
var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("YOUR_API", "YOUR_SECRET", loaderInfo);
fbook = session.facebook;
We sould compile the swf and upload to make sure that there are no errors that will haunt us later. Compile, upload and run the swf in the Facebook application canvas. We can only move forward if there are no errors in the swf. The next step would be simply to call the publishUserAction directly in ActionScript. Ok, let’s move on to the next line of code:
var call = new PublishUserAction("yourTemplateID", {}, [], null, com.facebook.data.feed.StorySizeValues.SHORT, null);
call.addEventListener(FacebookEvent.COMPLETE, newsPublished);
fbook.post(call);
function newsPublished(e:FacebookEvent):void{
trace("news sent...");
}
So the complete code in the first frame would look like this:
import com.facebook.Facebook;
import com.facebook.net.FacebookCall;
import com.facebook.utils.FacebookSessionUtil;
import com.facebook.events.FacebookEvent;
import com.facebook.commands.feed.*;
import com.facebook.data.feed.*;
var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("YOUR_API", "YOUR_SECRET", loaderInfo);
fbook = session.facebook;
var call = new PublishUserAction("yourTemplateID", {}, [], null, com.facebook.data.feed.StorySizeValues.SHORT, null);
call.addEventListener(FacebookEvent.COMPLETE, newsPublished);
fbook.post(call);
function newsPublished(e:FacebookEvent):void{
trace("news sent...");
}
And the final result would be:
Finally, we published news directly from the SWF! That’s huge for us developers because now we know that we really do not need to connect to PHP in order to publish news. In this case few lines of code are necessary in ActionScript. This approach makes the swfs completely independent from server side code. Now we will try to extend the sample and try to register template bundles from the swf. The sample will display a simple text field where the user will type in text. The text will be saved as a unique temple bundle and published to the world. In some aspects, this resembles complex games, where template bundles are registered on the fly and published later. So, here is how it will be done. First we place to code to register a dummy template bundle:
import com.facebook.Facebook;
import com.facebook.net.FacebookCall;
import com.facebook.utils.FacebookSessionUtil;
import com.facebook.events.FacebookEvent;
import com.facebook.commands.feed.*;
import com.facebook.data.feed.*;
var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("2b6378f4f5b55953f0c87d1eac40e4a1", "2151000c183a927ebbc7e24869d26a36", loaderInfo);
fbook = session.facebook;
var short_story_templates = new TemplateCollection();
var tplData = new TemplateData();
tplData.template_title = "{*actor*} likes articles from Flash :-)";
tplData.template_body = "That's true :-)";
short_story_templates.addTemplateData(tplData);
var call = new RegisterTemplateBundle(["{*actor*} likes articles from Flash :-)"], short_story_templates, null, null);
call.addEventListener(FacebookEvent.COMPLETE, templateRegistered);
fbook.post(call);
function templateRegistered(e:FacebookEvent):void{
trace("templateRegistered...");
}
When the swf is compiled and uploaded, and when we run it in the FB canvas, nothing happens but when we check the registered template bundles, we see the newly created bundle:
Let’s see if the newly created bundle actually works. On every side, the newly created template bundle has a unique id, so copy it any paste it so the it maches the following:
var call = new PublishUserAction("85533189238", {}, [], null, com.facebook.data.feed.StorySizeValues.SHORT, null);
call.addEventListener(FacebookEvent.COMPLETE, newsPublished);
fbook.post(call);
function newsPublished(e:FacebookEvent):void{
trace("news sent...");
}
We see that finally we have the story published, that’s great since we know that the story was registered from within Flash. Now let's move on to create the app with the text field where we will allow users to type in their own news.
Clear the stage to make room for new components.
Place an input text field and a button on the stage.
Name them news_txt and publish_btn respectively. Now, we need to create the event for the button. As soon as the button is clicked, the story needs to be published.
Here how the code looks like:
import com.facebook.Facebook;
import com.facebook.net.FacebookCall;
import com.facebook.utils.FacebookSessionUtil;
import com.facebook.events.FacebookEvent;
import com.facebook.commands.feed.*;
import com.facebook.data.feed.*;
import com.facebook.data.NumberResultData;
var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("2b6378f4f5b55953f0c87d1eac40e4a1", "2151000c183a927ebbc7e24869d26a36", loaderInfo);
fbook = session.facebook;
publish_btn.addEventListener(MouseEvent.CLICK, clicked);
function clicked(e:MouseEvent):void{
var short_story_templates = new TemplateCollection();
var tplData = new TemplateData();
tplData.template_title = "{*actor*}" + news_txt.text;
tplData.template_body = "That's true :-)";
short_story_templates.addTemplateData(tplData);
var call = new RegisterTemplateBundle(["{*actor*}" + news_txt.text], short_story_templates, null, null);
call.addEventListener(FacebookEvent.COMPLETE, templateRegistered);
fbook.post(call);
}
function templateRegistered(e:FacebookEvent):void{
var call = new PublishUserAction(e.data.value.toString(), {}, [], null, com.facebook.data.feed.StorySizeValues.SHORT, null);
call.addEventListener(FacebookEvent.COMPLETE, newsPublished);
fbook.post(call);
}
function newsPublished(e:FacebookEvent):void{
trace("news sent...");
}
Now when we type in news into the input field:
By clicking the Publish button, here is how it looks like:
Cool, finally it works!
I agree that the app we made is not spectacular, but it was not the goal to create spectacular stuff since we concentrated to demonstrate the details of the news publishing process. Publishin news are perhaps the most important part in facebook application development since it gives us the ability to expose actions taken by the user and allow other to get involved, via the action links. With all that knowledge equippled, slowly you are becoming a real master in the facebook application development. Be sure to reread this article and make sure the code works on your side because if your apps do publish news and not "talk" to others, you are going to stay lonely!
To view the entire series please visit http://www.insideria.com/series-facebook-dev.html




Facebook Application Development
Hello,
This is a brilliant tutorial but can it does not publish to user home wall can you please write a tutorial that will do that.
And thanks again for this tutorial.
Hello,
Great set of tutorials really helped me out.
I'm in a jam with this one though.
I keep getting a error with this line:
e.data.value.toString()
1119: Access of possibly undefined property value through a reference with static type com.facebook.data:FacebookData.
What am I missing
Cheers
Great post, I wish I had come across it before I figured it all out on my own. Unfortunately, it stops just where I got stuck - trying to send template data. I have tried a thousand different ways to format the template_data object but none of them seem to take. What is the syntax for poulating a custom token?
Thanks a lot,
It works fine now, is there a way the hole template can show and not a single line?
Nacho
Have the same problem as Nacho, could you share the solution?
thanks
use:
Object(e.data).value.toString()
Hello nice series of code,
I want to know about,
is there a way the hole template can show and not a single line?
Thank you
I am glad to talk with you and you give me great help! Thanks for that,I am wonderring if I can contact you via email when I meet problems.
Hi Rebecca
glad you like my posts.
You can follow me on twitter where I publish my commercial videos
covering flash.
http://twitter.com/mirzahat
You can contact me anytime regarding my posts.
Regards,
Mirza
Hello Mirza,
Thanks a lot for your great posts :D
I've got a question for you: is it possible to publish Full Size Stories from Flash?
Thanks,
Vincenzo
Hi Mirza,
This is a fabulous tutorial! nothing else covering this on the web right now.
I have a question (here it comes!)...
When making the call to 'RegisterTemplateBundle' - how would I also include images and links for the full story?
many thanks
Duncan
This is on the facebook site.
"Facebook will deprecate template bundles and their related API calls December 20, 2009.
Please start using stream attachments with stream.publish, FB.Connect.streamPublish, and Facebook.streamPublish instead."
how would we use stream.publish, FB.Connect.streamPublish, and Facebook.streamPublish with flash?
thanks!