Wednesday, February 29, 2012

Twitter account automation using PHP, cron, and the Twitter API

Code example makes use of themattharris tmhOAuth library:

1.) Sign into the Twitter developers site using the account you want to automate

2.) Create a new app by hovering over your user name in the top right corner and clicking "My Applications"

3.) In the 'Settings' tab, change permissions of your app to "Read, Write and Access direct messages"

4.) In the 'Details' tab, at the bottom of the page, click "Create my access token"

5.) Copy and paste your consumer key, consumer secret, access token and access token secret from the 'Details' tab into the appropriate location in the example code

6.) In the code, change your outgoing tweets by modifying the $possibilities array and adding more levels of customization/randomization

7.) Test your script on the command line or browser:
# php /path/to/file/twitter.php (command line) 
or (browser)

8.) If the script prints out "200 (your message)", then everything has succeeded. Check your account on the Twitter website to make sure you have posted a new status.

9.) Once your script is working and complete, setup a cron job on the command line (replace path to script and PHP based on your configuration/OS):
# crontab -e
*/5 * * * * /usr/local/bin/php /path/to/file/twitter.php

This cron job is set to run every 5 minutes. Your Twitter account will now be posting random tweets every 5 minutes.

This method is especially powerful when used with additional resources from the Twitter REST API.



// themattharris tmhOAuth library
require 'tmhOAuth.php';

// credentials from
$tmhOAuth = new tmhOAuth(array(
    => 'xxxxxxxxxxxxxxxxxxxxxx',
    => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

// all possible statuses
$possibilities = array('Random status 1 #hashtag1',
                       'Random status 2 #hashtag2',
                       'Random status 3 #hashtag3',
                       'Random status 4 #hashtag4',
                       'Random status 5 #hashtag5',
                       'Random status 6 #hashtag6',
                       'Random status 7 #hashtag7',
                       'Random status 8 #hashtag8');

// pick a status randomly
$posIndex = array_rand($possibilities,1);
$msg = $possibilities[$posIndex];

// always limit the message to 140 characters
$out = substr($msg, 0, 140);

// post status to authenticated user's profile
$code = $tmhOAuth->request('POST', 
                           array('status' => $out));

// echo response code/error and the message sent
echo $code.'  '.$out;


No comments:

Post a Comment