2011-02-14

Making Lingr Bot

dev

Background

I wrote an article about new Lingr bot (Japanese) about 1 year ago, but recently, Lingr API had been changed.

So I try to use new API and write a note for it.

This note is based on this official document.

What's changed?

  • Bots now can say to room on bot's own will.
  • Now JSON params will send without json= (params[:json])

Try name calling bot

require "sinatra"
require "json"

post "/hi" do
  j = JSON.parse(request.body.string)
  j["events"].map{ |e|
    if e["message"]
      "Hi, #{e["message"]["nickname"]}!"
    end
  }.compact.join("\n")+"\n"
end
  • Lingr will post a JSON to bot's endpoint.
  • JSON is like:

    {"status":"ok",
     "counter":208,
     "events":[
      {"event_id":208,
       "message":
        {"id":82,
         "room":"myroom",
         "public_session_id":"UBDH84",
         "icon_url":"http://example.com/myicon.png",
         "type":"user",
         "speaker_id":"kenn",
         "nickname":"Kenn Ejima",
         "text":"yay!",
         "timestamp":"2011-02-12T08:13:51Z",
         "local_id":"pending-UBDH84-1"}}]
    

    Quoted from the document

deploy this code to web, then register to lingr, finally invite your bot to room.

d8128a11728fcf10460e6fb4335038ba.png

Note: You can create a bot from here

Try self posting

#-*- coding: utf-8 -*-
require "sinatra"
require "json"
require "open-uri"

Thread.new do
  t = nil
  loop do
    if t.nil? || Time.now.min > t
      t = Time.now.min
      text = "#{Time.now} ですがだるいです"
      open("http://lingr.com/api/room/say?room=ROOM&bot=BOT_NAME&text=#{URI.escape(text)}&bot_verifier=YOUR_VERIFIER"){|io| io.read }
    end
    sleep 15
  end
end

post "/darui" do
  j = JSON.parse(request.body.string)
end
  • Posting API is http://lingr.com/api/room/say?room=ROOM&bot=BOT_NAME&text=TEXT&bot_verifier=YOUR_VERIFIER

    • ROOM: room id. http://lingr.com/room/ROOM_ID
    • BOT_NAME: bot id. You can reference at http://lingr.com/developer
    • TEXT: URL escaped body (It'll appear on room)
    • YOUR_VERIFIER: bot verifier. ruby -rdigest/sha1 -e'puts Digest::SHA1.hexdigest("BOT_NAME"+"BOT_SECRET")'; BOT_SECRET is at http://lingr.com/developer

Deploy this code to web, then register to lingr, finally invite your bot to room.

64b82429332f6aa5330f7f332393abcc.png

Published at 2011-02-14 03:34:42 +0900 | Permalink
2010-12-28

Easy Easy Paging

dev

set items per page to items_per_page, items with Array to items and page number to page.

It's easy to implement. Woo!

Published at 2010-12-28 03:54:50 +0900 | Permalink
2010-12-05

Ruby Advent Calendar 2010 jp-en Day 6: Tinatra

dev

Did you make any twitter bots?

Now Twitter doesn't support BASIC authorization, so bots making is more difficult.

OAuth authorization code is waste!

Tinatra resolve that problem. :)

Tinatra?

Sinatra: Classy web-development dressed in a DSL (quoted from github description)

Tinatra: Dirty twitter-bot development dressed in a DSL

Tinatra on github: https://github.com/sorah/tinatra

Install

$ gem install tinatra

or

$ git clone https://github.com/sorah/tinatra.git

Create a bot

Step 1. Register as OAuth consumer

http://dev.twitter.com/apps/new

Fill forms and submit.

NOTE: The following forms must be selected the following answers.

Application Type: Client

Default Access Type: Read & Write

Step 2. Note "Consumer key" and "Consumer secret"

See a application page; application page will be showed after registration.

Step 3. Write a code

  • Bot will reply a time to any mentions.
  • Bot post a time every boot.

Code is here

require 'tinatra'

mention do |d|
  api.update("@#{d[:user][:screen_name]} Hi, the time is #{Time.now}",
            :in_reply_to_status_id => d[:id])
end

always do
  api.update("#{Time.now}")
end

It's easy to read, easy to write. Any authorization codes don't exist.

Code is clean! Woooooo!

Step 4. Get Account For Bot

I'm using incognito window for making new account.

Step 5. Run

% ruby bot.rb
You must set a path to db file using --db= or db method.

Database is used to saving token, last mention, etc...

% ruby bot.rb --db=./db
Run bot.rb --init first.
% ruby bot.rb --db=./db --init
------------ AUTHORIZING ------------
Input your consumer key: CONSUMER_KEY
Input your consumer secret: CONSUMER_SECRET

Access This URL and press 'Allow' in account for tinatra => http://api.twitter.com//oauth/authorize...
Input key shown by twitter: 0000000

Authorizing is done.

Open URL and allow on bot account, then Input PIN code.

Final, run again.

% ruby bot.rb --db=./db 

0c4fed6571445bd0ac8f970625124506.png (552×307)

I post a mention for the bot and run again.

The bot returned the time to me.

c1345aa3bbff3ed4e9bc77521794108d.png (445×247)

Next?

  • Add the command to crontab
  • Announce the bot
  • etc...

Code description

require 'tinatra'

mention do |d|
  api.update("@#{d[:user][:screen_name]} Hi, the time is #{Time.now}",
            :in_reply_to_status_id => d[:id])
end

always do
  api.update("#{Time.now}")
end

mention block will be called with new mention.

always block will be called every boot.

api is an instance of OAuthRubytter.

More blocks exist for bot development.

require 'tinatra'

timeline do |tweet|
  p tweet #=> New tweet in timeline
end

mention do |m|
  p m #=> New tweet in mention
end

direct_message do |dm|
  p dm #=> New Direct message
end

followed do |user|
  p user #=> New user who is followed
end

removed do |user|
  p user #=> User removed
end

always do
  # Always run
  p api.class #=> OAuthRubytter
  api.update("hi")
end

It's useful.

Ruby Advent Calendar 2010: jp-en

This entry is for Ruby Advent Calendar jp-en: 2010.

Previous post is from igaiga555, And next post will be from tagomoris

I forgot to attend Ruby Advent Calendar jp: 2010.. ;-(

Published at 2010-12-05 15:00:51 +0900 | Permalink
2010-12-04

I became a contributor at ruby

dev

I forgot to wrote as post.

I became a contributor at ruby at Nov 25.

HINT: contributor isn't equal to committer

Still I can't commit directly to ruby :)

Ruby - Overview - Ruby Issue Tracking System

I'll do my best still more to become a committer ;-)

Published at 2010-12-04 12:11:02 +0900 | Permalink
2010-12-04

そういえばRubyのContributerになっていました。

dev

11/25のときのお話。まだかいていませんでした。

nurse: そらさんに権限追加しとくか
nurse: とりあえずContributorに
n0kada: あーぁ
n0kada: かわいそうに…
nurse: これでそらさんにはRubyに貢献する義務が発生しました
nurse: おめでとうございます
sora_h: ありがとうございます
n0kada: 士農工商 Contributor Committer
nurse: Contributorまでは人

Ruby - Overview - Ruby Issue Tracking System

Contributerなのでコミッターではない。

要するに「不動点小数勉強してこい」といいながらrejectできる(nurseさんいわく らしい。

コミッターになるためにこれからもがんばります。

Published at 2010-12-04 12:04:01 +0900 | Permalink
2010-10-28

Titanium developer won't launch the iPhone simulator

dev

Upgrade your Xcode and SDK (I was using SDK for 3.1.x)

SDK 4.1 overwrites SDK 3.1.x, but 4.1 can work to 3.1.x devices. :)

Published at 2010-10-28 01:19:33 +0900 | Permalink
2010-10-14

Notify git status to Growl/libnotify in background

dev

I putted git status in zsh prompt, but sometimes slowly like git-svn ruby repo.

So I found the page notify to Growl, but It needed a drb daemon for notify it.

http://d.hatena.ne.jp/hitode909/20100222/1266808483

Ruby supports fork, I used fork for background working, but fork wake up slowly (slower than prompt putting!)

But we can use spawn for instead.

Spawn

fork: Clone this process

fork { .. }: Clone this process and run block

spawn: Make another process and run in background

zshrc

requirements

  • ruby1.9+
  • notify.gem
  • git.gem
  • libnotify with libnotify-bin or growl

script

Demerits

  • Ruby doesn't know myself; spawned ruby is same as ruby?
  • Doesn't know version; it is really 1.9+?
  • Error will be not hidden; it puts error directly if failed
Published at 2010-10-14 23:25:59 +0900 | Permalink
2010-09-23

Test ruby with the beautiful night sky

dev

Test with stars.

star-test

Patch here: sorah/ruby:neta_startest

This patch changes lib/minitest/unit.rb, make star and append some spaces unless @verbose.

If test is failed, make spaceship <=> unless @verbose.

Have fun!

Published at 2010-09-23 01:25:55 +0900 | Permalink