the world is a pixel
Posts tagged API
Twitter Bot @rudaufc versão 1
Nov 9th

Este aqui é um bot bem simples para Twitter.
Diariamente, as nove da manhã ele posta qual vai ser o cardápio do RU (Restaurante Universitário) da UFC naquele dia.
Assim, quando vai batendo a hora da fome, os alunos podem entrar no perfil @rudaufc e olhar qual vai ser o prato do dia, ou quem está seguindo ele no Twitter pode ter a agradável surpresa de ver todo dia o que vai ser servido hoje.
Aqui está o código fonte do arquivo rudaufc.sh:
#!/bin/sh # Twitter bot @rudaufc login="rudaufc" senha="suasenhaaqui" segunda="Picadinho com legumes ou bife na chapa. Salada de macarrão com cenoura. Arroz. Feijão com abóbora e batata doce." terca="Franco guisado ou coxas de frango ao forno . Salada de acelga, cenoura e passas. Arroz. Feijão com abóbora e batata doce." quarta="# Feijoada à moda RU ou bisteca . Salada de repolho branco, cenoura e abacaxi. Arroz. Feijão com abóbora e batata doce" quinta="Frango à passarinho ou frango chinês. Salada de Alface, Tomate e Cebola. Arroz. Feijão com abóbora e batata doce." sexta="# Isca ao molho ou maravilha de carne. Salada de acelga com cenoura. Arroz. Feijão com abóbora e batata doce." dia=`(date +%w)` log=`(date +%Y-%m-%d-%s)`"-$$.log" dir="/home/silveiraneto/rudaufc" msg="" case "$dia" in # "0") msg=$domingo ;; "1") msg=$segunda ;; "2") msg=$terca ;; "3") msg=$quarta ;; "4") msg=$quinta ;; "5") msg=$sexta ;; # "6") msg=$sabado ;; esac curl -u $login:$senha -d status="$msg" http://twitter.com/statuses/update.xml > $dir/$log
A mágica toda está na capacidade do Curl de acessar facilmente a API do Twitter para enviar mensagens.
Para que o script execute diariamente as nove da manhã ele está alocado em um servidor com a crontab configurada da seguinte maneira:
0 5 * * * . /caminho_para_onde_ele_esta/rudaufc.sh
ps: leve em conta que o servidor está em um fuso horário diferente do Brasil.
Nessa versão o prato de cada dia está hardcoded no script, o que não é o ideal e faz com que semanalmente eu tenha que atualizar o script inserindo os pratos da semana manualmente. Eu espero que a próxima versão seja capaz de descobrir esses pratos e se atualizar sem nenhuma interferência.
Reading Twitter with JavaFX
Jan 4th

Twitter is a social network and micro-blogging service that allow you to create and read tweets, 140 characters text-based posts. It’s becoming a popular tool to keep in touch with your friends, coworkers, bloggers, etc. Here we’ll create a very simple application that show us tweets related with a given word.
Twitter offers a very simple and powerfull REST API which supports XML, JSON, and the RSS and Atom formats. As we are aiming just to read tweets we’ll use just the Search API.
We do that in three steps:
- Query Tweets
- Parser the Atom result
- Show tweets into a GUI
Let’s see them in the order of dependence beetween them.
Displaying a Tweet
var gradient = LinearGradient { startX: 0.0, startY: 0.0, endX: 0.0, endY: 150.0 proportional: false stops: [Stop {offset: 0.0 color: Color.DARKGRAY }, Stop { offset: 1.0 color: Color.BLACK }] } public class Tweet extends CustomNode { public var image: Image; public var username: String; public var message: String; public override function create(): Node { var txt = Text { x: 65 y: 35 wrappingWidth: 150 fill: Color.WHITE content: "{message}" } return Group { content: [ Rectangle { width: 220 height: txt.boundsInLocal.height + 40 arcHeight: 10 arcWidth: 10 fill: gradient }, ImageView { x: 5 y: 20 image: image }, Text { x: 65 y: 20 fill: Color.BLACK content: "{username} said" }, txt ] }; } }
For example, this tweet would become:

Parsing ATOM result
In my last post about JavaFX I showed how to parse XML documents (and make sandwiches) with JavaFX. Here we’ll use the Atom format, but use any other would be almost the same. Parsing XML or JSON documents with JavaFX is both very simple using the javafx.data.pull.PullParser class.
A query output is a Atom XML document with several information. We are interested only in the fields that holds the avatar image, the message and the user name.
var tweets = VBox {} def parser = PullParser { var avatar; var firstname; var text; documentType: PullParser.XML; onEvent: function(event: Event) { if(event.type == PullParser.START_ELEMENT){ if(event.qname.name.equals("link")){ if(event.getAttributeValue(QName{name: "rel"}) == "image"){ avatar = event.getAttributeValue(QName{name:"href"}); } } } if(event.type == PullParser.END_ELEMENT) { if(event.qname.name == "title"){ text = event.text; } if((event.qname.name == "name")and(event.level==3)){ var names: String[] = event.text.split(" "); firstname = names[0]; insert Tweet { image: Image { url: avatar } message: text username: firstname } into tweets.content; } } } }
Querying Tweets
We can get Atom results through url queries like that:
- Tweets containing the word Beatles http://search.twitter.com/search.atom?q=Beatles
- Tweets from the user Silveira http://search.twitter.com/search.atom?q=from%3ASilveira
- Tweets to the user Silveira http://search.twitter.com/search.atom?q=to%3ASilveira
- Tweets containing the hashtag #CEJUG http://search.twitter.com/search.atom?q=to%23CEJUG
Notice that queries should be URL encoded. We will use a additional parameters &rpp=4 to receive only 4 results per page. To know more about search queries read the Search API Documentation. We get these results as InputStreams making asynchronous HTTP requests using the javafx.io.http.HttpRequest class, which it’s perfect to invoke RESTful Web Services.
word = "Beatles"; var request = HttpRequest { location: "http://search.twitter.com/search.atom?q={word}&rpp=4"; onInput: function(stream: java.io.InputStream) { parser.input = stream; parser.parse(); } } request.enqueue();
Conclusion
Here is the application running for the word “House”.

Is not a complete Twitter client, as it’s not intended to be, but can show you how to handle a simple asynchronous call and handle Twitter documents. There’s already a few beta JavaFX Twitter clients like Tweetbox and Twitterfx and certanly others will appears.
Download
Sources and Netbeans project, fxtwitter.tar.bz2.












