A Twitter Memo: Auto Responding with PHP

By Andy Mornes | 03/09/2010 - 4:54pm

Twitter continues to becoming more and more popular these days, especially for businesses. As a business, you want to keep your followers interested, and in-tune with all your media outlets. One great way is to use Twitter's direct messages. If you follow CATS on twitter, you'll get a direct message from us right away letting you know how you can keep in touch and get all of our updates.This kind of response is helpful to build a relationship with your followers. We searched google, and there were slim pickings as far as auto-responding software, so we decided to develop this inhouse. I'll be showing you how to build this into your email.

To implement this setup, you'll need the following things:

  • An email account on a Linux/UNIX system
  • A twitter account registered for that user
  • php-cli (or another scripting language if you want to re-implement it)
  • curl

When I was asked to develop the auto-responder, my first thought was "I'm getting this email from twitter that says 'George is now following you on twitter'. I bet I could use regular expressions to solve my case, but who knows when they'll change the format of the email or something...". After some investigation, I looked at the headers of the email, and I was delightfully surprised to see:

...
X-Twitterrecipientscreenname: catsone
X-Twittersenderscreenname: George_C
X-Twitteremailtype: is_following
X-Twitterrecipientid: 16535056
X-Twittersenderid: 16600001
Errors-To: Twitter <twitter-follow-twitter=catsone.com@postmaster.twitter.com>
X-Twittercreatedat: Tue Mar 09 17:04:37 +0000 2010
Bounces-To: Twitter <twitter-follow-twitter=catsone.com@postmaster.twitter.com>
X-Twitterrecipientname: CATS App Track Sys
X-Twittersendername: George C
...

This is something I can work with. I don't need to do any heavy lifting for this.

The main reason you need a unix email account is so that you can create a .forward file. This file tells your mail server to redirect your email messages to another email address, or in our case, a PHP script. The contents of the file is very simple. Assuming the user's name is twitter and our processing script is located at '/home/twitter/twitterReply.php', All we need in that file is: "| /usr/bin/php /home/twitter/twitterReply.php"
You can read more about the ".forward" file at http://www-acs.ucsd.edu/students/email/dotforward.shtml

The actual PHP script will essentially read the email headers to determine if the email is a "Following" email and the user ID of your new follower. If we can determine both, then we're going to use the Twitter API to send a message to that user. I'll leave all the code explanation to the comments since the whole script is just about 50 lines.
Note: Feel free to include HTML tags in the message such as <a href="www.example.com">My Site</a> because it's running through urlencode().

<?php
 
// Config Options
$username = 'andy';
$password = 'secret';
$message  = 'This is the message your followers will get.';
 
// Read the email message from standard input
$fp = fopen('php://stdin', 'r');
 
// These default to false
$isFollowing = false;
$userID = false;
 
// Read lines until we get past the header
while($line = fgets($fp))
{
    // We just need to match a static header signifying that they are now following us
    if (trim($line) == 'X-Twitteremailtype: is_following')
    {
        $isFollowing = true;
    }
 
    // If we haven't found the userID yet, then use a regular expression to pull out the userID
    // Sure we could have used strpos() and substr(), but I <3 regular expressions.
    if (empty($userID) && preg_match('/X-Twittersenderid: (d+)/', $line, $m))
    {
        $userID = $m[1];
    }
 
    // Once we're finished reading the headers, then we're done.
    if ($line == "\n")
    {
        break;
    }
}
 
// Close the file handle properly
fclose($fp);
 
// Make sure this email is an "Is Following" email and we found a valid userID
if ($isFollowing && $userID)
{
    // urlencode the message because it's going to be a POST variable. The userID is just a number, so it's fine.
    $message = urlencode($message);
    // Use the "which" command to find the proper path for curl.
    $curl = trim(`which curl`);
    // Finally, call curl using our username and password, the userID, and the message to the Twitter API.
    // I added a redirection to /tmp/twitter.debug.txt so we can check what the last api call returned.
    exec("$curl -u $username:$password -d 'user=$userID&text=$message' \
        http://twitter.com/direct_messages/new.xml > /tmp/twitter.debug.txt");
}
?>

See a list of our other blogs.
 

Recent blogs by Andy Mornes

Setting up a redundant email server - 10/05/2009 - 10:32am
In the past few weeks, we have seen an increase in the amount of emails being sent through the CATS system. In response to this increase, I was assigned the task of... read more

Search and Import LinkedIn Profiles into CATS - 09/09/2009 - 4:33pm
There's no shortage of requests for LinkedIn integration. We're proud to announce that as of today, via our Firefox toolbar, you can now import LinkedIn profiles, resumes... read more

Tips for importing CSV files - 04/24/2009 - 3:59pm
During my time working with CATS, I've dealt a lot with CSV files, whether it be exporting a MySQL query using the "INTO OUTFILE" clause, or converting a MSSQL database... read more