<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Konstantin Kovshenin &#187; twitterapi</title>
	<atom:link href="http://kovshenin.com/tag/twitterapi/feed/" rel="self" type="application/rss+xml" />
	<link>http://kovshenin.com</link>
	<description>WordPress, Automattic and Open Source</description>
	<lastBuildDate>Mon, 21 May 2012 15:59:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Tweet Button Showing Zero Count</title>
		<link>http://kovshenin.com/2010/tweet-button-still-showing-zero/</link>
		<comments>http://kovshenin.com/2010/tweet-button-still-showing-zero/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 12:33:15 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[twitter]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=2711</guid>
		<description><![CDATA[I came across this issue a few days ago and started looking for solutions. Didn&#8217;t find too many decent ones, which is why I&#8217;m writing this post. I&#8217;ve implemented Twitter&#8217;s Tweet Button on Foller.me last week and noticed that it always shows 0 count, despiting the fact that the page has been tweeted 3-4 times. [...]]]></description>
			<content:encoded><![CDATA[<p>I came across this issue a few days ago and started looking for solutions. Didn&#8217;t find too many decent ones, which is why I&#8217;m writing this post.</p>
<p>I&#8217;ve implemented Twitter&#8217;s <a href="http://twitter.com/about/resources/tweetbutton">Tweet Button</a> on <a href="http://www.foller.me">Foller.me</a> last week and noticed that it always shows 0 count, despiting the fact that the page has been tweeted 3-4 times. My friends suggested to wait a while, but that didn&#8217;t help either. Count was still showing zero after 3 days, so I decided to inspect of what&#8217;s going on.</p>
<p>It turns out that Twitter has it&#8217;s own monster crawler called <strong>Twitterbot</strong> who sends HTTP HEAD requests to pages that have been tweeted. This flooded my error log with code 405 responses: Method not allowed. I thought that this is the part that was causing the 0 count and I was right. I solved it with only a couple of lines in my Python code, inside the WSGI handler (note that I&#8217;m running Google App Engine):</p>
<pre>def head(self, screen_name):
    return</pre>
<p>That was quite easy ;) Too bad the Twitter developers docs don&#8217;t mention this at all, and a Google search for Twitterbot shows you how to create your own Twitter robot ;) Thanks for sharing this, cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2010/tweet-button-still-showing-zero/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Twitter Followers Count Snippet for WordPress</title>
		<link>http://kovshenin.com/2010/twitter-followers-count-snippet-for-wordpress/</link>
		<comments>http://kovshenin.com/2010/twitter-followers-count-snippet-for-wordpress/#comments</comments>
		<pubDate>Wed, 12 May 2010 10:38:47 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[twitter]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=2253</guid>
		<description><![CDATA[Here&#8217;s a short snippet to grab and display your twitter followers count in WordPress. You can use this anywhere, sidebar, posts, header, footer. We&#8217;ll be firing an anonymous call to the Twitter API for a user profile. This method does not require authentication, unless you&#8217;re trying to view a protected profile. To make this slightly [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a short snippet to grab and display your twitter followers count in WordPress. You can use this anywhere, sidebar, posts, header, footer. We&#8217;ll be firing an anonymous call to the Twitter API for a user profile. This method does not require authentication, unless you&#8217;re trying to view a protected profile. To make this slightly easier I&#8217;ve used the JSON functions which are available in PHP 5, but you can easily get them to work in PHP 4 (and as Alex mentioned in the comments below, WordPress comes with it&#8217;s own JSON functions for PHP 4 users, which is awesome).</p>
<p>I&#8217;ve modified the snippet a little bit due to comments below, and thank you again Alex (@Viper007Bond) for clarifying things with the <a href="http://codex.wordpress.org/HTTP_API">WordPress HTTP API</a> and those very useful <a href="http://codex.wordpress.org/Transients_API">Transients</a>. I actually grabbed some ideas from Alex&#8217;s own version of the <a href="http://www.viper007bond.com/2010/05/15/twitter-followers-count-snippet-for-wordpress/">Twitter Followers Count for WordPress</a> snippet and added a fail-safe route (for times when the Twitter API is down).</p>
<p>Anyways, the snippet now consists of a single function, which checks for a transient (for caching purposes), then fires a query to the Twitter API, and in case of an error return a stored followers count value from the past. In case the Twitter API responded fine, we set a new transient and store the value as the last successful. Here&#8217;s the new snippet:</p>
<pre>// Use this function to retrieve the followers count
function my_followers_count($screen_name = 'kovshenin')
{
	$key = 'my_followers_count_' . $screen_name;

	// Let's see if we have a cached version
	$followers_count = get_transient($key);
	if ($followers_count !== false)
		return $followers_count;
	else
	{
		// If there's no cached version we ask Twitter
		$response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
		if (is_wp_error($response))
		{
			// In case Twitter is down we return the last successful count
			return get_option($key);
		}
		else
		{
			// If everything's okay, parse the body and json_decode it
			$json = json_decode(wp_remote_retrieve_body($response));
			$count = $json-&gt;followers_count;

			// Store the result in a transient, expires after 1 day
			// Also store it as the last successful using update_option
			set_transient($key, $count, 60*60*24);
			update_option($key, $count);
			return $count;
		}
	}
}

echo "I have " . my_followers_count('kovshenin') . " followers";
</pre>
<p>Yup, quite simple isn&#8217;t it? Now call my_followers_count whenever you need to retrieve your followers count ;) Hope this will be of use to someone ;) Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2010/twitter-followers-count-snippet-for-wordpress/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>The Twitter API v2 Transition</title>
		<link>http://kovshenin.com/2009/the-twitter-api-v2-transition/</link>
		<comments>http://kovshenin.com/2009/the-twitter-api-v2-transition/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 13:38:26 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[twitter]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1700</guid>
		<description><![CDATA[It&#8217;s a mess around the current working copy of the Twitter API, there are more issues than functionality and the whole naming and renaming is a total disaster. Today for instance I tried a simple search query to the API and kept receiving &#8220;400 Bad Request&#8221; errors without any further explenation. As soon as I [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s a mess around the current working copy of the Twitter API, there are more issues than functionality and the whole naming and renaming is a total disaster. Today for instance I tried a simple search query to the API and kept receiving &#8220;400 Bad Request&#8221; errors without any further explenation. As soon as I changed the address from search.twitter.com to api.twitter.com/1 (I got this from Abraham Williams&#8217; php code), which is not clearly mentioned anywhere in the <a href="http://apiwiki.twitter.com/">Twitter docs</a>, everything started working fine.</p>
<p>But then I realised that the from_user_id field that&#8217;s being returned is far from the correct user ID. People in the <a href="http://groups.google.com/group/twitter-development-talk?pli=1">Twitter Development Talk</a> Google group stated this problem a few times (since March 2009 I believe). It seems that the &#8220;wrong&#8221; user IDs are meant for the second version of the Twitter API, thus cannot be used before it&#8217;s released. But wait! What the hack should I do with my app now? It&#8217;s not working y&#8217;know! Here you go:</p>
<pre>$response = $oauth-&gt;get('search', array('q' =&gt; $search_query));
foreach($response-&gt;results as $result)
{
$id = $result-&gt;id;
$text = $result-&gt;text;
$user_name = $result-&gt;from_user;

$user = $oauth-&gt;get("users/show", array("screen_name" =&gt; $user_name));
$user_id = $user-&gt;id; // Get the old-style user ID
}
</pre>
<p>Yeah, that&#8217;s one extra API call, but it solves things temporarily ;)</p>
<p>I guess there&#8217;s nothing that we could really do right now, and it&#8217;s probably true that we&#8217;ll have to rewrite some parts of our code as soon as <a href="http://apiwiki.twitter.com/V2-Roadmap">Twitter API v2</a> is released, but then again, what about the apps which stopped development? Will they stop working? Tonnes of Twitter clients and web apps still use basic authentication. Twitter mentioned that everybody must use OAuth these days, and that basic auth will be closed sooner or later.</p>
<p>Oh well, software comes, software goes. The best thing to do right now would be sign up to <a href="http://groups.google.com/group/twitter-api-announce">Twitter API Announce</a> Google group and follow <a href="http://twitter.com/twitterapi">@twitterapi</a>. By the way, <a href="http://twitter.com/web2feed">@web2feed</a> can now use the new features of the API to retweet messages based on hashtags and build user lists ;)</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/the-twitter-api-v2-transition/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Twitter OAuth PHP Class Gets Even Better</title>
		<link>http://kovshenin.com/2009/the-twitter-oauth-php-class-gets-even-better/</link>
		<comments>http://kovshenin.com/2009/the-twitter-oauth-php-class-gets-even-better/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 11:55:54 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[robotics]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1688</guid>
		<description><![CDATA[Or perhaps simpler?.. Together with the Twitter API itself, the TwitterOAuth PHP class (the one by Abraham Williams) is being updated too! According to GitHub the latest changeset was commited on December 3rd so yeah, I tried to take a look at what&#8217;s going on there a few days ago and was quite disapointed. Disappointed [...]]]></description>
			<content:encoded><![CDATA[<p>Or perhaps simpler?.. Together with the Twitter API itself, the <a href="http://github.com/abraham/twitteroauth">TwitterOAuth PHP class</a> (the one by Abraham Williams) is being updated too! According to GitHub the latest changeset was commited on December 3rd so yeah, I tried to take a look at what&#8217;s going on there a few days ago and was quite disapointed. Disappointed with the fact that all my previous code was broken without giving any reason.</p>
<p>Just like everybody else, I never read the readme or other documentation files so I dug straight into the class code and examples. Soon after I realized that the new changes were not that bad, so instead of the usual 5 lines of code, I shortened it up to only one. I stopped worrying about parsing XML or JSON, converting them to objects, and I stopped typing in the full address for Twitter API calls. Abraham did all that for us, so all we have left is:</p>
<pre>$credentials = $oauth-&gt;get("account/verify_credentials");
if ($oauth-&gt;http_code == 200)
echo "Hey there, {$credentials-&gt;screen_name}!";
</pre>
<p>I&#8217;m not going to publish all the new features and stuff (read about them at GitHub), but hey, this is quite sweet isn&#8217;t it? The only drawback was having to rewrite some parts of the code I wrote for the past few months (the Twitter Robots stuff), but I guess that&#8217;s partly my bad as it&#8217;s not as organized as it should be. That&#8217;s the main reason why I&#8217;m not publishing the whole code here yet, have a lot of cleaning up to do ;)</p>
<p>Meanwhile you may take a look at this buddy: <a href="http://twitter.com/web2feed">@web2feed</a>. I turned off the auto-replies because they were getting quite annoying, and I&#8217;ve added a couple of feeds to the big list, oh and it&#8217;s DM controlled too!</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/the-twitter-oauth-php-class-gets-even-better/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Automated Twitter Bot in PHP: Remote Control</title>
		<link>http://kovshenin.com/2009/automated-twitter-bot-in-php-remote-control/</link>
		<comments>http://kovshenin.com/2009/automated-twitter-bot-in-php-remote-control/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 10:21:14 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[robotics]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1423</guid>
		<description><![CDATA[Hope you&#8217;ve all read the first part of this series &#8211; Create Your Own Automated Twitter Robot in PHP and got your own prototype up and running. Today we&#8217;ll be adding a remote control feature to our robot. It&#8217;ll be working through direct messages and running in crontab every 5 minutes or so. You can [...]]]></description>
			<content:encoded><![CDATA[<p>Hope you&#8217;ve all read the first part of this series &#8211; <a href="http://kovshenin.com/2009/create-your-own-automated-twitter-robot-in-php/">Create Your Own Automated Twitter Robot in PHP</a> and got your own prototype up and running. Today we&#8217;ll be adding a remote control feature to our robot. It&#8217;ll be working through direct messages and running in crontab every 5 minutes or so. You can extend this as far as you want (adding retweet capabilities, follow/unfollow, direct messaging other people, etc) but we&#8217;ll stick to simple status updating in this post, might cover the others later on.</p>
<p>So, direct messaging the robot&#8217;s twitter account with the text &#8220;update status text&#8221; would make him tweet &#8220;status text&#8221; to the public timeline. Remember we had three branches of actions &#8211; feed, reply and rthx? Let&#8217;s add a fourth one and call it dm. This branch will simply scan through the account&#8217;s latest direct messages, find those sent by you and tweet them out loud. Again, as I said in the first tutorial, this is simply a prototype, just to get things up and running. You&#8217;ll have to polish this off for actual use and yeah, storing the access keys, dm_since_id, etc on disk is not such a good idea, you should probably use the database. Here&#8217;s the code:</p>
<pre>// The id of the latest read direct message will be stored in
// a file called dm_since_id, just like mentions_since_id
// in the previous examples
$since_id = @file_get_contents("dm_since_id", true);
if ($since_id &gt; 0) { }
else { $since_id = 1; }

// Retrieve the direct messages into $dms and parse the xml string
$dms = $oauth-&gt;OAuthRequest("http://twitter.com/direct_messages.xml" ,
	array("count" =&gt; 10, "since_id" =&gt;  $since_id), "GET");
$dms = simplexml_load_string($dms);

// If it's valid read the latest id and store into dm_since_id
if (count($dms))
{
	$last_id = ($dms-&gt;direct_message[0]-&gt;id &gt; $since_id) ?
		$dms-&gt;direct_message[0]-&gt;id : $since_id;
	file_put_contents("dm_since_id", (string)$last_id, FILE_USE_INCLUDE_PATH);
}

// Loop through the messages
foreach ($dms-&gt;direct_message as $dm)
{
	// Make sure you're the sender
	$sender = $dm-&gt;sender-&gt;screen_name;
	if ($sender == "kovshenin")
	{
		// What should we do
		if (strtolower(substr($dm-&gt;text, 0, 7)) == "update ")
		{
			// Construct the message, tweet and wait a few seconds
			$message = substr($dm-&gt;text, 7);
			$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
				array('status' =&gt; $message), 'POST');
			echo "Tweeting: " . $message;
			sleep(rand(5,30));
		}

		// Add more actions here
	}
}
</pre>
<p>Read through the comments in the code and you should be able to get the idea. The direct messages Twitter API method is documented <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct_messages">here</a>. Test it out a few times through your SSH client by sending a direct message to your robot with the text &#8220;update Updating my status&#8221; or whatever, then run:</p>
<pre># php robot.php dm
Tweeting: Updating my status
</pre>
<p>If everything works fine you might as well add the action to your cron, say 5 minutes:</p>
<pre>*/5 * * * * php /home/youruser/twibots/robot.php dm
</pre>
<p>And done! Your robot is now remote controlled. A few suggestions to more advanced remote controlled operations would be:</p>
<ul>
<li>Retweet capabilities by regular expression</li>
<li>Adding and removing feed sources, prefixes and postfixes</li>
<li>Turning on and off other operations (feeding, replying, rthxing)</li>
<li>Adding people to &#8220;reply ignore lists&#8221; (ones that talk to your robot too much)</li>
<li>Adding people to &#8220;rthx ignore lists&#8221; (ones that retweet too much, twitterfeed for instance)</li>
</ul>
<p>I think that&#8217;s enough for a start, oh and please don&#8217;t build dumb and annoying spammish robots. Stick to intelligent, smart <a href="http://twibots.com">twibots</a>! ;)</p>
<p>Upd. Continued: <a href="http://kovshenin.com/2010/twitter-robot-in-php-twibots-draft/">Twitter Robot in PHP: Twibots Draft</a></p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/automated-twitter-bot-in-php-remote-control/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Create Your Own Automated Twitter Robot in PHP</title>
		<link>http://kovshenin.com/2009/create-your-own-automated-twitter-robot-in-php/</link>
		<comments>http://kovshenin.com/2009/create-your-own-automated-twitter-robot-in-php/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 16:39:42 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[robotics]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1376</guid>
		<description><![CDATA[The ultimate guide to creating your own personalized twitterfeed clone! Kidding&#8230; Actualy this is just a mockup, a simple prototype, which is way too fresh for any actual use. We&#8217;ll take this forward step by step. I&#8217;m not going to give out all my sources but I&#8217;ll guide you through authentication, rss lookup, parsing, thanking [...]]]></description>
			<content:encoded><![CDATA[<p>The ultimate guide to creating your own personalized twitterfeed clone! Kidding&#8230; Actualy this is just a mockup, a simple prototype, which is way too fresh for any actual use. We&#8217;ll take this forward step by step. I&#8217;m not going to give out all my sources but I&#8217;ll guide you through authentication, rss lookup, parsing, thanking for retweets, and shooting random stuff at people that mention your robot.</p>
<p>Here&#8217;s a brief list of features we will implement:</p>
<ul>
<li>Runs in console, no HTTP access</li>
<li>Authentication via OAuth, tweeting via OAuth</li>
<li>RSS lookup, parsing, forming tweets in bound of 140 characters including a postfix (hashtag or RT)</li>
<li>Tweeting &#8216;thank you for retweeting&#8217; to users that retweet the robot</li>
<li>Following people that retweet the robot</li>
<li>Acting strange on users that mention the robot</li>
</ul>
<p>All this is going to be setup on a linux box running crond and acting every 15 minutes or so. Are you ready? Let&#8217;s do it!</p>
<p><span id="more-1376"></span></p>
<h2>Registering an App at Twitter OAuth Clients</h2>
<p>This is mandatory if we&#8217;re using OAuth (don&#8217;t go with basic authentication because Twitter will be closing that down sooner or later, plus we&#8217;re making a personalized robot, so the &#8216;from&#8217; string in the tweets is a must). Browse to the <a href="http://twitter.com/oauth_clients">Twitter OAuth Clients</a> page (assuming you&#8217;re logged into Twitter) and register a new application. Make sure you pick <strong>Read and Write access</strong> as our robot will use POST calls to update its status. Also note that we&#8217;re preventing all HTTP access to the robot control, thus we&#8217;ll be using PIN based OAuth, so make sure you pick <strong>Client application</strong> and not web.</p>
<p>Now, don&#8217;t lose your <strong>Consumer key</strong> and <strong>Consumer secret</strong> &#8211; we&#8217;ll be using those in our app for identity. Don&#8217;t give them out to anybody you don&#8217;t trust unless you&#8217;d like people tweeting &#8220;from YourApp&#8221;. Note that you can ask Twitter to reset the values for you in case somebody got unwanted access to them. The request and access URLs are not important, they&#8217;re the same for everyone.</p>
<h2>Setting up the Environment</h2>
<p>What environment? Umm, we&#8217;ll be using <a href="http://magpierss.sourceforge.net/">Magpie RSS</a> to parse RSS feeds, <a href="http://ru2.php.net/curl">Curl</a> to access the Twitter API and the <a href="http://github.com/abraham/twitteroauth">Twitter OAuth Class</a> by Abraham Williams (we used this a bunch of times in my earlier postings) which is dependent on the Curl functions. Make sure you install everything right &#8211; the magpie functions work, curl functions are available and the Twitter OAuth class is defined.</p>
<p>What you also need is a bit.ly login and API key, go get yours <a href="http://bit.ly/account/register">somewhere here</a>. Feel free to use a different URL shortener if you feel like, but we&#8217;ll stick to bit.ly.</p>
<h2>Authentication: Storing the Access Tokens</h2>
<p>We&#8217;ll divide our application in two parts, one will be running every 15 minutes, the second one will run once for authentication. Create a new PHP file, call it oauth.php or whatever and also make sure you got your consumer key and secret next to you and visible by oauth.php. It&#8217;s up to you where to keep them, I like storing them in a config.php which I include/require in auth.php and robot.php.</p>
<p><img src="http://kovshenin.com/files/2009/10/twitter_robot_chart.png" alt="twitter_robot_chart" width="680" height="500" class="aligncenter size-full wp-image-1399" /></p>
<p>If you haven&#8217;t read my previous articles about <a href="http://kovshenin.com/2009/automatic-tweet-oauth/">Automated Serverside Tweeting Using OAuth</a> and <a href="http://kovshenin.com/2009/twitter-api-pin-based-oauth-php/">PIN-based OAuth Using PHP</a> then make sure you do, because I wouldn&#8217;t like to go through the same code again. What&#8217;s important here is that oauth.php will run on its own and will accept parameters via command line. Like this:</p>
<pre># php oauth.php register
Request tokens aquired, proceed to this link: https://twitter.com/oauth/authorize?oauth_token=whatever

# php oauth.php validate 123456
Access tokens stored, identified as @twittername
</pre>
<p>So after you&#8217;ve validated your OAuth session, access tokens are stored somewhere on disk, I just call my files access_token and access_token_secret. If the files are present, then your robot will be able to tweet, otherwise ask for registration. I hope everything&#8217;s clear enough here. The main point of this file is to get your access tokens written to disk.</p>
<h2>Feeding Twitter from RSS</h2>
<p>We need to distinguish different actions which the robot is supposed to do, through an action parameter passed by the command line. I leave it up to you, but make sure your control flows similar to this:</p>
<pre>$action = $argv[1];
if ($action == "feed")
{
	$feed_name = $argv[2];
	// Read the feeds, tweet the feeds
}
elseif ($action == "rthx")
{
	// Read the names, tweet the names!
}
elseif ($action == "reply")
{
	// Read the names, umm.. Say something!
}
</pre>
<p>So the robot control will look something like this:</p>
<pre># php robot.php feed wordpress
Feeding my public timeline with wordpress articles
# php robot.php rthx
Thanking peeps for the retweets and following them all
# php robot.php reply
Writing strange stuff to peeps that mentioned me
</pre>
<p>Good, now let&#8217;s assume we&#8217;re in the feed action. Define an associative array of feeds:</p>
<pre>$feeds = array(
	"wordpress" =&gt; array("url" =&gt; "http://wordpress.org/development/feed/",
		"postfix" =&gt; "#wordpress"),
	"mashable" =&gt; array("url" =&gt; "http://feeds2.feedburner.com/Mashable",
		"postfix" =&gt; "via (@mashable)"),
);
</pre>
<p>Two is enough for starting. We&#8217;ll make our robot tweet #wordpress tweets and read out mashable&#8217;s website and tweet headlines via @mashable. Make sure that you&#8217;ve already written a check for access_token and access_token_secret and gave out an error message if they didn&#8217;t exist or were expired. We cannot tweet without those, remember? I&#8217;m assuming you&#8217;ve stored them into $access_token and $access_token_secret respectively and initialized the $oauth object:</p>
<pre>$oauth = new TwitterOAuth($oauth_consumer_key, $oauth_consumer_secret,
	$access_token, $access_token_secret);
</pre>
<p>The second parameter (&#8220;wordpress&#8221; in the control above example) would be stored into a $feed_name variable. From there on we&#8217;ll go with code:</p>
<pre>// Store the feed settings into $feed
$feed = $feeds[$feed_name];

// Fetch the feed and store the prefix
$rss = fetch_rss($feed["url"]);
$postfix = $feed["postfix"];

// Loop through the feed items
foreach ($rss-&gt;items as $item)
{
	// All simple enough here
	$title = trim($item["title"]);
	$url = $item["link"];

	// Let's make sure our feeds are in English, allow spaces and punctuation
	if (ereg('^[[:alnum:][:blank:][:punct:]]+$', $title))
	{
		// Escape the URL for bit.ly shortening and then shorten the link
		// This is the place where you have to use your bit.ly login
		// And the API key
		$url_escaped = urlencode($url);
		$bitly_url = "http://api.bit.ly/shorten?version=2.0.1";
		$bitly_url .= "&amp;longUrl=$url_escaped";
		$bitly_url .= "&amp;login=$bitly_login&amp;apiKey=$bitly_key";

		$shortened_url = json_decode(file_get_contents($bitly_url));

		// If everything went okay, go on
		if ($shortened_url-&gt;errorCode == 0)
		{
			// Retrieve the shortened url from the json object
			foreach ($shortened_url-&gt;results as $key =&gt; $value)
				$shorturl = $value-&gt;shortUrl;

			// Form a new message from the short URL and the postfix
			$message = " $shorturl $postfix";
			$length = strlen($message);

			// We should trim down the title if it's too long
			// So that our tweets are 120 characters or less
			if (strlen($title) &gt; 120-$length)
				$shorttitle = substr($title, 0, 117-$length) . "...";
			else
				$shorttitle = $title;

			// Add the title to the message
			$message = $shorttitle.$message;

			// Post the message to Twitter
			$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
				array('status' =&gt; $message), 'POST');

			// Wait a couple of mintes before the next tweet
			// Don't try and flood Twitter, remember, you have
			// Only 150 API calls per hour, use them wisely.
			sleep(rand(60,120));
		}
	}
}
</pre>
<p>Read carefully through the comments, you should be able to understand what we&#8217;re doing here. This is the RSS part, (almost) all clean and shiny. Proceed to the retweets part.</p>
<h2>Automatically Thank Your Retweeters and&#8230; Follow them!</h2>
<p>Be very very careful here as we don&#8217;t want to thank the retweeters too much. You&#8217;ll need to think of a mechanism to store the id of the latest retweet that you already thanked and use it in the since_id parameter when calling the Twitter API. I&#8217;ll leave this part up to you, but in general the code should look something like this:</p>
<pre>// Read the since_id from a file
$since_id = @file_get_contents("retweets_since_id");
if ($since_id &gt; 0) { }
else { $since_id = 1; }

// Send the Twitter API request for the latest 50 mentions
// That were posted after the since_id parameter we read earlier
$mentions = $oauth-&gt;OAuthRequest("http://twitter.com/statuses/mentions.xml" ,
	array("count" =&gt; 50, "since_id" =&gt;  $since_id), "GET");

// Make the XML an object
$mentions = simplexml_load_string($mentions);

// Setup an array which will contain users to retweet and follow
$users_to_rthx = array();

// Read the last tweet's id and store it into the retweets_since_id file
$last_id = ($mentions-&gt;status[0]-&gt;id &gt; $since_id) ? $mentions-&gt;status[0]-&gt;id : $since_id;
file_put_contents("retweets_since_id", (string)$last_id);

// Loop through the tweets
foreach ($mentions-&gt;status as $status)
{
	// Let's see if somebody retweeted you.
	// Err, remember to replace @yourname
	if (strpos(strtolower($status-&gt;text), "rt @yourname")
		|| strpos(strtolower($status-&gt;text), "via @yourname"))
	{
		// Add the guy to the retweeters array
		$users_to_rthx[] = $status-&gt;user-&gt;screen_name;
	}
}

// Remove duplicates (we don't thank somebody twice in a tweet)
$users_to_rthx = array_unique($users_to_rthx);

// Setup the tweet prefix and initialize the mentions variable
// The tweet_prefix is just in case ;)
$tweet_prefix = "Thanks for the retweets! ";
$tweet_mentions = "";
$tweet_prefix = "";

// Loop through the retweeters popping variables out of the array
while ($mention_this_guy = array_pop($users_to_rthx))
{
	// If the popped guy fits into our brand new tweet, add him
	if (strlen($tweet_prefix . $tweet_mentions .
		$tweet_postfix . "@".$mention_this_guy) &lt; 140)
	{
		$tweet_mentions .= "@".$mention_this_guy . " ";

		// Send the friendhips create (follow) request to the API
		echo "Following: " . $mention_this_guy;
		$oauth-&gt;oAuthRequest("https://twitter.com/friendships/create/" .
			$mention_this_guy . ".xml",	array(), "POST");
	}
	// If he doesn't push him back into the variable, tweet and reset
	// The $tweet_mentions variable for the other retweeters
	else
	{
		array_push($users_to_rthx, $mention_this_guy);

		// Format the message and output to screen (for debugging)
		$message = $tweet_prefix . trim($tweet_mentions) . $tweet_postfix;
		echo "Tweeting: " . $message . " (" . strlen($message) . ") n";

		// Send the status update request to the Twitter API
		$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
			array('status' =&gt; $message), 'POST');

		// Wait a few seconds before the next round
		sleep(rand(5,30));

		// Reset
		$tweet_mentions = "";
	}
}

// If we've got something left in the mentions, we need to tweet that
if (strlen($tweet_mentions) &gt; 0)
{
	$message = $tweet_prefix . trim($tweet_mentions) . $tweet_postfix;
	echo "Tweeting: " . $message . " (" . strlen($message) . ") n";

	$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
		array('status' =&gt; $message), 'POST');
	sleep(rand(5,30));

	$tweet_mentions = "";
}
</pre>
<p>The comments explain it all.</p>
<h2>Did Somebody Say Anything? Random Replies</h2>
<p>This is the fun part. Whenever somebody mentions your name (and it is not a retweet), we send them a strange message mentioning their name. The code looks exactly like the retweeters thank code above, except that we don&#8217;t search for &#8220;rt @yourname&#8221; and &#8220;via @yourname&#8221;, instead we work with ones that don&#8217;t contain &#8220;rt&#8221; and &#8220;via&#8221; at all.</p>
<p>Don&#8217;t forget to store the replies_since_id too as we don&#8217;t want to message users multiple times (infinite number of times actually) because they&#8217;ll block the frustrating robot. Here&#8217;s the while loop that actually tweets. In this part the names are stored in the $users_to_reply array and goes like this:</p>
<pre>// The loop
while ($mention_this_guy = array_pop($users_to_reply))
{
	// Some random quotes ;) You can add your own
	$random_quotes = array(
		"Wha?", "Interesting ...", "Affirmative sir!", "Hmm, makes me think ..",
		"So you really think I'm not human? Well.. Umm.. *sigh*"
	);

	// Format the message and tweet a random quote
	$message = "@".$mention_this_guy . " " .
		$random_quotes[array_rand($random_quotes)];

	echo "Tweeting: " . $message . " (" . strlen($message) . ") n";
	$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
		array('status' =&gt; $message), 'POST');

	// Wait a little
	sleep(rand(5,30));
}
</pre>
<p>That&#8217;s about it. The last part is adding the whole stuff to crontab for automated work. Open up /etc/crontab and add a few lines:</p>
<pre># Feed mashable and wordpress tweets once every 15-16 minutes
*/15 * * * * php /home/youruser/twibots/robot.php feed wordpress
*/16 * * * * php /home/youruser/twibots/robot.php feed mashable

# Thank and follow the retweeters once every half an hour
*/30 * * * * php /home/youruser/twibots/robot.php rthx

# Reply to people hourly
01 * * * * php /home/youruser/twibots/robot.php reply
</pre>
<p>Restart your cron daemon and voila! I&#8217;m used to having full control over my virtual private server so if you use simple shared hosting you should access the crontab (also called cron jobs) via your CPanel. Don&#8217;t forget to actually write the php command because .php files aren&#8217;t actually executable by linux. Also note that my files are stored in a non-accessible by apache part of the hard drive, so omit putting them into public_html, www or whatever. If you do though, make sure you define a &#8220;deny from all&#8221; rule in .htaccess. We don&#8217;t want other people messing with our newly born robot. Robots, robots, robots&#8230; What should we call them? <a href="http://twibots.com">Twibots</a>? ;)</p>
<p>Upd. Continued: <a href="http://kovshenin.com/2009/automated-twitter-bot-in-php-remote-control/">Automated Twitter Bot in PHP: Remote Control</a> and <a href="http://kovshenin.com/2010/twitter-robot-in-php-twibots-draft/">Twitter Robot in PHP: Twibots Draft</a></p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/create-your-own-automated-twitter-robot-in-php/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Twitter API: PIN-based OAuth Using PHP</title>
		<link>http://kovshenin.com/2009/twitter-api-pin-based-oauth-php/</link>
		<comments>http://kovshenin.com/2009/twitter-api-pin-based-oauth-php/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 08:11:15 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1353</guid>
		<description><![CDATA[A few weeks ago we discussed Automated Serverside Tweeting Using OAuth (read this before going on) and I kept looking deeper into security issues, so I found a way to make things slightly simpler. If you played with the OAuth Clients page on Twitter, you know that there are two ways of authentication &#8211; web [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago we discussed <a href="http://kovshenin.com/2009/automatic-tweet-oauth/">Automated Serverside Tweeting Using OAuth</a> (read this before going on) and I kept looking deeper into security issues, so I found a way to make things slightly simpler. If you played with the <a href="http://twitter.com/oauth_clients">OAuth Clients</a> page on Twitter, you know that there are two ways of authentication &#8211; web application and client application. Also, I found out that there&#8217;s a redirect_to parameter in OAuth authentication, although we&#8217;re not going to use the original web redirects this time. If we&#8217;re talking about automatic server-side tweeting, then it should be serverside, right? So why not close down HTTP access at all?</p>
<p>The downside of all this is that you&#8217;re unable to have two applications (web and client) with the same name, thus you cannot create a web application and a client application that would return the same &#8220;from&#8221; string in tweets, so you should probably divide your app in two parts, say &#8220;AppName&#8221; (web application) and &#8220;AppName Server&#8221; (client application) and feel free to link them to the same URL.</p>
<p>Pin based Twitter OAuth works just like the original (web) OAuth (request tokens, access tokens) but instead of returning back to a web page, Twitter gives out a Pin code that you have to input into your app in order to exchange its request token with an access token. It&#8217;s fairly simple, but unfortunatelly Abraham Williams didn&#8217;t implement this part into his <a href="http://github.com/abraham/twitteroauth">Twitter OAuth php library</a>, but we&#8217;re still going to use it, with some slight modifications.</p>
<p>Assuming we&#8217;ve initiated an OAuth session and stored the request tokens, here&#8217;s the original piece of code that exchanges the request tokens with the access tokens (the ones that actually give you the right to call the Twitter API via OAuth):</p>
<pre>$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);

// Ask Twitter for an access token (and an access token secret)
$request = $oauth-&gt;getAccessToken();

$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
</pre>
<p>The getAccessToken function is the one that posts the request to exchange request tokens for access tokens. It&#8217;s the one we have to modify to implement the pin code solution, so open up twitterOAuth.php, find the function (it&#8217;s around line 100) and make it look like this:</p>
<pre>function getAccessToken($token = NULL, $pin = NULL)
{
	if ($pin)
		$r = $this-&gt;oAuthRequest($this-&gt;accessTokenURL(),
			array("oauth_verifier" =&gt; $pin));
	else
		$r = $this-&gt;oAuthRequest($this-&gt;accessTokenURL());

	$token = $this-&gt;oAuthParseResponse($r);
	$this-&gt;token = new OAuthConsumer($token['oauth_token'],
		$token['oauth_token_secret']);

	return $token;
}
</pre>
<p>What we did is add an extra parameter right after $token which is optional (not to break all the other code) &#8211; $pin. Now in terms of OAuth, the pin code is called the OAuth verifier (oauth_verifier), we add it as a parameter to the oAuthRequest call, which then wraps it up into a signed HTTP request to Twitter containing the verifier (line 114).</p>
<p>Back to our script. The rest is simple, just change the getAccessToken call to look like this:</p>
<pre>$request = $oauth-&gt;getAccessToken(NULL, $pin);
</pre>
<p>Where $pin would be the pin code provided by Twitter during OAuth. Now, move all your scripts into a secured place, preferably not accessible through HTTP, write a few modifications in order to pass parameters through command line (use $argv[n] instead of $_GET[...]). Here&#8217;s a tip on how it should look to get you on the right track. All the work is done through SSH:</p>
<pre># php oauth.php register
Request tokens aquired, proceed to this link: https://twitter.com/oauth/authorize?oauth_token=whatever

# php oauth.php validate 123456
Access tokens stored, identified as @twittername

# php oauth.php reset
Access tokens deleted
</pre>
<p>That&#8217;s the way my script works and voila! No more HTTP! Hmm.. <a href="http://twibots.com">TwiBots</a>? ;)</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/twitter-api-pin-based-oauth-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Automated Serverside Tweeting Using OAuth</title>
		<link>http://kovshenin.com/2009/automatic-tweet-oauth/</link>
		<comments>http://kovshenin.com/2009/automatic-tweet-oauth/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 08:41:51 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[foller.me]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1309</guid>
		<description><![CDATA[Great, our Foller.me Rundown account (@fmrd) now tweets via OAuth and has our application name and link attached to every tweet. It was indeed pretty simple. After reading the specs of the OAuth protocol I came up with a fairly simple solution. I&#8217;m using this open source Twitter OAuth php library by Abraham Williams which [...]]]></description>
			<content:encoded><![CDATA[<p>Great, our <a href="http://foller.me">Foller.me</a> Rundown account (<a href="http://twitter.com/fmrd">@fmrd</a>) now tweets via OAuth and has our application name and link attached to every tweet. It was indeed pretty simple. After reading the specs of the OAuth protocol I came up with a fairly simple solution. I&#8217;m using this open source <a href="http://github.com/abraham/twitteroauth">Twitter OAuth php library</a> by Abraham Williams which is quite good, and I do recommend you try some basic OAuth stuff (with sessions, based on Abraham&#8217;s example) before proceeding to automated tweeting.</p>
<p>Okay, let me first breifly explain how OAuth at Twitter is supposed to work (focusing on automated work). Step by step:</p>
<ol>
<li>You browse to some hidden area (which nobody but you has access to) and initiate the app registration process. At this point, your app should go ask Twitter for a request token and provide you with a link to Twitter authentication (which will contain the received token)</li>
<li>Next, you click on that link which directs you to Twitter, login, click allow and you&#8217;ll be redirected back to your application page (not the hidden area!) with the request token attached to the URL.</li>
<li>You copy that token, browse back to your hidden area and initiate the app validation process by providing the token in your request (GET)</li>
<li>Your app will go talk to Twitter again asking them for an access token. It stores that token (in a very safe place) for later use.</li>
</ol>
<p>That&#8217;s pretty much everything. Once you have your access token you can update your status via OAuth as much as you want. Also note that when I mention request token and access token, I mean request token secret and access token secret too. OAuth tokens come in pairs. Token + secret. Yes, it is that simple!</p>
<p>Now let&#8217;s get to some coding! Suppse your app is called MyApp and is located at myapp.com. Make sure your hidden area is actually hidden. Choose a nifty directory for your place and make sure you protected it with .htaccess (allow by IP or based on authentication, it&#8217;s up to you). Don&#8217;t worry, Twitter will not try to access that directory. Twitter (the OAuth Service Provider) doesn&#8217;t do anything but give responses to your requests, so block that as strong as possible.</p>
<p>Suppse your hidden server auth place is at myapp.com/hidden/ and there&#8217;s an index.php file, your requests would look like this:</p>
<pre>myapp.com/hidden/?register
</pre>
<p>That would mean &#8220;initiate the OAuth registration process!&#8221;, which will give you the URL to Twitter. And:</p>
<pre>myapp.com/hidden/?validate&amp;oauth_token=whatever
</pre>
<p>Which will get your Twitter OAuth access token and store it somewhere safe. Remember that you&#8217;ll have to replace the word &#8220;whatever&#8221; with the request token provided by Twitter after you authorize.</p>
<p>Let&#8217;s look at the php code (omitting the includes and blah blah blah). Just read through the comments, you should be able to understand. Also make sure you got your $consumer_key and $consumer_secret setup in the Twitter OAuth applications settings.</p>
<pre>if (isset($_GET["register"]))
{
    // If the "register" parameter is set we create a new TwitterOAuth object
    // and request a token
    $oauth = new TwitterOAuth($consumer_key, $consumer_secret);
    $request = $oauth-&gt;getRequestToken();

    $request_token = $request["oauth_token"];
    $request_token_secret = $request["oauth_token_secret"];

    // At this stage you should store the two request tokens somewhere.
    // Database or file, whatever. Just make sure it's safe and nobody can read it!
    // I'll dump mine into files using file_put_content:

    file_put_contents("request_token", $request_token);
    file_put_contents("request_token_secret", $request_token_secret);

    // Generate a request link and output it
    $request_link = $oauth-&gt;getAuthorizeURL($request);
    echo "Request here: &lt;a href="" . $request_link . ""&gt;" . $request_link . "&lt;/a&gt;";
    die();
}
elseif (isset($_GET["validate"]))
{
    // This is the validation part. At this point you should read the stored request
    // tokens. You'll need them to get your access tokens!
    // Mine are located in two files:

    $request_token = file_get_contents("request_token");
    $request_token_secret = file_get_contents("request_token_secret");

    // Initiate a new TwitterOAuth object. This time we provide them with more details:
    // The request token and the request token secret
    $oauth = new TwitterOAuth($consumer_key, $consumer_secret,
        $request_token, $request_token_secret);

    // Ask Twitter for an access token (and an access token secret)
    $request = $oauth-&gt;getAccessToken();

    // There we go
    $access_token = $request['oauth_token'];
    $access_token_secret = $request['oauth_token_secret'];

    // Now store the two tokens into another file (or database or whatever):
    file_put_contents("access_token", $access_token);
    file_put_contents("access_token_secret", $access_token_secret);

    // Great! Now we've got the access tokens stored.
    // Let's verify credentials and output the username.
    // Note that this time we're passing TwitterOAuth the access tokens.
    $oauth = new TwitterOAuth($consumer_key, $consumer_secret,
        $access_token, $access_token_secret);

    // Send an API request to verify credentials
    $credentials = $oauth-&gt;oAuthRequest(
        "https://twitter.com/account/verify_credentials.xml",
        array(), "GET"
    );

    // Parse the result (assuming you've got simplexml installed)
    $credentials = simplexml_load_string($credentials);

    // And finaly output some text
    echo "Access token saved! Authorized as @" . $credentials-&gt;screen_name;
    die();
}
</pre>
<p>That&#8217;s all. It wasn&#8217;t difficult, was it? Now that you&#8217;ve got your access tokens stored, you can call Twitter API using OAuth at any time! Here&#8217;s a brief example:</p>
<pre>// Read the access tokens
$access_token = file_get_contents("path/to/access_token");
$access_token_secret = file_get_contents("path/to/access_token_secret");

// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
    $access_token, $access_token_secret);

// Post an update to Twitter via your application:
$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
    array('status' =&gt; "Hey! I'm posting via #OAuth!"), 'POST');
</pre>
<p>Then setup a cron job to access that page URL and you&#8217;ll be automatically tweeting! That&#8217;s about it.</p>
<p>Now, in conclusion, a few security suggestions. Never, NEVER place your tokens into a publicly visible folder. Deny all HTTP access to them via .htaccess (look at the Files directive) and yes, I&#8217;m going to let you finish, but please, PLEASE secure that hidden place we talked about earlier. Yes I&#8217;m repeating this and I&#8217;ll keep repeating it over and over. If hackers gain access to your hidden place, they&#8217;ll be able to swap your account with another one (or just break it). If they get to your access tokens, then they might spam through your account. That&#8217;s not very nice, is it? So please, IP based security, password protected, whatever. I close the whole directory down with a &#8220;deny from all&#8221; rule in .htaccess once I got my access tokens, so if for any reason I&#8217;d have to update or change them, I&#8217;d have to do more than just browse there.</p>
<p>That&#8217;s all. Have a good time with Twitter OAuth and I hope everything goes well. Feel free to post questions or any kind of feedback in the comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/automatic-tweet-oauth/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Twitter API: Moving From Basic Auth to OAuth</title>
		<link>http://kovshenin.com/2009/twitter-api-basic-auth-to-oauth/</link>
		<comments>http://kovshenin.com/2009/twitter-api-basic-auth-to-oauth/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 17:38:31 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[twitter]]></category>
		<category><![CDATA[foller.me]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1274</guid>
		<description><![CDATA[As I mentioned earlier this week, with Foller.me beta 3, people now have the ability to follow tweeps directly from the website with a single click, without having to browse to their Twitter profile nor providing us with their Twitter credentials (thanks to OAuth. Read this post if you haven&#8217;t: The Importance of Using Twitter [...]]]></description>
			<content:encoded><![CDATA[<p>As I mentioned earlier this week, with <a href="http://foller.me">Foller.me</a> beta 3, people now have the ability to follow tweeps directly from the website with a single click, without having to browse to their Twitter profile nor providing us with their Twitter credentials (thanks to OAuth. Read this post if you haven&#8217;t: <a href="http://kovshenin.com/2009/twitter-oauth-api-important/">The Importance of Using Twitter API via OAuth</a>).</p>
<p>Now, why not take even more advantage of Twitter OAuth? As mentioned in the documentation and a few tweets by <a href="http://twitter.com/netik">@netik</a> (John Adams, Ops Engineer @ Twitter), due to the high growth of Twitter apps being developed every day, the source parameter in the statuses/update calls will no longer give you the desired result (attaching &#8220;via Your App Name&#8221; with a link to your website to the tweet). Calls with no source parameter come out as &#8220;via API&#8221;. Ones with unknown source parameters come out as &#8220;from web&#8221;. This doesn&#8217;t apply to already developped apps such as TweetDeck and Seesmic Desktop and they still use the source parameter via Basic Auth.</p>
<blockquote><p>
So how do I get my Twitter app name listed in the tweets?
</p></blockquote>
<p>And the answer is OAuth. Once you subscribe your app to the <a href="http://twitter.com/oauth_clients">Applications Using Twitter</a> page, those guys know about you. They know the name of your application and they know where to link if you post &#8220;via&#8221; your application. The key here is <strong>posting &#8220;via&#8221; your application</strong>. Well, the little &#8220;Tweet my profile&#8221; link at the bottom of a Foller.me profile (if you&#8217;re signed in) is fairly simple. We&#8217;ve got an authenticated (via OAuth) user and an OAuth request method:</p>
<pre>$oauth-&gt;OAuthRequest('https://twitter.com/statuses/update.xml',
    array('status' =&gt; 'Test OAuth update. #testoauth'), 'POST');
</pre>
<p>That will post from the authenticated user via your application. Sweet isn&#8217;t it? But, you probably know our <a href="http://blog.foller.me/extend/rundown/">Foller.me Rundown</a> feature, which tweets through the <a href="http://twitter.com/fmrd">@fmrd</a> account. It&#8217;s totally automated and uses Basic Auth to post. As I said above, Basic Auth will not give us the &#8220;from device&#8221; bit in your tweets, so we have to use OAuth. And this is actually what I am after.</p>
<p>There are a few request tokens and token secrets that travel between both servers (Twitter and the client) during OAuth authentication. In general OAuth usage, we store them into our user&#8217;s sessions on server. Now what if we store them into our database (or some other place) and when tweeting via @fmrd use THEM instead of starting a new Basic Auth session? This means that I somehow need to send myself (on a closed by .htaccess page or whatever) to the Twitter authentication page with a generated OAuth token, then, whenever Twitter redirects me back to my page, I need to copy the received &#8220;request token&#8221; and secret and write it down somewhere. I&#8217;ll have to dig deeper into OAuth for this, rather than just use a ready-to-go library that works with sessions. I&#8217;ll try this method out and write about it next week. It&#8217;d be cool if @fmrd could tweet &#8220;via Foller.me&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/twitter-api-basic-auth-to-oauth/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The Importance of Using Twitter API via OAuth</title>
		<link>http://kovshenin.com/2009/twitter-oauth-api-important/</link>
		<comments>http://kovshenin.com/2009/twitter-oauth-api-important/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 10:34:17 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[twitter]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[foller.me]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitterapi]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1255</guid>
		<description><![CDATA[I hope you noticed the latest changes at Foller.me. I&#8217;m talking about the new Followers rate section thanks to the TwitterCounter API and of course something I&#8217;ve been dreaming about since the launch of the project. You view a profile at Foller.me before making a decision about following that particular person or not, right? And [...]]]></description>
			<content:encoded><![CDATA[<p>I hope you noticed the latest changes at <a href="http://foller.me">Foller.me</a>. I&#8217;m talking about the new Followers rate section thanks to the <a href="http://twittercounter.com/pages/api">TwitterCounter API</a> and of course something I&#8217;ve been dreaming about since the launch of the project. You view a profile at Foller.me before making a decision about following that particular person or not, right? And yeah, we had a link at the bottom of the page that lead to their profile on Twitter, where you could click the follow button.</p>
<p>Now we&#8217;ve updated that section to a Twitter OAuth powered follow button. This means that once you authorize Foller.me to use your Twitter profile without having to even input your username or password, you can follow people directly from Foller.me, without having to do any extra clicks. Yeah, we&#8217;re ready to remove our beta label and as we promised we&#8217;re coming up with a few more features and optimizations.</p>
<p>Guess that&#8217;s enough for the news section. Now, back to the topic of this post. OAuth. Y&#8217;know at the very beginning I was thinking about giving people the chance to input their username and password on Foller.me, but hey, that&#8217;s dangerous, right? I still see tonnes of websites and Twitter services, which are super cool, and yes, they still use basic authentication instead of OAuth. Seriously, it took me less than two hours to incorporate OAuth into Foller.me and once somebody has authorized with you (on the server side) you&#8217;re able to do all the stuff with their account with no difference from baisc auth! No limitations at all! Please take a look at the <a href="http://apiwiki.twitter.com/OAuth-Examples">Twitter OAuth Examples</a> which include ready-to-use libraries (and classes) for the major programming languages including php, Python, Ruby, .NET and a bunch of others.</p>
<p>So, why bother switch to OAuth? Well, personally I hate websites and Twitter services that would ask me for my Twitter username and password, I start to think that they&#8217;re scam (don&#8217;t you?), even if they&#8217;re not. I repeat, I see tonnes of those, and I gave out my password only to a couple because I really, really wanted to see what&#8217;s inside. After that, I immediately picked a new password for my Twitter account. And yes, I really can&#8217;t wait till TweetDeck, Seesmic Desktop and the others implement OAuth into their apps. That would make them extra cool, seriously.</p>
<p>Here&#8217;s more! There&#8217;s also lots of discussion going on in the Twitter Development in Google Groups and I heard somebody mention that the source parameter for your apps will no longer be available sooner or later. Yep, they&#8217;re closing down the basic authentication method. I&#8217;m not sure when, and the Twitter API Wiki says that the date hasn&#8217;t been announced yet, but hey, you should do it now before it&#8217;s too late. OAuth applications won&#8217;t need any source parameter as Twitter already knows who they are after <a href="http://twitter.com/oauth">signing your app with them</a>.</p>
<p>So dear friends, please switch your apps to OAuth, it&#8217;s very, VERY important.</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/twitter-oauth-api-important/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

