Sha256: aa20d8b74d7b29455222bca7c6e31a8c378afb11b94a89ac807bd5a9b4db53fe

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

require 'xmpp4r'
require 'xmpp4r/muc'
require 'xmpp4r/roster'

require 'singleton'
require 'zoe/jabber'
require 'zoe/rexml_patches'

class Zoe
  include Singleton

  attr_reader :client, :roster, :rooms, :callbacks

  def initialize
    @callbacks = []
  end

  def connect(jid: nil, password: nil, rooms: [])
    @jid = jid
    @client = Jabber::Client.new(jid + '/bot')

    @client.connect
    @client.auth(password)
    @client.send(Jabber::Presence.new.set_type(:available))

    @roster = Jabber::Roster::Helper.new(@client)
    @roster.wait_for_roster

    @rooms = rooms.map do |room_name|
      room = Jabber::MUC::MUCClient.new(@client)
      room.join(room_name + '/' + self.jid.iname)
      room
    end

    @client.add_message_callback(200) do |m|
      if m.type == :chat # if PM
        m.reply_to = m.from
      elsif m.type == :groupchat && m.from.resource # if GM
        m.reply_to = m.from
        m.from = get_jid_by_name(m.from.resource)
      end

      if m.body
        @callbacks.each{ |c| c.call(m) }
      end
    end
  end

  def jid
    @roster[@jid]
  end

  def get_jid_by_name(name)
    @roster.items.values.find{ |v| v.iname == name }
  end

  def send(to, message)
    to = to.is_a?(Jabber::JID) ? to : Jabber::JID.new(to.to_s)
    message = Jabber::Message.new(to, message)
    message.type = (to.domain == "conf.hipchat.com" ? :groupchat : :chat)

    @client.send(message)
  end

  def on_message(&block)
    @callbacks << block
  end

  def debug!
    Jabber.logger = Logger.new(STDOUT)
    Jabber.debug = true
  end

  def self.method_missing(method, *args, &block)
    instance.__send__(method, *args, &block)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
zoe-0.1.0 lib/zoe.rb