XMPP4R-Simple makes XMPP in Ruby uhh... simple...

May 28, 2008

I thought it would be fun to build a control interface you could talk to over instant messaging -- something like the IM bot that Twitter used to have. I started by looking at XMPP4R, but a bit of reading led me to [XMPP4R-Simple](http://xmpp4r-simple.rubyforge.org/). Well, simple is always good. One `gem install` and 45 minutes later, I had a Ruby script that could log in to an XMPP server, listen to (and log) what people said, and respond with a simple message. ```ruby #!/usr/bin/env ruby require 'rubygems' require 'xmpp4r-simple' logfile = File.join('..', 'log', "#{File.basename(__FILE__)}.log") logger = Hodel3000CompliantLogger.new(logfile) jabber = Jabber::Simple.new "username@domain.com", "password" sleep 1 jabber.status(:away, "No one here but us mice.") sleep 1 jabber.deliver("craig@xeriom.net", "I woke up at #{Time.now}.") loop do begin jabber.received_messages do |msg| jid = msg.from.strip.to_s logger.info "%s said: %s" % [ jid, msg.body ] jabber.add(jid) if !jabber.subscribed_to?(jid) jabber.deliver(jid, "Nom nom nom.") end jabber.presence_updates do |update| jid, status, message = *update logger.info "#{jid} is #{status} (#{message})" end jabber.new_subscriptions do |friend, presence| logger.info "#{friend.jid} #{presence.type}" jabber.add(friend.jid) if !jabber.subscribed_to?(friend.jid) end rescue Exception => e logger.error e.to_s end sleep 1 end ``` The loop does three things: it handles incoming messages (logging them and replying with a deeply intellectual "Nom nom nom"), tracks presence updates, and auto-accepts new subscriptions. The `sleep 1` calls keep us from hammering the server. Our own little pet XMPP client. How cute is that? If you've found this article useful, I'd appreciate a recommendation at [Working With Rails](http://www.workingwithrails.com/recommendation/new/person/7241-craig-webster).
Questions or thoughts? Get in touch.