2008年 02月 06日

Ruby の Jabber(XMPP) ライブラリ

xmpp4r-simple がつかいやすいみたいかな。xmpp4r のラッパで、作者が twitter の中の人みたい

require "rubygems"
require "xmpp4r-simple"
require "pit"

config = Pit.get("jabber", :require => {
	"username" => "username of jabber account",
	"password" => "password of jabber account",
})

im = Jabber::Simple.new(config["username"], config["password"])

Thread.start do
	loop do
		im.received_messages do |msg|
			p msg
			p msg.from
			p msg.body
			p msg.type
		end
		sleep 1
	end
end
#im.deliver("to@example.com", "foobar")

sleep

received_messages は常に non-blocking なのでループさせる必要がある。xmpp4r のほうはコールバックになってるから、特に non-blocking にしたくないんだったら im.client.add_message_callback do |msg| end したほうがいいかも。

im.subscribed_to?(jid) とか便利なのもあるけど、接続直後だと、どんなアカウントでも false をかえしたりする。

特別いろいろやりたいんじゃなかったら xmpp4r-simple のほうがめんどくさくなくてよさげ (なにがめんどいって最初のコネクションだけど、あと接続きれたときの処理とかもめんどいし、そこらへんかってにやってくれるのは嬉しい)

require "rubygems"
require "xmpp4r"

config = ...

jid    = Jabber::JID.new(config["username"])
client = Jabber::Client.new(jid)
client.connect
client.auth(config["password"])
client.send Presence.new(nil, "") # 現在の状態をセット。しないと他の人にはオフラインのままにみえる
client.add_message_callback do |msg|
	p msg
end

エラー処理もいれないといけなくて、エラーがおきて re-connect したらまた Presence をおくらないといけなくて、みたいな感じでめんどい。