aboutsummaryrefslogtreecommitdiff
path: root/dinobot.rb
blob: ce08b7ccafef2ef1639fa91642163b24eed08eec (plain) (blame)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
require 'socket'
require 'timeout'

module Dinobot
  class Bot
    attr_accessor :trigger
    attr_reader :server, :port, :nick, :pass, :modules, :channels

    def initialize(server, port, nick, pass=nil, &block)
      @server = server
      @port = port
      @nick = nick
      @pass = pass

      @trigger = '!'

      @socket = nil
      @modules = Hash.new
      @channels = Array.new

      instance_eval(&block) if block_given?
    end

    def connect
      log :info, "Connecting to #{@server}:#{@port}."
      @socket = TCPSocket.new(@server, @port)

      out "PASS #{@pass}" if @pass
      out "NICK #{@nick}"
      out "USER #{@nick} 0 * :#{@nick}"

      @channels.each do |channel|
        join channel
      end
    end

    def connected?
      !(@socket.nil? || @socket.closed?)
    end

    def run
      connect unless connected?

      while str = @socket.gets.chomp
        log :in, str.inspect

        Thread.new do
          begin
            Timeout.timeout(30) do
              parse_line(str)
            end
          rescue => e
            log :error, "Error parsing line. (#{e})"
            log :indent, *e.backtrace
          end
        end
      end

      @socket.close
      log :info, 'Disconnected.'
    end

    def out(str)
      return unless connected?

      log :out, str.inspect
      @socket.puts str
    end

    def say(channel, message)
      out "PRIVMSG #{channel} :#{message}"
    end

    def join(channel)
      @channels << channel unless @channels.include?(channel)

      out "JOIN #{channel}"
    end

    def part(channel)
      @channels.delete(channel)

      out "PART #{channel}"
    end

    def load_module(mod)
      mod = mod.downcase.intern
      log :info, "Loading module: #{mod}"

      begin
        load "#{mod}.rb"

        m = Dinobot.const_get(Dinobot.constants.find { |x| x.downcase == mod })
        @modules[mod] = m.new(self)

        log :info, "Loaded module: #{mod} (#{m})"
      rescue LoadError, StandardError => e
        log :error, "Failed to load module: #{mod} (#{e})"
      end
    end

    def unload_module(mod)
      mod = mod.downcase.intern
      log :info, "Unloading module: #{mod}"

      begin
        raise 'module not loaded' unless @modules.has_key?(mod)

        @modules.delete(mod)
        m = Dinobot.send(:remove_const,
          Dinobot.constants.find { |x| x.downcase == mod })

        log :info, "Unloaded module: #{mod} (#{m})"
      rescue => e
        log :error, "Failed to unload module: #{mod} (#{e})"
      end
    end

    def log(type, *lines)
      str = lines.join("\n")

      case type
      when :in
        prefix = "\e[32m<<\e[0m "
      when :out
        prefix = "\e[36m>>\e[0m "
      when :error
        prefix = "\e[31m!!\e[0m "
      when :info
        prefix = "\e[33m==\e[0m "
      when :indent
        prefix = '   '
      else
        raise "unknown type specified -- #{type}"
      end

      puts str.gsub(/^/, prefix)
    end

    private

    def parse_line(str)
      out str.sub('PING', 'PONG') if str =~ /^PING /

      if str =~ /(\S+) PRIVMSG (\S+) :(.*)/
        user, channel, message = str.scan(/(\S+) PRIVMSG (\S+) :(.*)/).first

        return unless message.sub!(/^#{Regexp.escape(@trigger)}/, '')

        methods = exec_command(user, channel, message)
        ensure_valid_methods(methods)
        run_methods(methods)
      end
    end

    def exec_command(user, channel, command, prev=nil)
      command, remainder = command.split(' | ', 2)
      mod = command.scan(/\A\S+/).first.downcase

      return unless @modules.keys.map { |x| x.to_s }.include?(mod)
      mod = mod.intern

      if prev.nil?
        methods = @modules[mod].call(user, channel, command)
      else
        ensure_valid_methods(prev)
        methods = []

        prev.each do |p|
          if p.first == :say
            m = @modules[mod].call(user, p[1], "#{command} #{p[2]}")
            ensure_valid_methods(m)
            methods.concat(m)
          else
            methods << p
          end
        end
      end

      remainder ? exec_command(user, channel, remainder, methods) : methods
    end

    def run_methods(methods)
      methods.each do |m|
        log :info, "Executing method: #{m.inspect}"
        send(*m)
      end
    end

    def ensure_valid_methods(methods)
      raise "method list not array -- #{methods}" unless methods.is_a?(Array)

      methods.each do |m|
        raise "method not array -- #{m}" unless m.is_a?(Array)

        case m.first
        when :say
          raise "wrong number of arguments -- #{m}" unless m.length == 3
        when :join, :part
          raise "wrong number of arguments -- #{m}" unless m.length == 2
        else
          raise "unknown method name -- #{m}"
        end
      end
    end
  end
end