summaryrefslogtreecommitdiffstats
path: root/bot.rb
blob: 1d5c0f6f9c809c7890cf65700b7bc2f3346144a3 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
require 'xmpp4r'
require 'xmpp4r/muc/helper/simplemucclient'

require_relative 'config'

module Lain
  Version = '0.1'

  class Bot

    def initialize
      $stderr.puts "Lain #{Version}"

      @modules = {}

      $stderr.print 'Loading modules...'

      Config::Modules.each { |mod, cfg|
        $stderr.print " #{mod}"
        require_relative "modules/#{mod}"
        @modules[mod] = Modules.const_get(mod).new(self, cfg)
      }

      $stderr.puts '.'

      @commands = @modules.values.reduce({}) { |c, mod| c.merge mod.commands }.to_a.sort

      $stderr.print 'Connecting... '

      @cl = Jabber::Client.new(Jabber::JID.new(Config::JID))
      @cl.connect
      @cl.auth(Config::Password)
      @cl.send(Jabber::Presence.new)

      $stderr.puts 'connection established.'

      @mucs = {}

      Config::Rooms.each { |r|
        muc = Jabber::MUC::SimpleMUCClient.new(@cl)
        @mucs[r] = muc

        muc.add_message_callback { |msg|
          unless msg.from == r
            @modules.each { | _, mod |
              begin
                mod.on_message muc, msg
              rescue
              end
            }
          end
        }

        $stderr.print "Trying to access room `#{r}'... "

        muc.join(r)

        begin
          muc.configure
        rescue
        end

        $stderr.puts "access granted."
      }

      $stderr.puts 'Initialization finished.'
    end

    def commands
      @commands
    end

    def run
      @mainthread = Thread.current
      Thread.stop
    end

    def close
      @cl.close
    end

  end
end