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. Hi
    This is great tutorial. I wonder how to display last 5 feeds of my twitter. Hope it is possible.
    Thanks for your time
    Krish

  2. Brilliant work and tutorial. I am however having a slight problem. When loaded i am receiving the second newest tweet and not the current tweet, like the second tweet down the list. ?????/ any idea what i may have done wrong

  3. Sorry bout last post i got it working, somehow private var num:Number = 0;//display first post info had 1 instead

  4. @krish: name_txt.text = xml.status[0].user.screen_name + xml.status[1].user.screen_name ……
    xml.status[5].user.screen_name;

    I think this will be ok, let me know if still have problems.

    Cheers

  5. @Ryan: yes, that was the first post.

  6. Thank you so much, your tutorial is the best for Twitter API!

    Congratulations, great job 😉

  7. Hey Robert,

    Can you post exactly how to change your code in order to call 3 or more feeds. I can’t get it to work, but furthermore it works flawlessly!

    Thanks!

    Arnold

  8. you have private var num:Number = 0;//display first post

    so, it will display first post. To show 3 posts as once you have to create 3 textfields, something like:

    txt1.text = xml.status[1]
    …….
    txt3.text = xml.status[3]

  9. Hey Robert,

    Thanks! That works flawlessly.
    One more thing, I’ve uploaded a test version but the text doesn’t show up.

    http://arnoldveeman.com/flashfiles/updates/twitter%202/

    And it keeps waiting for your activeden.fladev.com site?

    I’ve edited the MainClass.as file as you mentioned and also put the proxy.php online (with read/write rights)

  10. I create a new version, more light that will add easily posts as much as you want. Feel free to send me any questions. Cheers!

  11. Hi Arnold, sorry for this delay; I saw your example and your request to my website, probably you didn’t change the paths inside of MainClass.as file. You should open again,

    private static const URL:String = “http://activeden.fladev.com/tutorials/twitter/”; // this is where your folder will be, also with yor .php file
    private static const REQUEST:String = URL + “proxy.php?url=” + FEED; // here is your php file along with your url
    private static const FEED:String = “http://twitter.com/statuses/user_timeline/” + USERNAME + “.xml”; is the twitter address with your ID.

    Replace these lines with your info and everything should be ok, if now send me an email.

    Thank you,
    Robert

  12. Hello, really nice article!

  13. Hi Robert,
    Great tutorial. Any thoughts about doing a tutorial using the Oauth using CS5 for Mobile Air. There seems to be absolutely no tutorials on how to accomplish this task. It’s a shame. Thanks again. Wonderful tutorial btw.

    Best Regards,
    Peter Tucker

  14. Hi Robert,

    This tutorial has been very helpful and works brilliantly locally using the ‘FEED’ ‘URLRequest’. However when I try it from the Web using the ‘REQUEST’ variable the ‘displayInfo’ function does not fire.
    I’m presuming this is because the ‘URLLoader’ does not complete.
    Any thoughts on why this could be?

    Thanks
    Andy

  15. Hi Andy, download again the sources. Everything should be fine now.

  16. Hi Robert,

    I changed the MainClass.as to private var num:Number = 0; to read the latest post, but it is still calling up the second last posting. Any ideas?

    Also, I am not getting the posted date showing. Should this be shown through the var content_txt or var posted_txt? If it is the latter where is it called (I only see posted being called).

    Any help would be greatly appreciated! Thanks

  17. Hi Robert, I got the posted date showing, but still seeing the 2nd latest post (as mentioned in last message even though I changed the number to 0). Please advise. Thanks.

  18. @Mike first of all make sure your files are not in cache, so clear it. Then put a simple trace command to your .XML after this was loaded:

    trace(xml)//play around with that values, 0, 1, 2.. and see if you got different results.

  19. I have had 3 different people test this tutorial and NONE of us had any success. What is the deal??

  20. Congratulations, but i have a problem!

    Why words like etrnônico don´t displayed with all caracteres?

    It´s what happen:

    eletrônico == > eletrnico
    amanhã ==> amanh
    Mário ==> Mrio

    thanks

  21. don´t work online! not showing tweets, but local ok!

  22. It works perfectly online, i think the people with problems are rushing, please read each line slowly and it should work, mine up and running,thanks again mate, excellent tutorial!

  23. Sorry, but it’s not working. I tried everything. In your file it’s working but if I copy it in my file then it’s not working.. The MainClass.as is located in the same folder but I have to add “src” to it and in your file it’s without “src”, very strange. Can someone help me with this?

  24. @Nick Menez – you’re right.
    @Jamie – let the MainClass where it is; just edit the path to your server/files and will be ok.

  25. Just awesome script !!!
    It works perfectly in local for me but when I put my files online it doesn’t work anymore :s
    Any idea ?
    thanks for your help !!

  26. @chris make sure you put your paths right before to compile.

  27. Hey Robert, great tutorial but I’m getting an error message from Flash that says it has stopped a potentially unsafe operation, and so my tweets aren’t displaying. Do you know how to solve this? Thanks.

  28. Did you open this on your local computer? If yes, then upload this to a server

  29. do you have to attach mainclass.as? I get the error “1114: The public atribute can only be used inside a package”

    on line
    public function MainClass() {
    urlLoader = new URLLoader();
    urlLoader.load(new URLRequest(REQUEST));
    urlLoader.addEventListener(Event.COMPLETE, displayInfo);
    }

    thank you

  30. Make sure you close all brackets {}

  31. Hi,
    I want to know how to tweet from this application. Can you let me know if there is any possibilities?

  32. Great tutorial Robert! Very clean and concise. Uploaded to a test directory on my FTP. Not sure why the info isn’t displaying. Could this be a server or file permissions issue? Thx

  33. Did you change all paths and also include the proxy.php in your file directory?

  34. I didn’t change much, so that’s where I could be falling short. Here’s what I did…

    I updated the MainClass.as file, changing the USERNAME:String to my Twitter account and the URL:String the test directory on my server and to the location of the proxy.php file.

    That seems to be working as I can see all of the info — http://www.marcuspape.com/test/proxy.php?url=mgpape

    Other than that I didn’t change anything. Is there a relative path somewhere that I may have missed?

  35. Hi,
    Nice tutorial..
    This application provide tweets related to the particular name only.
    I want to gather all tweets means other people tweets added on that twitter.
    For ex. if i provide nfl name (http://twitter.com/#!/nfl)it shows me only tweets posted by nfl.
    I want other people tweets also.
    (like “MiamiDolphins Miami Dolphins
    by nfl
    In this week’s @DanMarino podcast, #13 talks about his passing records, 0-3 & more. Plus, your Twitter questions: thefinsiders.com/blog/2011/13-m…”
    )
    Is their any way to access all tweets.
    Thx..

  36. Anyone know if this still works? I used to have it this way too, but doesn’t work now.

  37. aravindakumar 06. Dec, 2011 at 9:34 pm

    Hi,
    for the testing purpose i made new file with some changes based on this tutorial after some time i got some message like this “Rate limit exceeded. Clients may not make more than 150 requests per hour. /statuses/user_timeline.xml?screen_name=raj”. how to solve this?

  38. It’s strange, maybe put just 100 ? don’t know what to say

  39. Hi,
    I can load mywidget when I use on your server
    (http://preview.fladev.com/how-to-build-a-flash-actionscript-3-0-twitter-widget/proxy.php?url=) But when I include proxy.php in my file directory.It doesn’t work( my server is http://flasher.net46.net/proxy.php)

    What can I solve this problem?

  40. Great Tut! Works like a charm! Just one simple newbie question for you. How can I add a button within your MainClass to load and external swf? I’ve tried with all my mojo (what little of it there is) and have failed miserably. Here is my most recent error message:

    Scene 1, Layer ‘Actions’, Frame 1, Line 11 1046: Type was not found or was not a compile-time constant: MouseEvent.

    Thanks!

  41. @hakan: did you change the paths to that proxy.php, in order to be on your server?

  42. @Clayton: You should import all classes from MouseEvent 🙂

  43. Hey! thanks for the tut! It works perfectly! but I did a SWF movie and I need it to refresh automatically without compiling every time to be able to see the new tweets.
    It’s not online

  44. I used you tut and have recreated the twitter reader and as long as I am pointing to your proxy.php it works great, but once I point it to mine on my server I get this message:

    TypeError: Error #1085: The element type “link” must be terminated by the matching end-tag “”.

    at fladev.twitter::MainClass/displayInfo()[G:\CTIS.App\iPhoneApp\src\fladev\twitter\MainClass.as:56]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    Any idea on what might be causing it and how I can fix it? I thought it might not be hitting my php for some reason but I have hit phps off my server with no problems in different flas for a while now.

    One more thing, when I try to make this twitter reader as a part of another project it loads but doesn’t pull down any twitter info. I have the MainClass in place but still getting blank information. Any tips here?

  45. I imported all MouseEvents and it still isn’t working. I found a work around however. I just loaded a smaller version into a frame with my nav buttons and it works great!

    However, when I try to use your Twitter Reader in my own fla, without importing it, I can’t pull down any info from twitter, it’s all blank. I have MainClass set as the document class, but nothing. Any ideas?

    Thanks!

  46. it seems that your example doesn’t work anymore 🙁 Did twitter change something ?

  47. Hi robert,

    Nice tutorial. I’m creating a ‘more’ button so that I can load more of my twitter status. Originally when I open this program, it will load 5 status, when I press the ‘more’ button, it will load total of 10 status and so on.

    Question is how do I change these line of codes? Do I use a for loop to generate more status?

    content_txt.htmlText = getContent(1) + getContent(2)+ getContent(3) + getContent(4);

  48. Hello, nice tutorial out here, it’s just what I need. I’ve met some problem. Take a look at this:

    content_txt.htmlText = getContent(20);

    It will generate Error #1010 when the numbe r inside getContent(is more than 19).

    Why is that so?