public
Description: Direct Connect bot written in Ruby
Clone URL: git://github.com/kballard/dcbot.git
Search Repo:
dcbot / plugin.rb
100644 71 lines (60 sloc) 1.856 kb
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
require 'activerecord'
 
class PluginBase
  @@plugins = []
  @@pluginWrapper = nil
  CMD_PREFIX = "!"
  
  def self.inherited(subclass)
    @@plugins << subclass
  end
  
  def self.cmd_prefix=(new_prefix)
    CMD_PREFIX.replace(new_prefix)
  end
  
  def self.commands
    @@plugins.map { |plugin| plugin.methods.grep(/^cmd_[a-zA-Z]+$/).map { |cmd| cmd.sub(/^cmd_/, "") } }.flatten
  end
  
  def self.has_command?(cmd)
    self.commands.include? cmd
  end
  
  def self.has_command_help?(cmd)
    @@plugins.any? { |plugin| plugin.methods.include? "cmd_#{cmd}_help"}
  end
  
  def self.command_help(cmd)
    @@plugins.each do |plugin|
      meth = plugin.methods.grep("cmd_#{cmd}_help").first
      return plugin.method(meth) unless meth.nil?
    end
  end
  
  def self.dispatch(socket, cmd, sender, isprivate, args)
    @@plugins.each do |plugin|
      if plugin.methods.include? "cmd_#{cmd}" then
        begin
          plugin.method("cmd_#{cmd}").call(socket, sender, isprivate, args)
        rescue StandardError => e
          STDERR.puts "Exception raised executing cmd_#{cmd}:\n#{e.to_s}"
          # try one more time
          socket.sendPrivateMessage(sender, "An error occurred executing your command. Retrying...")
          self.initdb
          plugin.method("cmd_#{cmd}").call(socket, sender, isprivate, args)
        end
      end
    end
  end
  
  def self.loadPlugins
    @@plugins = []
    @@pluginWrapper = Module.new
    Dir["plugins/*"].each do |file|
      begin
        @@pluginWrapper.class_eval File.read(file), file
      rescue StandardError, ScriptError => e
        STDERR.puts "Error loading plugin `#{file}': #{e.to_s}"
      end
    end
  end
  
  def self.initdb
    ActiveRecord::Base.establish_connection(
      :adapter => "sqlite3",
      :dbfile => "dcbot.db")
  end
end
 
PluginBase.initdb
PluginBase.loadPlugins