Sou responsável por um site de notícias e hoje precisei criar um meio de que quando uma notícia for inserida no site, ser criado automaticamente um tweet no twitter lincando para ela, a solução foi essa classe abaixo:
class Tweet{ var $user; var $pass; var $json = false; function __construct($user, $pass, $texto=false){ $this->user = $user; $this->pass = $pass; if ($texto) $this->send($texto); } private function testTweet($texto, $match){ foreach ($match as $m){ $url = $m[0]; if (ereg("^www", $url)) $url = "http://$url"; if (strlen($url) > 19) $url = str_repeat("x", 19); $texto = str_replace($m[0], $url, $texto); } $texto = ereg_replace("http://(x{19,})", "\\1", $texto); if (strlen($texto) > 140) return false; return true; } public function makeUrl($url){ if (ereg("^www", $url)) $url = "http://$url"; if (strlen($url) <= 19) return $url; $url = "http://migre.me/atalho/" . urlencode($url); $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true )); $o = curl_exec($ch); ereg ("value=\"(http://migre.me/[a-zA-Z0-9/:]+)\"", $o, $mat); return $mat[1]; } public function send($texto){ if (function_exists("curl_init")){ // Localiza as URLs preg_match_all("/((https?:\/\/)|(www))([a-zA-Z0-9\/:%&\?\.=\-\+]+)/", $texto, $match, PREG_SET_ORDER ); // Testa se o tamanho do twitter é aceitavel if (!$this->testTweet($texto, $match)) throw new Exception ("Postagem muito longa!"); // Cria as URLs finais foreach ($match as $m) $texto = str_replace($m[0], $this->makeUrl($m[0]), $texto); $texto = str_replace("http://http://", "http://", $texto); // Testa novamente pelo comprimento do tweet if (strlen($texto) > 140) throw new Exception ("Postagem muito longa!"); // Envia o tweet $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => "http://twitter.com/statuses/update.json", CURLOPT_HTTPHEADER => array('Expect:'), CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array("status" => "{$texto}"), CURLOPT_HTTPAUTH => CURLAUTH_ANY, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERPWD => "{$this->user}:{$this->pass}") ); return $this->json = curl_exec($ch); } return $this->json = false; } } $tmp = new Tweet("username", "password"); echo $tmp->send("Eu não gosto das URLs do site da Microsoft: http://search.microsoft.com/results.aspx?form=MSHOME&setlang=en-us&q=office+templates&mkt=en-US");
Ela faz a análise do seu texto e converte as URLs, caso necessário, para um formato resumido usando o migre.me e caso passe os 140 caracteres uma exception é jogada.
Caramba, que ótima dica, amigo!
Está favoritada aqui! Stumblizada e Deliciouszada! huahuahuahuahua
Peço permissão para publicá-la em meu blog, em alguma data não definida ainda.
Com trackbacks e referência para seu site, ok?!
No aguardo!
Abração,
Rodrigo Filardi
Gostei muito; forma fácil de utilização da APi do Twitter!
Parabéns pelo blog, inclusive! Estou aproveitando muito a leitura dos demais posts!