7 $debug = false unless $debug
8 $daemonize = false unless $daemonize
10 $dateformat = "%Y/%m/%d %H:%M:%S"
11 $logger = Logger.new($stderr)
12 $logger.datetime_format = $dateformat
13 $logger.level = $cl_loglevel if $cl_loglevel
14 $logger.level = 0 if $debug
16 def rawlog(level, message=nil, who_pos=1)
18 if call_stack.length > who_pos
19 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
23 # Output each line. To distinguish between separate messages and multi-line
24 # messages originating at the same time, we blank #{who} after the first message
26 message.to_s.each_line { |l|
27 $logger.add(level, l.chomp, who)
33 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
37 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
40 def debug(message=nil, who_pos=1)
41 rawlog(Logger::Severity::DEBUG, message, who_pos)
44 def log(message=nil, who_pos=1)
45 rawlog(Logger::Severity::INFO, message, who_pos)
48 def warning(message=nil, who_pos=1)
49 rawlog(Logger::Severity::WARN, message, who_pos)
52 def error(message=nil, who_pos=1)
53 rawlog(Logger::Severity::ERROR, message, who_pos)
56 def fatal(message=nil, who_pos=1)
57 rawlog(Logger::Severity::FATAL, message, who_pos)
62 warning "warning test"
66 # The following global is used for the improved signal handling.
70 require 'rbot/rbotconfig'
75 require 'rbot/rfc2812'
76 require 'rbot/ircsocket'
77 require 'rbot/botuser'
79 require 'rbot/plugins'
80 # require 'rbot/channel'
81 require 'rbot/message'
82 require 'rbot/language'
84 require 'rbot/registry'
85 require 'rbot/httputil'
89 # Main bot class, which manages the various components, receives messages,
90 # handles them or passes them to plugins, and contains core functionality.
92 # the bot's IrcAuth data
95 # the bot's BotConfig data
98 # the botclass for this bot (determines configdir among other things)
101 # used to perform actions periodically (saves configuration once per minute
105 # synchronize with this mutex while touching permanent data files:
106 # saving, flushing, cleaning up ...
107 attr_reader :save_mutex
109 # bot's Language data
116 # bot's object registry, plugins get an interface to this for persistant
117 # storage (hash interface tied to a bdb file, plugins use Accessors to store
118 # and restore objects in their own namespaces.)
119 attr_reader :registry
121 # bot's plugins. This is an instance of class Plugins
124 # bot's httputil help object, for fetching resources via http. Sets up
125 # proxies etc as defined by the bot configuration/environment
126 attr_reader :httputil
128 # server we are connected to
134 # bot User in the client/server connection
140 # bot User in the client/server connection
145 # create a new IrcBot with botclass +botclass+
146 def initialize(botclass, params = {})
147 # BotConfig for the core bot
148 # TODO should we split socket stuff into ircsocket, etc?
149 BotConfig.register BotConfigStringValue.new('server.name',
150 :default => "localhost", :requires_restart => true,
151 :desc => "What server should the bot connect to?",
153 BotConfig.register BotConfigIntegerValue.new('server.port',
154 :default => 6667, :type => :integer, :requires_restart => true,
155 :desc => "What port should the bot connect to?",
156 :validate => Proc.new {|v| v > 0}, :wizard => true)
157 BotConfig.register BotConfigBooleanValue.new('server.ssl',
158 :default => false, :requires_restart => true, :wizard => true,
159 :desc => "Use SSL to connect to this server?")
160 BotConfig.register BotConfigStringValue.new('server.password',
161 :default => false, :requires_restart => true,
162 :desc => "Password for connecting to this server (if required)",
164 BotConfig.register BotConfigStringValue.new('server.bindhost',
165 :default => false, :requires_restart => true,
166 :desc => "Specific local host or IP for the bot to bind to (if required)",
168 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
169 :default => 5, :validate => Proc.new{|v| v >= 0},
170 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
171 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
172 :default => 2.0, :validate => Proc.new{|v| v >= 0},
173 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
174 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
175 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
176 :default => 4, :validate => Proc.new{|v| v >= 0},
177 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
178 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
179 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
180 :default => 30, :validate => Proc.new{|v| v >= 0},
181 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
183 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
184 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
185 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
186 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
187 :requires_restart => true,
188 :desc => "local user the bot should appear to be", :wizard => true)
189 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
190 :default => [], :wizard => true,
191 :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'")
192 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
194 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
196 BotConfig.register BotConfigIntegerValue.new('core.save_every',
197 :default => 60, :validate => Proc.new{|v| v >= 0},
198 # TODO change timer via on_change proc
199 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
201 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
202 :default => false, :requires_restart => true,
203 :desc => "Should the bot run as a daemon?")
205 BotConfig.register BotConfigStringValue.new('log.file',
206 :default => false, :requires_restart => true,
207 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
208 BotConfig.register BotConfigIntegerValue.new('log.level',
209 :default => 1, :requires_restart => false,
210 :validate => Proc.new { |v| (0..5).include?(v) },
211 :on_change => Proc.new { |bot, v|
214 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
215 BotConfig.register BotConfigIntegerValue.new('log.keep',
216 :default => 1, :requires_restart => true,
217 :validate => Proc.new { |v| v >= 0 },
218 :desc => "How many old console messages logfiles to keep")
219 BotConfig.register BotConfigIntegerValue.new('log.max_size',
220 :default => 10, :requires_restart => true,
221 :validate => Proc.new { |v| v > 0 },
222 :desc => "Maximum console messages logfile size (in megabytes)")
224 @argv = params[:argv]
226 unless FileTest.directory? Config::coredir
227 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
231 unless FileTest.directory? Config::datadir
232 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
236 unless botclass and not botclass.empty?
237 # We want to find a sensible default.
238 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
239 # * On Windows (at least the NT versions) we want to put our stuff in the
240 # Application Data folder.
241 # We don't use any particular O/S detection magic, exploiting the fact that
242 # Etc.getpwuid is nil on Windows
243 if Etc.getpwuid(Process::Sys.geteuid)
244 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
246 if ENV.has_key?('APPDATA')
247 botclass = ENV['APPDATA'].dup
248 botclass.gsub!("\\","/")
253 botclass = File.expand_path(botclass)
254 @botclass = botclass.gsub(/\/$/, "")
256 unless FileTest.directory? botclass
257 log "no #{botclass} directory found, creating from templates.."
258 if FileTest.exist? botclass
259 error "file #{botclass} exists but isn't a directory"
262 FileUtils.cp_r Config::datadir+'/templates', botclass
265 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
266 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
267 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
268 Utils.set_safe_save_dir("#{botclass}/safe_save")
270 # Time at which the last PING was sent
272 # Time at which the last line was RECV'd from the server
275 @startup_time = Time.new
278 @config = BotConfig.configmanager
279 @config.bot_associate(self)
282 fatal e.backtrace.join("\n")
287 if @config['core.run_as_daemon']
291 @logfile = @config['log.file']
292 if @logfile.class!=String || @logfile.empty?
293 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
296 # See http://blog.humlab.umu.se/samuel/archives/000107.html
297 # for the backgrounding code
303 rescue NotImplementedError
304 warning "Could not background, fork not supported"
306 warning "Could not background. #{e.inspect}"
309 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
310 log "Redirecting standard input/output/error"
312 STDIN.reopen "/dev/null"
314 # On Windows, there's not such thing as /dev/null
317 def STDOUT.write(str=nil)
319 return str.to_s.length
321 def STDERR.write(str=nil)
322 if str.to_s.match(/:\d+: warning:/)
327 return str.to_s.length
331 # Set the new logfile and loglevel. This must be done after the daemonizing
332 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
333 $logger.datetime_format= $dateformat
334 $logger.level = @config['log.level']
335 $logger.level = $cl_loglevel if $cl_loglevel
336 $logger.level = 0 if $debug
340 @registry = BotRegistry.new self
342 @timer = Timer::Timer.new(1.0) # only need per-second granularity
343 @save_mutex = Mutex.new
344 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
345 @quit_mutex = Mutex.new
349 @httputil = Utils::HttpUtil.new(self)
352 @lang = Language::Language.new(self, @config['core.language'])
355 @auth = Auth::authmanager
356 @auth.bot_associate(self)
357 # @auth.load("#{botclass}/botusers.yaml")
360 fatal e.backtrace.join("\n")
364 @auth.everyone.set_default_permission("*", true)
365 @auth.botowner.password= @config['auth.password']
367 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
368 @plugins = Plugins::pluginmanager
369 @plugins.bot_associate(self)
370 @plugins.add_botmodule_dir(Config::coredir)
371 @plugins.add_botmodule_dir("#{botclass}/plugins")
372 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
375 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
376 @client = IrcClient.new
377 myself.nick = @config['irc.nick']
379 # Channels where we are quiet
380 # It's nil when we are not quiet, an empty list when we are quiet
381 # in all channels, a list of channels otherwise
384 @client[:welcome] = proc {|data|
385 irclog "joined server #{@client.server} as #{myself}", "server"
387 @plugins.delegate("connect")
389 @config['irc.join_channels'].each { |c|
390 debug "autojoining channel #{c}"
391 if(c =~ /^(\S+)\s+(\S+)$/i)
398 @client[:isupport] = proc { |data|
399 # TODO this needs to go into rfc2812.rb
400 # Since capabs are two-steps processes, server.supports[:capab]
401 # should be a three-state: nil, [], [....]
402 sendq "CAPAB IDENTIFY-MSG" if server.supports[:capab]
404 @client[:datastr] = proc { |data|
405 # TODO this needs to go into rfc2812.rb
406 if data[:text] == "IDENTIFY-MSG"
407 server.capabilities["identify-msg".to_sym] = true
409 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
412 @client[:privmsg] = proc { |data|
413 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
414 # debug "Message source is #{data[:source].inspect}"
415 # debug "Message target is #{data[:target].inspect}"
416 # debug "Bot is #{myself.inspect}"
418 # TODO use the new Netmask class
419 # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
423 @plugins.delegate "listen", m
424 @plugins.privmsg(m) if m.address?
426 @client[:notice] = proc { |data|
427 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
428 # pass it off to plugins that want to hear everything
429 @plugins.delegate "listen", message
431 @client[:motd] = proc { |data|
432 data[:motd].each_line { |line|
433 irclog "MOTD: #{line}", "server"
436 @client[:nicktaken] = proc { |data|
437 nickchg "#{data[:nick]}_"
438 @plugins.delegate "nicktaken", data[:nick]
440 @client[:badnick] = proc {|data|
441 warning "bad nick (#{data[:nick]})"
443 @client[:ping] = proc {|data|
444 sendq "PONG #{data[:pingid]}"
446 @client[:pong] = proc {|data|
449 @client[:nick] = proc {|data|
450 source = data[:source]
453 m = NickMessage.new(self, server, source, old, new)
455 debug "my nick is now #{new}"
457 data[:is_on].each { |ch|
458 irclog "@ #{old} is now known as #{new}", ch
460 @plugins.delegate("listen", m)
461 @plugins.delegate("nick", m)
463 @client[:quit] = proc {|data|
464 source = data[:source]
465 message = data[:message]
466 m = QuitMessage.new(self, server, source, source, message)
467 data[:was_on].each { |ch|
468 irclog "@ Quit: #{source}: #{message}", ch
470 @plugins.delegate("listen", m)
471 @plugins.delegate("quit", m)
473 @client[:mode] = proc {|data|
474 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
476 @client[:join] = proc {|data|
477 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
480 @plugins.delegate("listen", m)
481 @plugins.delegate("join", m)
483 @client[:part] = proc {|data|
484 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
487 @plugins.delegate("listen", m)
488 @plugins.delegate("part", m)
490 @client[:kick] = proc {|data|
491 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
494 @plugins.delegate("listen", m)
495 @plugins.delegate("kick", m)
497 @client[:invite] = proc {|data|
498 if data[:target] == myself
499 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
502 @client[:changetopic] = proc {|data|
503 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
506 @plugins.delegate("listen", m)
507 @plugins.delegate("topic", m)
509 @client[:topic] = proc { |data|
510 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
512 @client[:topicinfo] = proc { |data|
513 channel = data[:channel]
514 topic = channel.topic
515 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
516 m = TopicMessage.new(self, server, data[:source], channel, topic)
518 @plugins.delegate("listen", m)
519 @plugins.delegate("topic", m)
521 @client[:names] = proc { |data|
522 @plugins.delegate "names", data[:channel], data[:users]
524 @client[:unknown] = proc { |data|
525 #debug "UNKNOWN: #{data[:serverstring]}"
526 irclog data[:serverstring], ".unknown"
530 # checks if we should be quiet on a channel
531 def quiet_on?(channel)
532 return false unless @quiet
533 return true if @quiet.empty?
534 return @quiet.include?(channel.to_s)
537 def set_quiet(channel=nil)
539 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
545 def reset_quiet(channel=nil)
547 @quiet.delete_if { |x| x == channel.to_s }
553 # things to do when we receive a signal
555 debug "received #{sig}, queueing quit"
557 quit unless @quit_mutex.locked?
558 debug "interrupted #{$interrupted} times"
566 # connect the bot to IRC
569 trap("SIGINT") { got_sig("SIGINT") }
570 trap("SIGTERM") { got_sig("SIGTERM") }
571 trap("SIGHUP") { got_sig("SIGHUP") }
572 rescue ArgumentError => e
573 debug "failed to trap signals (#{e.inspect}): running on Windows?"
575 debug "failed to trap signals: #{e.inspect}"
578 quit if $interrupted > 0
581 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
583 quit if $interrupted > 0
584 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
585 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
586 quit if $interrupted > 0
589 # begin event handling loop
593 quit if $interrupted > 0
597 while @socket.connected?
598 quit if $interrupted > 0
600 # Wait for messages and process them as they arrive. If nothing is
601 # received, we call the ping_server() method that will PING the
602 # server if appropriate, or raise a TimeoutError if no PONG has been
603 # received in the user-chosen timeout since the last PING sent.
605 break unless reply = @socket.gets
607 @client.process reply
613 # I despair of this. Some of my users get "connection reset by peer"
614 # exceptions that ARENT SocketError's. How am I supposed to handle
619 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
620 error "network exception: #{e.class}: #{e}"
621 debug e.backtrace.join("\n")
622 rescue BDB::Fatal => e
623 fatal "fatal bdb error: #{e.class}: #{e}"
624 fatal e.backtrace.join("\n")
626 # Why restart? DB problems are serious stuff ...
627 # restart("Oops, we seem to have registry problems ...")
630 rescue Exception => e
631 error "non-net exception: #{e.class}: #{e}"
632 error e.backtrace.join("\n")
634 fatal "unexpected exception: #{e.class}: #{e}"
635 fatal e.backtrace.join("\n")
642 if @socket.connected?
649 quit if $interrupted > 0
651 log "waiting to reconnect"
652 sleep @config['server.reconnect_wait']
656 # type:: message type
657 # where:: message target
658 # message:: message text
659 # send message +message+ of type +type+ to target +where+
660 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
661 # relevant say() or notice() methods. This one should be used for IRCd
662 # extensions you want to use in modules.
663 def sendmsg(type, where, message, chan=nil, ring=0)
664 # Split the message so that each line sent is not longher than 400 bytes
665 # TODO allow something to do for commands that produce too many messages
666 # TODO example: math 10**10000
667 # TODO try to use the maximum line length allowed by the server, if there is
668 # a way to know what it is
669 left = 400 - type.length - where.to_s.length - 3
671 if(left >= message.length)
672 sendq "#{type} #{where} :#{message}", chan, ring
673 log_sent(type, where, message)
676 line = message.slice!(0, left)
677 lastspace = line.rindex(/\s+/)
679 message = line.slice!(lastspace, line.length) + message
680 message.gsub!(/^\s+/, "")
682 sendq "#{type} #{where} :#{line}", chan, ring
683 log_sent(type, where, line)
684 end while(message.length > 0)
687 # queue an arbitraty message for the server
688 def sendq(message="", chan=nil, ring=0)
690 @socket.queue(message, chan, ring)
693 # send a notice message to channel/nick +where+
694 def notice(where, message, mchan="", mring=-1)
710 message.each_line { |line|
712 next unless(line.length > 0)
713 sendmsg "NOTICE", where, line, chan, ring
717 # say something (PRIVMSG) to channel/nick +where+
718 def say(where, message, mchan="", mring=-1)
734 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
736 next unless(line.length > 0)
737 unless quiet_on?(where)
738 sendmsg "PRIVMSG", where, line, chan, ring
743 # perform a CTCP action with message +message+ to channel/nick +where+
744 def action(where, message, mchan="", mring=-1)
760 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
763 irclog "* #{myself} #{message}", where
765 irclog "* #{myself}[#{where}] #{message}", where
769 # quick way to say "okay" (or equivalent) to +where+
771 say where, @lang.get("okay")
774 # log IRC-related message +message+ to a file determined by +where+.
775 # +where+ can be a channel name, or a nick for private message logging
776 def irclog(message, where="server")
777 message = message.chomp
778 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
779 where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
780 unless(@logs.has_key?(where))
781 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
782 @logs[where].sync = true
784 @logs[where].puts "[#{stamp}] #{message}"
785 #debug "[#{stamp}] <#{where}> #{message}"
788 # set topic of channel +where+ to +topic+
789 def topic(where, topic)
790 sendq "TOPIC #{where} :#{topic}", where, 2
793 # disconnect from the server and cleanup all plugins and modules
794 def shutdown(message = nil)
795 @quit_mutex.synchronize do
796 debug "Shutting down ..."
797 ## No we don't restore them ... let everything run through
799 # trap("SIGINT", "DEFAULT")
800 # trap("SIGTERM", "DEFAULT")
801 # trap("SIGHUP", "DEFAULT")
803 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
805 message = @lang.get("quit") if (message.nil? || message.empty?)
806 if @socket.connected?
807 debug "Clearing socket"
809 debug "Sending quit message"
810 @socket.emergency_puts "QUIT :#{message}"
811 debug "Flushing socket"
813 debug "Shutting down socket"
816 debug "Logging quits"
817 server.channels.each { |ch|
818 irclog "@ quit (#{message})", ch
823 @save_mutex.synchronize do
826 # debug "Closing registries"
828 debug "Cleaning up the db environment"
830 log "rbot quit (#{message})"
834 # message:: optional IRC quit message
835 # quit IRC, shutdown the bot
836 def quit(message=nil)
844 # totally shutdown and respawn the bot
845 def restart(message = false)
846 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
848 sleep @config['server.reconnect_wait']
850 # Note, this fails on Windows
854 # call the save method for all of the botmodules
856 @save_mutex.synchronize do
862 # call the rescan method for all of the botmodules
864 @save_mutex.synchronize do
870 # channel:: channel to join
871 # key:: optional channel key if channel is +s
873 def join(channel, key=nil)
875 sendq "JOIN #{channel} :#{key}", channel, 2
877 sendq "JOIN #{channel}", channel, 2
882 def part(channel, message="")
883 sendq "PART #{channel} :#{message}", channel, 2
886 # attempt to change bot's nick to +name+
892 def mode(channel, mode, target)
893 sendq "MODE #{channel} #{mode} #{target}", channel, 2
897 def kick(channel, user, msg)
898 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
901 # m:: message asking for help
902 # topic:: optional topic help is requested for
903 # respond to online help requests
905 topic = nil if topic == ""
908 helpstr = "help topics: "
909 helpstr += @plugins.helptopics
910 helpstr += " (help <topic> for more info)"
912 unless(helpstr = @plugins.help(topic))
913 helpstr = "no help for topic #{topic}"
919 # returns a string describing the current status of the bot (uptime etc)
921 secs_up = Time.new - @startup_time
922 uptime = Utils.secs_to_string secs_up
923 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
924 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
927 # We want to respond to a hung server in a timely manner. If nothing was received
928 # in the user-selected timeout and we haven't PINGed the server yet, we PING
929 # the server. If the PONG is not received within the user-defined timeout, we
930 # assume we're in ping timeout and act accordingly.
932 act_timeout = @config['server.ping_timeout']
933 return if act_timeout <= 0
935 if @last_rec && now > @last_rec + act_timeout
937 # No previous PING pending, send a new one
939 @last_ping = Time.now
941 diff = now - @last_ping
942 if diff > act_timeout
943 debug "no PONG from server in #{diff} seconds, reconnecting"
944 # the actual reconnect is handled in the main loop:
945 raise TimeoutError, "no PONG from server in #{diff} seconds"
951 def stop_server_pings
952 # cancel previous PINGs and reset time of last RECV
962 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
964 irclog "* #{m.sourcenick} #{m.message}", m.target
968 irclog "<#{m.sourcenick}> #{m.message}", m.target
970 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
975 # log a message. Internal use only.
976 def log_sent(type, where, message)
981 irclog "-=#{myself}=- #{message}", where
983 irclog "[-=#{where}=-] #{message}", where
988 irclog "<#{myself}> #{message}", where
990 irclog "[msg(#{where})] #{message}", where
997 debug "joined channel #{m.channel}"
998 irclog "@ Joined channel #{m.channel}", m.channel
1000 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1006 debug "left channel #{m.channel}"
1007 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1009 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1015 debug "kicked from channel #{m.channel}"
1016 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1018 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1023 if m.source == myself
1024 irclog "@ I set topic \"#{m.topic}\"", m.channel
1026 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel