Twitter OAuth: a Simple Ruby Script

June 3rd, 2010 § 0

We all want shortcuts.
As of the end of this month, Twitter will deprecate support for http authentication (provide username and password explicitly) in API request. The alternative is called OAuth and Twitter has a comprehensive guide here. However, it appears too complex to us, and what we need is a method as similar to http auth as possible, since for researchers like us, the sole purpose of using API request is to get data via a robot account.
Here is the simplest shortcut, illustrated in Ruby.

  1. Register an app at http://dev.twitter.com/apps/new, and you’ll get a consumer key and a consumer secret. From the page “my access token”, you can find an access token and an access secret.
  2. Write the four strings into a config file, e.g. $HOME/.twitter. Below is a yaml config example.
    #!/usr/bin/ruby -w
    # require 'pp'
    require 'yaml'
    
    CToken   = "AAAAAAAAAAAAAAAAAAAAA"
    CSecret  = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
    AToken   = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
    ASecret  = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
    
    config = {"ctoken" => CToken, "csecret"=>CSecret, "atoken"=>AToken, "asecret"=>ASecret}
    File.open("#{ENV["HOME"]}/.twitter", "w") do |f|
      f.puts config.to_yaml
    end
    
  3. Authorize your application in a script, using twitter gem.
    #!/usr/bin/ruby -w
    
    require 'pp'
    require 'yaml'
    require 'twitter'
    require 'mysql'
    
    conf = {}
    File.open("#{ENV["HOME"]}/.twitter", "r") { |f| conf = YAML.load(f) }
    
    # twitter authentication
    oauth  = Twitter::OAuth.new(conf["ctoken"], conf["csecret"])
    oauth.authorize_from_access(conf["atoken"], conf["asecret"])
    client = Twitter::Base.new(oauth)
    
    client.home_timeline.each { |tweet| pp tweet }
    exit
    

关于食物的续

May 18th, 2010 § 5

伊壁鸠鲁说

一切幸福的根源都是口腹的快乐。

或许也可以反过来说,所有的不幸福都可反溯回口腹的不快乐。说了好多次留学美利坚后吃的历史像是一部迂回冗长的破小说,在尝过新鲜之后就开始愈发地索然无味,自然产生了抛诸脑后的念头。然而终没有一门学问可以教人学会光合作用的功夫,进化了两千三百年,“胃(依然)是一切事物的根本”,所以在北美生活一天,这部可怜的破小说就要无可奈何地写下去,只有期望若淡到最后不要觉得是味同嚼蜡便是值得庆幸的了。
都说音乐像是尘封记忆的盒子,当往日的旋律响起,浮现在脑海里的便是那时的景那时的人和那时的心情。Y 说人人心里都有属于自己的那张“旧船票”,没想到食物也会有相似的作用。过了一个天天有午饭吃的去年夏天之后,我的正午十二点便开始经历六道轮回,厌倦了中式水饺、厌倦了韩国泡面、厌倦了台湾凤梨稣、厌倦了玉米小馒头、厌倦了杰斯特、厌倦了三刀的小皮萨,最终又回到了起点。一年前能在墨西哥自助里聚起的一大桌都已散到了海峡两岸还有加拿大,只是彼时对二年论文的焦虑换成了别人,而旧人留给我的那一张怎么用也用不完的破饭卡就成了让我又登上那艘破船的旧船票。除此之外就是不断地晃荡着去学校周围的那些馆子,只不过同行的人由一个 Tang 变成了另一个 Tang。让人哭笑不得的是在游戏似的四方网里 check in 也竟成了新尝试的动力,怂恿着我在马丁格尔和布朗运动的压迫里暂时逃脱出来,在德州的阳光下看瓜德拉普街上熙熙攘攘的人,谈冗冗长长的文,笑系里古古怪怪的事。
又有人要离开,于是和上篇一样,周六是在游泳池边树荫底下吃的轰煤的 BBQ。都是三年前来的相似的人,转眼间就已做着太不同的事。话题不多,聊着聊着就收敛到了世博、世界杯还有「非诚勿扰」。国内同学纷纷逃离的东西,到这里变成了流露着艳羡的趣事。可能是生活太平静了,需要点调味品吧。