技術と全然関係ない話から始めるが、筆者うづらはUSローファイとカンタベリ系プログレが好きで、その両方のテイストを持った稀有な日本のバンド「箱庭の室内楽 (ex. bolbots)」を応援している。
なので、彼らの曲をLast.fmから引っ張って勝手にTwitterにポストするBot Programを作成しました。
使用したライブラリ
- Twitter/OAuth
- OAuthに必要な各種情報の取得は、「TwitterのbotをOAuthに対応させる」を参考にしました。
- Twitter with OAuthのサンプルは普通に公式から。
- Scrobbler
- Scrobbler by John Nunemaker
- APIが洗練されていて非常にいいライブラリだと思う。
ソース
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' require 'optparse' require 'yaml' require 'securerandom' require 'scrobbler' require 'oauth' require 'twitter' class Array def random_pick self[SecureRandom.random_number(self.size)] end end class BolbotsBot class << self def post self.new.post end end def initialize @conf_file = nil opt = OptionParser.new opt.on('-c CONF', '--config=CONF'){|v| @conf_file = v } opt.parse!(ARGV) @CONF = YAML.load_file(@conf_file || File.join(File.dirname($0), "config.yml")) end def post client.update("今日の一曲: #{track.name} - #{track.artist} #{track.url}") puts "ポスト成功: #{track.name} - #{track.artist}" end private def client @client ||= Twitter::Base.new(oauth) end def oauth unless @oauth @oauth = Twitter::OAuth.new(@CONF[:consumer_token], @CONF[:consumer_secret]) @oauth.authorize_from_access(@CONF[:access_token], @CONF[:access_secret]) end @oauth end def track @track ||= Scrobbler::Artist.new(artists.random_pick).top_tracks.random_pick end def artists @CONF[:artists] end end (__FILE__ == $0) && BolbotsBot.post |
ライブラリの力で意外と60行で済んだ。
設定ファイルは、例えば以下のようにして、「config.yml」と言う名前でプログラムと同じフォルダに置くか、「-c」オプションで指定する。
1 2 3 4 5 6 7 | :consumer_token: "hogehoge" :consumer_secret: "fugafuga" :access_token: "foo-bar" :access_secret: "buzbuz" :artists: - "bolbots" - "箱庭の室内楽" |
Usage
1 2 3 | chmod a+x bolbotsbot.rb ./bolbotsbot.rb -c bolbots.yml #=> ポスト成功: Deadwinter - Bolbots |
ちなみに、設定ファイルの書式で分かると思うけれど、例えば以下のような sogabe.yml ファイルを作って指定すれば曽我部恵一ボットになります。
1 2 3 4 5 6 7 8 | :consumer_token: "hogehoge" :consumer_secret: "fugafuga" :access_token: "foo-bar" :access_secret: "buzbuz" :artists: - "曽我部恵一" - "曽我部恵一BAND" - "サニーデイ・サービス" |
皆さんも自分勝手なBotを作るといいと思うよ。
免責事項
- テスト書いてない
- 例外処理書いてない
ToDo(思いつき)
- Scrobblerライブラリをもっと紹介してみる
- bolbotsbot_spec.rbを作成すればちょうどいいRSpecの教材にならないかな。無理かな




