5 $debug = false unless $debug
6 # print +message+ if debugging is enabled
9 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
10 message.to_s.each_line { |l|
11 $stdout.puts "D: [#{stamp}] #{l}"
18 # The following global is used for the improved signal handling.
22 require 'rbot/rbotconfig'
26 require 'rbot/rfc2812'
27 require 'rbot/keywords'
28 require 'rbot/ircsocket'
31 require 'rbot/plugins'
32 require 'rbot/channel'
33 require 'rbot/message'
34 require 'rbot/language'
36 require 'rbot/registry'
37 require 'rbot/httputil'
41 # Main bot class, which manages the various components, receives messages,
42 # handles them or passes them to plugins, and contains core functionality.
44 # the bot's current nickname
47 # the bot's IrcAuth data
50 # the bot's BotConfig data
53 # the botclass for this bot (determines configdir among other things)
56 # used to perform actions periodically (saves configuration once per minute
63 # channel info for channels the bot is in
69 # bot's object registry, plugins get an interface to this for persistant
70 # storage (hash interface tied to a bdb file, plugins use Accessors to store
71 # and restore objects in their own namespaces.)
74 # bot's httputil help object, for fetching resources via http. Sets up
75 # proxies etc as defined by the bot configuration/environment
78 # create a new IrcBot with botclass +botclass+
79 def initialize(botclass, params = {})
80 # BotConfig for the core bot
81 # TODO should we split socket stuff into ircsocket, etc?
82 BotConfig.register BotConfigStringValue.new('server.name',
83 :default => "localhost", :requires_restart => true,
84 :desc => "What server should the bot connect to?",
86 BotConfig.register BotConfigIntegerValue.new('server.port',
87 :default => 6667, :type => :integer, :requires_restart => true,
88 :desc => "What port should the bot connect to?",
89 :validate => Proc.new {|v| v > 0}, :wizard => true)
90 BotConfig.register BotConfigStringValue.new('server.password',
91 :default => false, :requires_restart => true,
92 :desc => "Password for connecting to this server (if required)",
94 BotConfig.register BotConfigStringValue.new('server.bindhost',
95 :default => false, :requires_restart => true,
96 :desc => "Specific local host or IP for the bot to bind to (if required)",
98 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
99 :default => 5, :validate => Proc.new{|v| v >= 0},
100 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
101 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
102 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
103 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
104 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
105 :requires_restart => true,
106 :desc => "local user the bot should appear to be", :wizard => true)
107 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
108 :default => [], :wizard => true,
109 :desc => "What channels the bot should always join at startup. List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'")
110 BotConfig.register BotConfigIntegerValue.new('core.save_every',
111 :default => 60, :validate => Proc.new{|v| v >= 0},
112 # TODO change timer via on_change proc
113 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example")
114 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
115 :default => 2.0, :validate => Proc.new{|v| v >= 0},
116 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
117 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
118 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
119 :default => 4, :validate => Proc.new{|v| v >= 0},
120 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
121 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
122 BotConfig.register BotConfigStringValue.new('server.byterate',
123 :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
124 :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
125 :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
126 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
127 :default => 10, :validate => Proc.new{|v| v >= 0},
128 :on_change => Proc.new {|bot, v| bot.start_server_pings},
129 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
131 @argv = params[:argv]
133 unless FileTest.directory? Config::datadir
134 puts "data directory '#{Config::datadir}' not found, did you setup.rb?"
138 botclass = "#{Etc.getpwuid(Process::Sys.geteuid)[:dir]}/.rbot" unless botclass
139 #botclass = "#{ENV['HOME']}/.rbot" unless botclass
140 botclass = File.expand_path(botclass)
141 @botclass = botclass.gsub(/\/$/, "")
143 unless FileTest.directory? botclass
144 puts "no #{botclass} directory found, creating from templates.."
145 if FileTest.exist? botclass
146 puts "Error: file #{botclass} exists but isn't a directory"
149 FileUtils.cp_r Config::datadir+'/templates', botclass
152 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
153 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
158 @startup_time = Time.new
159 @config = BotConfig.new(self)
160 # TODO background self after botconfig has a chance to run wizard
161 @timer = Timer::Timer.new(1.0) # only need per-second granularity
162 @registry = BotRegistry.new self
163 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
166 @httputil = Utils::HttpUtil.new(self)
167 @lang = Language::Language.new(@config['core.language'])
168 @keywords = Keywords.new(self)
169 @auth = IrcAuth.new(self)
171 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
172 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
174 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
175 @nick = @config['irc.nick']
177 @client = IrcClient.new
178 @client[:privmsg] = proc { |data|
179 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
182 @client[:notice] = proc { |data|
183 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
184 # pass it off to plugins that want to hear everything
185 @plugins.delegate "listen", message
187 @client[:motd] = proc { |data|
188 data[:motd].each_line { |line|
189 log "MOTD: #{line}", "server"
192 @client[:nicktaken] = proc { |data|
193 nickchg "#{data[:nick]}_"
194 @plugins.delegate "nicktaken", data[:nick]
196 @client[:badnick] = proc {|data|
197 puts "WARNING, bad nick (#{data[:nick]})"
199 @client[:ping] = proc {|data|
200 # (jump the queue for pongs)
201 @socket.puts "PONG #{data[:pingid]}"
203 @client[:pong] = proc {|data|
206 @client[:nick] = proc {|data|
207 sourcenick = data[:sourcenick]
209 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
210 if(sourcenick == @nick)
211 debug "my nick is now #{nick}"
214 @channels.each {|k,v|
215 if(v.users.has_key?(sourcenick))
216 log "@ #{sourcenick} is now known as #{nick}", k
217 v.users[nick] = v.users[sourcenick]
218 v.users.delete(sourcenick)
221 @plugins.delegate("listen", m)
222 @plugins.delegate("nick", m)
224 @client[:quit] = proc {|data|
225 source = data[:source]
226 sourcenick = data[:sourcenick]
227 sourceurl = data[:sourceaddress]
228 message = data[:message]
229 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
230 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
232 @channels.each {|k,v|
233 if(v.users.has_key?(sourcenick))
234 log "@ Quit: #{sourcenick}: #{message}", k
235 v.users.delete(sourcenick)
239 @plugins.delegate("listen", m)
240 @plugins.delegate("quit", m)
242 @client[:mode] = proc {|data|
243 source = data[:source]
244 sourcenick = data[:sourcenick]
245 sourceurl = data[:sourceaddress]
246 channel = data[:channel]
247 targets = data[:targets]
248 modestring = data[:modestring]
249 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
251 @client[:welcome] = proc {|data|
252 log "joined server #{data[:source]} as #{data[:nick]}", "server"
253 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
254 if data[:nick] && data[:nick].length > 0
258 @plugins.delegate("connect")
260 @config['irc.join_channels'].each {|c|
261 debug "autojoining channel #{c}"
262 if(c =~ /^(\S+)\s+(\S+)$/i)
269 @client[:join] = proc {|data|
270 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
273 @client[:part] = proc {|data|
274 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
277 @client[:kick] = proc {|data|
278 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
281 @client[:invite] = proc {|data|
282 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
283 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
286 @client[:changetopic] = proc {|data|
287 channel = data[:channel]
288 sourcenick = data[:sourcenick]
290 timestamp = data[:unixtime] || Time.now.to_i
291 if(sourcenick == @nick)
292 log "@ I set topic \"#{topic}\"", channel
294 log "@ #{sourcenick} set topic \"#{topic}\"", channel
296 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
299 @plugins.delegate("listen", m)
300 @plugins.delegate("topic", m)
302 @client[:topic] = @client[:topicinfo] = proc {|data|
303 channel = data[:channel]
304 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
307 @client[:names] = proc {|data|
308 channel = data[:channel]
310 unless(@channels[channel])
311 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
314 @channels[channel].users.clear
316 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
318 @plugins.delegate "names", data[:channel], data[:users]
320 @client[:unknown] = proc {|data|
321 #debug "UNKNOWN: #{data[:serverstring]}"
322 log data[:serverstring], ".unknown"
327 debug "received #{sig}, queueing quit"
329 debug "interrupted #{$interrupted} times"
333 elsif $interrupted >= 3
339 # connect the bot to IRC
342 trap("SIGINT") { got_sig("SIGINT") }
343 trap("SIGTERM") { got_sig("SIGTERM") }
344 trap("SIGHUP") { got_sig("SIGHUP") }
346 debug "failed to trap signals: #{e.inspect}\nProbably running on windows?"
351 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
353 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
354 @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
358 # begin event handling loop
365 while @socket.connected?
367 break unless reply = @socket.gets
368 @client.process reply
370 quit if $interrupted > 0
373 # I despair of this. Some of my users get "connection reset by peer"
374 # exceptions that ARENT SocketError's. How am I supposed to handle
378 rescue TimeoutError, SocketError => e
379 puts "network exception: #{e.class}: #{e}"
381 debug e.backtrace.join("\n")
382 rescue BDB::Fatal => e
383 puts "fatal bdb error: #{e.class}: #{e}"
385 debug e.backtrace.join("\n")
387 restart("Oops, we seem to have registry problems ...")
388 rescue Exception => e
389 puts "non-net exception: #{e.class}: #{e}"
391 debug e.backtrace.join("\n")
392 @socket.shutdown # now we reconnect
394 puts "unexpected exception: connection closed: #{e.inspect}"
395 puts e.backtrace.join("\n")
405 puts "waiting to reconnect"
406 sleep @config['server.reconnect_wait']
410 # type:: message type
411 # where:: message target
412 # message:: message text
413 # send message +message+ of type +type+ to target +where+
414 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
415 # relevant say() or notice() methods. This one should be used for IRCd
416 # extensions you want to use in modules.
417 def sendmsg(type, where, message)
418 # limit it according to the byterate, splitting the message
419 # taking into consideration the actual message length
420 # and all the extra stuff
421 # TODO allow something to do for commands that produce too many messages
422 # TODO example: math 10**10000
423 left = @socket.bytes_per - type.length - where.length - 4
425 if(left >= message.length)
426 sendq("#{type} #{where} :#{message}")
427 log_sent(type, where, message)
430 line = message.slice!(0, left)
431 lastspace = line.rindex(/\s+/)
433 message = line.slice!(lastspace, line.length) + message
434 message.gsub!(/^\s+/, "")
436 sendq("#{type} #{where} :#{line}")
437 log_sent(type, where, line)
438 end while(message.length > 0)
441 # queue an arbitraty message for the server
442 def sendq(message="")
444 @socket.queue(message)
447 # send a notice message to channel/nick +where+
448 def notice(where, message)
449 message.each_line { |line|
451 next unless(line.length > 0)
452 sendmsg("NOTICE", where, line)
456 # say something (PRIVMSG) to channel/nick +where+
457 def say(where, message)
458 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
460 next unless(line.length > 0)
461 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
462 sendmsg("PRIVMSG", where, line)
467 # perform a CTCP action with message +message+ to channel/nick +where+
468 def action(where, message)
469 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
471 log "* #{@nick} #{message}", where
472 elsif (where =~ /^(\S*)!.*$/)
473 log "* #{@nick}[#{where}] #{message}", $1
475 log "* #{@nick}[#{where}] #{message}", where
479 # quick way to say "okay" (or equivalent) to +where+
481 say where, @lang.get("okay")
484 # log message +message+ to a file determined by +where+. +where+ can be a
485 # channel name, or a nick for private message logging
486 def log(message, where="server")
487 message = message.chomp
488 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
489 where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
490 unless(@logs.has_key?(where))
491 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
492 @logs[where].sync = true
494 @logs[where].puts "[#{stamp}] #{message}"
495 #debug "[#{stamp}] <#{where}> #{message}"
498 # set topic of channel +where+ to +topic+
499 def topic(where, topic)
500 sendq "TOPIC #{where} :#{topic}"
503 # disconnect from the server and cleanup all plugins and modules
504 def shutdown(message = nil)
505 debug "Shutting down ..."
506 ## No we don't restore them ... let everything run through
508 # trap("SIGINT", "DEFAULT")
509 # trap("SIGTERM", "DEFAULT")
510 # trap("SIGHUP", "DEFAULT")
512 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
514 message = @lang.get("quit") if (message.nil? || message.empty?)
515 if @socket.connected?
516 debug "Clearing socket"
518 debug "Sending quit message"
519 @socket.puts "QUIT :#{message}"
520 debug "Flushing socket"
522 debug "Shutting down socket"
525 debug "Logging quits"
526 @channels.each_value {|v|
527 log "@ quit (#{message})", v.name
533 # debug "Closing registries"
535 debug "Cleaning up the db environment"
537 puts "rbot quit (#{message})"
540 # message:: optional IRC quit message
541 # quit IRC, shutdown the bot
542 def quit(message=nil)
550 # totally shutdown and respawn the bot
551 def restart(message = false)
552 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
554 sleep @config['server.reconnect_wait']
556 # Note, this fails on Windows
560 # call the save method for bot's config, keywords, auth and all plugins
569 # call the rescan method for the bot's lang, keywords and all plugins
576 # channel:: channel to join
577 # key:: optional channel key if channel is +s
579 def join(channel, key=nil)
581 sendq "JOIN #{channel} :#{key}"
583 sendq "JOIN #{channel}"
588 def part(channel, message="")
589 sendq "PART #{channel} :#{message}"
592 # attempt to change bot's nick to +name+
598 def mode(channel, mode, target)
599 sendq "MODE #{channel} #{mode} #{target}"
602 # m:: message asking for help
603 # topic:: optional topic help is requested for
604 # respond to online help requests
606 topic = nil if topic == ""
609 helpstr = "help topics: core, auth, keywords"
610 helpstr += @plugins.helptopics
611 helpstr += " (help <topic> for more info)"
614 when /^core\s+(.+)$/i
615 helpstr = corehelp $1
618 when /^auth\s+(.+)$/i
619 helpstr = @auth.help $1
621 helpstr = @keywords.help
622 when /^keywords\s+(.+)$/i
623 helpstr = @keywords.help $1
625 unless(helpstr = @plugins.help(topic))
626 helpstr = "no help for topic #{topic}"
632 # returns a string describing the current status of the bot (uptime etc)
634 secs_up = Time.new - @startup_time
635 uptime = Utils.secs_to_string secs_up
636 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
637 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
640 # we'll ping the server every 30 seconds or so, and expect a response
641 # before the next one come around..
642 def start_server_pings
644 return unless @config['server.ping_timeout'] > 0
645 # we want to respond to a hung server within 30 secs or so
646 @ping_timer = @timer.add(30) {
647 @last_ping = Time.now
648 @socket.puts "PING :rbot"
650 @pong_timer = @timer.add(10) {
651 unless @last_ping.nil?
652 diff = Time.now - @last_ping
653 unless diff < @config['server.ping_timeout']
654 debug "no PONG from server for #{diff} seconds, reconnecting"
658 debug "couldn't shutdown connection (already shutdown?)"
661 raise TimeoutError, "no PONG from server in #{diff} seconds"
667 def stop_server_pings
669 # stop existing timers if running
670 unless @ping_timer.nil?
671 @timer.remove @ping_timer
674 unless @pong_timer.nil?
675 @timer.remove @pong_timer
682 # handle help requests for "core" topics
683 def corehelp(topic="")
686 return "quit [<message>] => quit IRC with message <message>"
688 return "restart => completely stop and restart the bot (including reconnect)"
690 return "join <channel> [<key>] => join channel <channel> with secret key <key> if specified. #{@nick} also responds to invites if you have the required access level"
692 return "part <channel> => part channel <channel>"
694 return "hide => part all channels"
696 return "save => save current dynamic data and configuration"
698 return "rescan => reload modules and static facts"
700 return "nick <nick> => attempt to change nick to <nick>"
702 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
704 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
706 # return "topic <channel> <message> => set topic of <channel> to <message>"
708 return "quiet [in here|<channel>] => with no arguments, stop speaking in all channels, if \"in here\", stop speaking in this channel, or stop speaking in <channel>"
710 return "talk [in here|<channel>] => with no arguments, resume speaking in all channels, if \"in here\", resume speaking in this channel, or resume speaking in <channel>"
712 return "version => describes software version"
714 return "botsnack => reward #{@nick} for being good"
716 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
718 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
722 # handle incoming IRC PRIVMSG +m+
727 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
729 log "* #{m.sourcenick} #{m.message}", m.target
733 log "<#{m.sourcenick}> #{m.message}", m.target
735 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
739 # pass it off to plugins that want to hear everything
740 @plugins.delegate "listen", m
742 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
743 notice m.sourcenick, "\001PING #$1\001"
744 log "@ #{m.sourcenick} pinged me"
751 when (/^join\s+(\S+)\s+(\S+)$/i)
752 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
753 when (/^join\s+(\S+)$/i)
754 join $1 if(@auth.allow?("join", m.source, m.replyto))
756 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
757 when (/^part\s+(\S+)$/i)
758 part $1 if(@auth.allow?("join", m.source, m.replyto))
759 when (/^quit(?:\s+(.*))?$/i)
760 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
761 when (/^restart(?:\s+(.*))?$/i)
762 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
764 join 0 if(@auth.allow?("join", m.source, m.replyto))
766 if(@auth.allow?("config", m.source, m.replyto))
770 when (/^nick\s+(\S+)$/i)
771 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
772 when (/^say\s+(\S+)\s+(.*)$/i)
773 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
774 when (/^action\s+(\S+)\s+(.*)$/i)
775 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
776 # when (/^topic\s+(\S+)\s+(.*)$/i)
777 # topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
778 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
779 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
781 say m.replyto, "pong"
783 if(@auth.allow?("config", m.source, m.replyto))
786 m.reply "Rescanning ..."
791 if(auth.allow?("talk", m.source, m.replyto))
793 @channels.each_value {|c| c.quiet = true }
795 when (/^quiet in (\S+)$/i)
797 if(auth.allow?("talk", m.source, m.replyto))
799 where.gsub!(/^here$/, m.target) if m.public?
800 @channels[where].quiet = true if(@channels.has_key?(where))
803 if(auth.allow?("talk", m.source, m.replyto))
804 @channels.each_value {|c| c.quiet = false }
807 when (/^talk in (\S+)$/i)
809 if(auth.allow?("talk", m.source, m.replyto))
810 where.gsub!(/^here$/, m.target) if m.public?
811 @channels[where].quiet = false if(@channels.has_key?(where))
814 when (/^status\??$/i)
815 m.reply status if auth.allow?("status", m.source, m.replyto)
816 when (/^registry stats$/i)
817 if auth.allow?("config", m.source, m.replyto)
818 m.reply @registry.stat.inspect
820 when (/^(help\s+)?config(\s+|$)/)
822 when (/^(version)|(introduce yourself)$/i)
823 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
824 when (/^help(?:\s+(.*))?$/i)
825 say m.replyto, help($1)
826 #TODO move these to a "chatback" plugin
827 when (/^(botsnack|ciggie)$/i)
828 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
829 say m.replyto, @lang.get("thanks") if(m.private?)
830 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
831 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
832 say m.replyto, @lang.get("hello") if(m.private?)
835 # stuff to handle when not addressed
837 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
838 say m.replyto, @lang.get("hello_X") % m.sourcenick
839 when (/^#{Regexp.escape(@nick)}!*$/)
840 say m.replyto, @lang.get("hello_X") % m.sourcenick
847 # log a message. Internal use only.
848 def log_sent(type, where, message)
852 log "-=#{@nick}=- #{message}", where
853 elsif (where =~ /(\S*)!.*/)
854 log "[-=#{where}=-] #{message}", $1
856 log "[-=#{where}=-] #{message}"
860 log "<#{@nick}> #{message}", where
861 elsif (where =~ /^(\S*)!.*$/)
862 log "[msg(#{where})] #{message}", $1
864 log "[msg(#{where})] #{message}", where
870 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
872 debug "joined channel #{m.channel}"
873 log "@ Joined channel #{m.channel}", m.channel
875 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
876 @channels[m.channel].users[m.sourcenick] = Hash.new
877 @channels[m.channel].users[m.sourcenick]["mode"] = ""
880 @plugins.delegate("listen", m)
881 @plugins.delegate("join", m)
886 debug "left channel #{m.channel}"
887 log "@ Left channel #{m.channel} (#{m.message})", m.channel
888 @channels.delete(m.channel)
890 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
891 if @channels.has_key?(m.channel)
892 @channels[m.channel].users.delete(m.sourcenick)
894 puts "bug: got part for channel '#{channel}' I didn't think I was in\n"
899 # delegate to plugins
900 @plugins.delegate("listen", m)
901 @plugins.delegate("part", m)
904 # respond to being kicked from a channel
907 debug "kicked from channel #{m.channel}"
908 @channels.delete(m.channel)
909 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
911 @channels[m.channel].users.delete(m.sourcenick)
912 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
915 @plugins.delegate("listen", m)
916 @plugins.delegate("kick", m)
920 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
921 @channels[m.channel].topic = m.topic if !m.topic.nil?
922 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
923 @channels[m.channel].topic.by = m.source if !m.source.nil?
925 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
928 # delegate a privmsg to auth, keyword or plugin handlers
929 def delegate_privmsg(message)
930 [@auth, @plugins, @keywords].each {|m|
931 break if m.privmsg(message)