How to build a Flash ActionScript 3.0 Twitter Widget (updated)

Since Twitter is the largest social networking and microblogging service that enables its users to send and read messages, today I’ll show you how to build a Flash ActionScript 3.0 Twitter Widget that read twitter posts using Twitter API. Just put your username and you are good to go. Also, before starting, please study the user_timeline.


Preview


Settings all files

Create a new ActionScript File and save it as “MainClass.as” (fladev.twitter.MainClass) – this will be the Main Class for our flash file; the package classes extends the Sprite class (since we don’t have a timeline animation).
Finally create a new AS3 Flash file (590×470px) and open it, so that we have both files opened.


MainMovie

First of all let’s create a background for this widget. Draw some blue rectangles, add a logo perhaps with Twitter and try to imitate as much as you can my interface. After you finish, add 3 dynamic textfields on stage with instance names:

  • “content_txt” for content, choose multiline in textfield panel
  • “info_txt” for user info
  • “name_txt” for user account

In this last version, I put a MovieClip called preloader, in order to show something until load is completed.

All textfields must have embed characters and “Render text as HTML” option checked;


MainClass.as

Let’s add some constants and variables:

[as3]
public var content_txt:TextField;
public var posted_txt:TextField;
public var info_txt:TextField;
public var name_txt:TextField;
public var preloader:Sprite;
private var objectInfo:Object;

private static var count:int = 5; //how many posts
private static const USERNAME:String = "bataglia";//username
private static const REQUEST:String = "http://preview.fladev.com/how-to-build-a-flash-actionscript-3-0-twitter-widget/proxy.php?username=" + USERNAME + "&count=" + count;

private var urlLoader:URLLoader;
private var loader:Loader;
public var btnFollowMe:SimpleButton;
[/as3]

As you can see the constant REQUEST represents the path to proxy.php, that helps us to avoid the Twitter’s securities. So basically we can manipulate this as a simple Object.


The Constructor Function

[as3]
public function MainClass() {
Security.allowDomain("http://www.twitter.com");
urlLoader = new URLLoader();
urlLoader.load(new URLRequest(REQUEST));
urlLoader.addEventListener(Event.COMPLETE, displayInfo);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurity);
}
[/as3]


DisplayInfo function

If you put in a browser the value of the REQUEST constant, you’ll get all info from that count – posts, images etc (note here, that the info is encoded with JSON; for more info check this user_timeline and json.org). But we don’t want all “n” posts, to load once, because it will freeze and after close the application; so we need to split them, to paginate if you want this term. To do this, I created the variable “count”, that can be any value (max 250). Also, all info are stored in a main object, called “objectInfo”, to avoid making additional requests for each post.

Now that we understand how it works, let’s fill the textfiels with info.

[as3]
private function displayInfo(e:Event):void
{
objectInfo = JSON.decode(e.target.data);
preloader.visible = false;

content_txt.htmlText = getContent();

//show some info about the user
info_txt.text = "Followers: " + objectInfo[0]["user"]["followers_count"] + "; " + "Following " + objectInfo[0]["user"]["friends_count"] + "; " + "Tweets " + objectInfo[0]["user"]["statuses_count"] + ";";

//display the user account
name_txt.text = objectInfo[0]["user"]["screen_name"];

//create a loader for picture
loader = new Loader();
loader.load(new URLRequest(objectInfo[0]["user"]["profile_image_url"]));
addChildAt(loader, 1);
loader.x = 116;
loader.y = 102;
}
[/as3]

And here is the content formatted:

[as3]
private function getContent():void {
//show just month, day and hour
var posted:String = "";
var from:String = "";
var id:String = "";
var desc:String = "";
var content:String = "";

for (var i:int = 0; i < count; i++)
{
posted = objectInfo[i]["created_at"];
from = objectInfo[i]["source"];
id = objectInfo[i]["id"];
desc = objectInfo[i]["text"];

content += "<font color=’#224466′><a href=" + ‘"http://twitter.com/’ + USERNAME + ‘" target="_blank">’ + desc + "</a></font><br/><font size=’9′>" + "Posted on: " + posted.substr(0, posted.length – 11) + "; " + "From: " + from + "</font><br/><br/>";
}

//return all info
return content;
}
[/as3]

Test your movie, and see the result.


I’m not done with you…

If you want to run this from your local computer or from web, you will have a surprise:Twitter’s cross-domain security restrictions. To bypass the security restrictions we make the API request from PHP, by creating a simple .php file. Create a new file “proxy.php”:

[php]
<?php
$username = $_GET[‘username’];
$count = "&count=" . $_GET[‘count’];
$url = ‘http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=’;

$username .= $count;
$url .= $username;

$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);

ob_start();

curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();

$content = ob_end_clean();

//$content = get_content("");
echo $string;
?>
[/php]

Test your movie again and publish to web. Let me know if this works, also add me as TheFlaDev on your Twitter to stay in touch with latest tutorials/articles/comments. Cheers


Twitter Digg Delicious Stumbleupon Technorati Facebook

79 Responses to “How to build a Flash ActionScript 3.0 Twitter Widget (updated)”

  1. Can this be done with facebook?

  2. Perhaps, there are just 19 feeds on single page.

  3. noup..only for twitter. The API from Facebook is different.

  4. Chris Somerville 17. Oct, 2012 at 9:37 pm

    Does this still work?

    I can’t get anything to work but the swf background displaying?

    Help?

  5. Hi, yes it’s working. See the demo 😉

  6. This is a great tutorial and I’ve had this Twitter feed working for quite some time. But as of 10-19-2012 it has stopped functioning. The demo on this page is not working either. If there is an update it would be greatly appreciated. Thanks!

  7. Demo is blank.

    I tried on my end and getting blank swf too. I did notice that I have 11 errors.

    1012, 1013, and 1014. I am using Flash CS6 .

  8. Hey Robert, nice one. I think twitter have changed stuff with their api. Your demo longer working and the proxy.php returns limit exceeds error. Anyway to fix that.

    Thank You

  9. it seems like not working anymore.
    This XML file does not appear to have any style information associated with it. The document tree is shown below.

    Sorry, that page does not exist

    what is wrong out there? is that the twitter change some setting?

  10. TypeError: Error #1010: A term is undefined and has no properties.
    at fladev.twitter::MainClass/getContent()
    at fladev.twitter::MainClass/displayInfo()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    error message from flash.
    all helps will be highly appreciated

  11. Not working check again. Try it latest twitter API

  12. Hello guys, I just updated this app. Please download again and tell me if all goes well. Cheers!

  13. It works. But is the tutorial still the same, or do I have to change something to make it work? I have not tried the tutorial myself yet.

  14. The tutorial is updated also. Cheers 😉

  15. Hi Robert, I really like the way this looks and would love to implement it on my site. However, I doesn’t seem work, I have checked the preview.swf and the index.html and I am getting nothing. Is it supposed to work without editing it? I just wanted to check it. Also I think I have downloaded the updated file as I just did it today.

    Thank you for your work! Let me know if we can figure it out.

  16. Hey, tell me what errors you have, and also tell me if you change the line to proxy.php with your server.com/proxy.php

  17. Hi. I am a bit new to Actionscript, though I have programmed PHP and other languages.

    I get this error when I run the flash program: “Type was not found or was not a compile-time constant: Event”, and it direct me to this line:”private function displayInfo(e:Event):void {“. Though when I run spell check no errors shows up.

    By the way, should I put the main.class code inside a package and inside a public class called MainClass?

  18. Hi Robert,
    I’ve tried to load it in CS 6 and get 2 errors:

    C:\..\Flash\src\fladev\twitter\MainClass.as, Line 63 1120: Access of undefined property JSON.

    C:\..\Flash\src\fladev\twitter\MainClass.as, Line 3 1172: Definition com.adobe.serialization.json:JSON could not be found.

    Can you probably help me where it went wrong?

    Thx
    Gert

  19. Hi, you need to import the package – import.flash.events.Event I think it is 🙂

  20. Yes..it’s because you use the last version of Flash Player, and on some forums I saw it’s very fast, than the hole logical scheme. A quick fix is to use an older version, perhaps 10.1 or other. Also, there is a hint already for this, google it if you want to deep more. Cheers

  21. Sorry for my bad AS3 knowledge, but can you look at this code and say what is wrong?

    In my MainMovie file at frame 1 I wrote this (I tried to import the class):

    import myPackage.MainClass;
    var myMainClass:MainClass = new MainClass();
    import flash.events.Event;”

    And at the top of my MainClass.as I wrote this:

    package MainClass
    {
    import flash.display.Sprite;
    import flash.display.MovieClip;
    public class MainClass extends MovieClip
    {
    etc…

  22. And what errors you get?

  23. C:\Users\isak_2\Documents\Programmering\Flash_actionscript\Twitter api\MainClass.as, Line 1 5001: The name of package ‘MainClass’ does not reflect the location of this file. Please change the package definition’s name inside this file, or move the file. C:\Users\isak_2\Documents\Programmering\Flash_actionscript\Twitter api\MainClass.as

  24. The tutorial isnt working. My ‘movie’ wont play anything except the background. Is there a folder structure that im not aware of here or is having the MainClass.as file in the same directory as the .swf file ok?

  25. Hi Robert,
    Even when I try to preview your code, I get stuck on Loading part… is there anything I need to change to your original package in order to have in working locally on my computer? Proxy.php perhaps?

    I do have a wamp server running, if that matters.

  26. Before to do this, did you changed all paths (your username and proxy) ?

  27. Hey Robert, great tutorial. Do you think there is a way to make it run locally (from the swf on the harddrive). It works great online and when I test it in flash but not if I doubleclick on the swf. I know that there are security policy and I’ve haded my folder to the sandbox (http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html#117502) but still not working. Cheers.

  28. Hey there, how about converting this swf into Projector? Or build this in AIR, should be fine 😉

  29. Unfortunatly, it as to be integrated in a swf player that displays different movies in rotation 🙁