viernes, 31 de diciembre de 2010

Script en PHP para felicitar a todos tus followers

Para este 31 de diciembre quise desearles un feliz año a todos los que me hacen el favor de leerme vía Twitter, así que me resigné a la tardada tarea de hacerlo persona por persona. No suena tan mal pero me tardaría todo el día, así que se me ocurrió la idea de hacerlo mediante un script (en PHP).

Primero hay que registrar tu aplicación (client) para obtener el consumer key, el consumer key secret, etcétera; sigue las instrucciones en esta otra entrada.

Recuerda instalar PHP CLI y PHP curl. Si utilizas un Debian o Ubuntu todo es tan fácil como

apt-get install php5-cli
apt-get install php5-curl

Uso: php felizanio.php


Ahora el código:

require('twitteroauth.php');

// Oauth settings: llenar segun datos al crear tu aplicacion
$consumerKey= 'XXXXXXXXXXXXXXXXXXXXXXX';
$consumerSecret = 'XXXXXXXXXXXXXXXXXXXX';
$oauthToken = 'XXXXXXXXXXXXXXXXXXX';
$oauthTokenSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$followers = array();

$conexion = new TwitterOAuth($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);

$followers = get_followers($conexion, $followers); // se obtiene un arreglo con todos tus followers

mensaje($conexion, $followers); // Manda el mensaje.


function get_followers($con, $fl){
$next_cursor = -1;
$hay_followers = true;
$path = 'statuses/followers';

while($hay_followers){
$parametros = array('cursor'=> $next_cursor,);
$timeline = $con->get($path,$parametros);

$users = $timeline->users;
$next_cursor = $timeline->next_cursor;

foreach($users as $value){
$fl[] = "@".$value->screen_name;
} // fin foreach

if($next_cursor == 0){
$hay_followers = false;
} //fi
} // fin while
return $fl;
} // fin get_followers()

function mensaje($con,$fl){

$a = "#FF y Feliz año ";
$b = $a;

foreach($fl as $value){
$value.= " ";
if(strlen($b.$value) <=140){
$b.=$value;
}else{
$twitter = $con->post('statuses/update', array('status' => $b));
echo"\n"."$b"."\n";
$b=$a;
$b.=$value;
}
}
$twitter = $con->post('statuses/update', array('status' => $b));
echo"\n"."$b"."\n";

}


*Nota: También son necesarias las librerias twitteroauth.php y Oauth.php escritas por Abraham Williams.

Todos los archivos necesarios están en aquí.

http://www.fileden.com/files/2010/10/29/3004194//felizanio.zip


Por último, para todos aquellos que puedan leer este artículo les deseo un 2011 lleno de paz y mucho éxito, que todos sus proyectos se realicen.

Felices líneas.

as

No hay comentarios: