Home » ActionScript 3.0, Flash CS5

AS3 + Twitter interaction code snippets | Flash

26 December 2011 No Comment
Share on Facebook

As a programmer we would like to reuse the actionscript code often, and the code snippets will be handy when we need to reuse again and again.

Here we have shared some of the AS3 code snippets to work with twitter.

AS3 Post tinyurl to Twitter via Twitter webpage:

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.navigateToURL;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLLoaderDataFormat;

	public class Main extends Sprite
		private var tinyLoader:URLLoader

		public function Main():void
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);

		private function init(e:Event = null):void
			removeEventListener(Event.ADDED_TO_STAGE, init);
			stage.addEventListener(MouseEvent.CLICK, postToTwitter);
			tinyLoader  = new URLLoader();
			tinyLoader.dataFormat = URLLoaderDataFormat.TEXT;
			tinyLoader.addEventListener(Event.COMPLETE, gotTinyURL);

		private function postToTwitter(event:MouseEvent):void {
			tinyLoader.load(new URLRequest('http://tinyurl.com/api-create.php?url=http://www.adrianparr.com'));

		private function gotTinyURL(event:Event):void {
			var reqString:String =  'http://twitter.com/home?status=Check this out ' +  encodeURIComponent(tinyLoader.data);
			navigateToURL(new URLRequest(reqString), "_blank");



AS3 code to post tinyurl to twitter. view code on snipplr.com

Get twitter ATOM search feed:

var query:String = "greenwich";
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://search.twitter.com/search.atom?lang=en&q="+query));
myLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event) {
	myXML = new XML(e.target.data);
	myXML = removeNS(myXML);
        // then use myXML object as normal to access various parts of the feed
	for (var i:int = 0; i < myXML.entry.length(); i++){

function removeNS(anXML:XML){
	var xmlString = anXML.toXMLString();
	var xmlnsPattern = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");
	var namespaceRemovedXML = xmlString.replace(xmlnsPattern, "");

	var aaaPattern = new RegExp("aaa:lang[^\"]*\"[^\"]*\"", "gi");
	var aaaRemovedXML = namespaceRemovedXML.replace(aaaPattern, "");

	var twitterPattern = new RegExp("twitter:", "gi");
	var twitterRemovedXML = aaaRemovedXML.replace(twitterPattern,"");

	var openSearchPattern = new RegExp("openSearch:", "gi");
	var openSearchRemovedXML = twitterRemovedXML.replace(openSearchPattern,"");

	var responseXML = new XML(openSearchRemovedXML);
	return responseXML;

view code on snipplr.com


OAuth Example with the Twitter API

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;

	import org.iotashan.oauth.OAuthConsumer;
	import org.iotashan.oauth.OAuthRequest;
	import org.iotashan.oauth.OAuthSignatureMethod_HMAC_SHA1;
	import org.iotashan.oauth.OAuthToken;
	import org.iotashan.utils.OAuthUtil;
	import org.iotashan.utils.URLEncoding;

	import qnx.ui.buttons.LabelButton;
	import qnx.ui.core.Container;
	import qnx.ui.core.ContainerAlign;
	import qnx.ui.core.ContainerFlow;
	import qnx.ui.core.Containment;
	import qnx.ui.core.SizeMode;
	import qnx.ui.core.SizeUnit;
	import qnx.ui.core.Spacer;
	import qnx.ui.data.DataProvider;
	import qnx.ui.listClasses.AlternatingCellRenderer;
	import qnx.ui.listClasses.List;
	import qnx.ui.text.Label;
	import qnx.ui.text.TextInput;

	public class PlayBookOauthDemo extends Sprite
		// Static variables for OAuth
		private static var CONSUMER_SECRET:String = "<YOUR CONSUMER SECRET>";
		private static var CONSUMER_KEY:String = "<YOUR CONSUMER KEY>";
		private static var REQUEST_TOKEN_URL:String = "https://api.twitter.com/oauth/request_token";
		private static var ACCESS_TOKEN_URL:String = "https://api.twitter.com/oauth/access_token";
		private static var AUTHORIZE_URL:String = "https://api.twitter.com/oauth/authorize";
		private static var API_URL:String = "https://api.twitter.com";
		private static var SIGNATURE:OAuthSignatureMethod_HMAC_SHA1 = new OAuthSignatureMethod_HMAC_SHA1();

		// Consumers and Request objects for making calls
		private var _consumer:OAuthConsumer;
		private var _authRequest:OAuthRequest;
		private var _accessRequest:OAuthRequest;

		// Tokens for passing information back and forth
		private var _requestToken:OAuthToken;
		private var _accessToken:OAuthToken;

		// Containers to hold the UI objects
		private var _loginContainer:Container;
		private var _authContainer:Container;
		private var _verifyContainer:Container;
		private var _mainContainer:Container;
		private var _spacer:Spacer = new Spacer(50);

		// PIN and Twitter text fields
		private var text:TextField;
		private var twitterTextField:TextField;

		public function PlayBookOauthDemo()

			// support autoOrients
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;


		protected function init():void
			// creating the consumer and the authRequest based on the info from Twitter
			_consumer = new OAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
			_authRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_GET,REQUEST_TOKEN_URL,null,_consumer);

			_loginContainer = new Container();
			_loginContainer.align = ContainerAlign.MID;

			var button:LabelButton = new LabelButton();
				button.label = "Login to Twitter";



		protected function onClick(event:MouseEvent):void
			// uses the buildRequest method of our authRequest to format it correctly
			var urlRequest:URLRequest = new URLRequest(_authRequest.buildRequest(SIGNATURE));
			var loader:URLLoader = new URLLoader(urlRequest);

		protected function onRequestComplete(event:Event):void
			// build our requestToken based on the response from Twitter
			_requestToken = OAuthUtil.getTokenFromResponse(event.currentTarget.data);

			_authContainer = new Container();
			_authContainer.align = ContainerAlign.MID;

			var authBtn:LabelButton = new LabelButton();
				authBtn.label = "Authorize this application";



		protected function onAuthClick(event:MouseEvent):void
			_verifyContainer = new Container();
			_verifyContainer.align = ContainerAlign.MID;

			var label:Label = new Label();
				label.text = "Enter the PIN from Twitter.com";

			var font:TextFormat = new TextFormat();
				font.align = TextFormatAlign.CENTER;
				font.bold = true;
				font.size = 24;

			text = new TextField();
			text.type = TextFieldType.INPUT;
			text.border = true;
			text.width = 250;
			text.height = 30;
			text.defaultTextFormat = font;

			var getDataBtn:LabelButton = new LabelButton();
				getDataBtn.label = "Get Tweets";



			// Use the key from the requestToken and send the user to Twitter
			// to Authorize our application
			var authRequest:URLRequest = new URLRequest('http://api.twitter.com/oauth/authorize?oauth_token='+_requestToken.key);

		protected function onGetDataClick(event:MouseEvent):void
			// The oauth_verifier is the PIN number the user entered
			var params:Object = new Object();
				params.oauth_verifier = text.text;

			// Create the access request
			_accessRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_GET,ACCESS_TOKEN_URL,params,_consumer,_requestToken);

			var accessUrlRequest:URLRequest = new URLRequest(_accessRequest.buildRequest(SIGNATURE));
			var accessLoader:URLLoader = new URLLoader(accessUrlRequest);

		protected function onAccessRequestComplete(event:Event):void
			_accessToken = OAuthUtil.getTokenFromResponse(event.currentTarget.data);

			var mainRequest:OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_GET,API_URL+'/1/statuses/friends_timeline.xml',null,_consumer,_accessToken);

			var getStatusURLRequest:URLRequest = new URLRequest(mainRequest.buildRequest(SIGNATURE));
			var getStatusLoader:URLLoader = new URLLoader(getStatusURLRequest);

		protected function onStatusLoadComplete(event:Event):void
			_mainContainer = new Container();
			_mainContainer.flow = ContainerFlow.HORIZONTAL;

			var sendTweetContainer:Container = new Container(25);
				sendTweetContainer.containment = Containment.DOCK_TOP;

			var font:TextFormat = new TextFormat();
				font.align = TextFormatAlign.CENTER;
				font.bold = true;
				font.size = 24;

			twitterTextField = new TextField();
			twitterTextField.type = TextFieldType.INPUT;
			twitterTextField.border = true;
			twitterTextField.width = 500;
			twitterTextField.height = 30;
			twitterTextField.defaultTextFormat = font;

			var tweetLabel:LabelButton = new LabelButton();
				tweetLabel.label = "Tweet This";


			// Code for parsing the XML from the response
			var xml:XML = new XML(event.currentTarget.data);
			var statusList:XMLList = xml.children();
			var arr:Array = new Array();

			for(var i:int=0;i<statusList.length();i++)
				var obj:Object = new Object();
					obj.label = statusList[i].user.name.toString() +': ' + statusList[i].text.toString();

			// Create the DataProvider out of the parsed data
			var dataProvider:DataProvider = new DataProvider(arr);
			var list:List = new List();
				list.dataProvider = dataProvider;
				list.size = 100;
				list.sizeUnit = SizeUnit.PERCENT;


		protected function onTweetClick(event:MouseEvent):void
			var params:Object = new Object();
				params.status = twitterTextField.text;

			// Use the same consuemr and accessToken to update the Status
			var tweetRequest:OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_POST,API_URL+'/1/statuses/update.json',params,_consumer,_accessToken);

			var setStatusURLRequest:URLRequest = new URLRequest(tweetRequest.buildRequest(SIGNATURE));
				setStatusURLRequest.method = URLRequestMethod.POST;

				// use the replace function to strip out the status
				setStatusURLRequest.url = setStatusURLRequest.url.replace("&status=" + URLEncoding.encode(params.status),"");

			// Add the status as a URLVariable since it's a POST operation
			setStatusURLRequest.data = new URLVariables( "status=" + twitterTextField.text  );

			var setStatusLoader:URLLoader = new URLLoader(setStatusURLRequest);

		protected function onSetStatusComplete(event:Event):void
			// Show 'Status Updated' in the text field
			twitterTextField.text = "Status Updated";


Code to post status update in twitter from Flash using Oauth. View code on snipplr.com


Hope the above AS3 and twitter interaction code snippets will help in gr8 time.


We don't share your email anywhere, grab our rss via feedburner

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.