repost/plugins/commands.rb
2014-03-25 07:21:49 +01:00

90 lines
2.7 KiB
Ruby

include EventMachine::IRC::Commands
# yay, monkey patching
class Repost
attr_accessor :commands
def register_command(keyword, &code)
begin
access_level = Config[:commands][keyword.to_sym][:access_level].nil? ? 5 : Config[keyword.to_sym][:access_level]
rescue NoMethodError
access_level = 5
end
self.commands = [] if self.commands.nil?
self.commands << {
:keyword => keyword,
:access_level => access_level,
:code => code
}
end
def unregister_command(keyword)
self.commands.reject! { |item| item[:keyword] == keyword }
end
# just a stub for now
def access_level(user, target)
99
end
def load_commands
self.commands = []
Dir.glob(File.dirname($0) + "/plugins/commands/*.rb") { |filename|
load filename
}
end
end
Client.load_commands
Client.register_trigger("PRIVMSG") { |msg|
# who sent the message
src_nick = msg[:prefix].split('!').first
# what was it
message = msg[:params][1]
# Was the message sent directly to us...
if msg[:params][0] == Config[:client][:nick] then
target = src_nick
reply_prefix = ""
# or to a channel (probably)
else
target = msg[:params][0]
reply_prefix = "#{src_nick}: "
end
# Did the message contain our nick with ":" "completion character"?
# If so, use the second word as a command and everything else as arguments
# array
if message.split.first == Config[:client][:nick] + ":" then
command = message.split[1]
arguments = message.split[2..-1]
else
if not message.split.first.nil? then
# did the message start with a :?
# If so, use everything after ":" from the first word as a command and
# all the other words as arguments array
if message.split.first[0] == ":" then
command = message.split.first[1..-1]
arguments = message.split[1..-1]
end
else
command = ""
arguments = ""
end
end
# don't do anything if there are no commands registered or this isn't a
# command call
Client.commands.each do |cmd|
# couldn't inline the if into second argument of Client.privmsg() call
if command.downcase == cmd[:keyword] then
next if cmd[:access_level] > Client.access_level(msg[:prefix], target)
retval = cmd[:code].call(arguments)
# if the command returned a String, we want to show it
Client.privmsg(target, reply_prefix + retval) if retval.instance_of? String
end
end if not ( Client.commands.nil? or command.nil? )
}