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 :on_change => Proc.new { |bot, v|
201 @timer.reschedule(@save_timer, v)
202 @timer.unblock(@save_timer)
204 @timer.block(@save_timer)
208 @save_timer = @timer.add(v) { bot.save }
210 # Nothing to do when v == 0
213 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
215 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
216 :default => false, :requires_restart => true,
217 :desc => "Should the bot run as a daemon?")
219 BotConfig.register BotConfigStringValue.new('log.file',
220 :default => false, :requires_restart => true,
221 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
222 BotConfig.register BotConfigIntegerValue.new('log.level',
223 :default => 1, :requires_restart => false,
224 :validate => Proc.new { |v| (0..5).include?(v) },
225 :on_change => Proc.new { |bot, v|
228 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
229 BotConfig.register BotConfigIntegerValue.new('log.keep',
230 :default => 1, :requires_restart => true,
231 :validate => Proc.new { |v| v >= 0 },
232 :desc => "How many old console messages logfiles to keep")
233 BotConfig.register BotConfigIntegerValue.new('log.max_size',
234 :default => 10, :requires_restart => true,
235 :validate => Proc.new { |v| v > 0 },
236 :desc => "Maximum console messages logfile size (in megabytes)")
238 @argv = params[:argv]
240 unless FileTest.directory? Config::coredir
241 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
245 unless FileTest.directory? Config::datadir
246 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
250 unless botclass and not botclass.empty?
251 # We want to find a sensible default.
252 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
253 # * On Windows (at least the NT versions) we want to put our stuff in the
254 # Application Data folder.
255 # We don't use any particular O/S detection magic, exploiting the fact that
256 # Etc.getpwuid is nil on Windows
257 if Etc.getpwuid(Process::Sys.geteuid)
258 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
260 if ENV.has_key?('APPDATA')
261 botclass = ENV['APPDATA'].dup
262 botclass.gsub!("\\","/")
267 botclass = File.expand_path(botclass)
268 @botclass = botclass.gsub(/\/$/, "")
270 unless FileTest.directory? botclass
271 log "no #{botclass} directory found, creating from templates.."
272 if FileTest.exist? botclass
273 error "file #{botclass} exists but isn't a directory"
276 FileUtils.cp_r Config::datadir+'/templates', botclass
279 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
280 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
281 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
282 Utils.set_safe_save_dir("#{botclass}/safe_save")
284 # Time at which the last PING was sent
286 # Time at which the last line was RECV'd from the server
289 @startup_time = Time.new
292 @config = BotConfig.configmanager
293 @config.bot_associate(self)
296 fatal e.backtrace.join("\n")
301 if @config['core.run_as_daemon']
305 @logfile = @config['log.file']
306 if @logfile.class!=String || @logfile.empty?
307 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
310 # See http://blog.humlab.umu.se/samuel/archives/000107.html
311 # for the backgrounding code
317 rescue NotImplementedError
318 warning "Could not background, fork not supported"
320 warning "Could not background. #{e.inspect}"
323 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
324 log "Redirecting standard input/output/error"
326 STDIN.reopen "/dev/null"
328 # On Windows, there's not such thing as /dev/null
331 def STDOUT.write(str=nil)
333 return str.to_s.length
335 def STDERR.write(str=nil)
336 if str.to_s.match(/:\d+: warning:/)
341 return str.to_s.length
345 # Set the new logfile and loglevel. This must be done after the daemonizing
346 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
347 $logger.datetime_format= $dateformat
348 $logger.level = @config['log.level']
349 $logger.level = $cl_loglevel if $cl_loglevel
350 $logger.level = 0 if $debug
354 @registry = BotRegistry.new self
356 @timer = Timer::Timer.new(1.0) # only need per-second granularity
357 @save_mutex = Mutex.new
358 if @config['core.save_every'] > 0
359 @save_timer = @timer.add(@config['core.save_every']) { save }
363 @quit_mutex = Mutex.new
367 @httputil = Utils::HttpUtil.new(self)
370 @lang = Language::Language.new(self, @config['core.language'])
373 @auth = Auth::authmanager
374 @auth.bot_associate(self)
375 # @auth.load("#{botclass}/botusers.yaml")
378 fatal e.backtrace.join("\n")
382 @auth.everyone.set_default_permission("*", true)
383 @auth.botowner.password= @config['auth.password']
385 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
386 @plugins = Plugins::pluginmanager
387 @plugins.bot_associate(self)
388 @plugins.add_botmodule_dir(Config::coredir)
389 @plugins.add_botmodule_dir("#{botclass}/plugins")
390 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
393 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
394 @client = IrcClient.new
395 myself.nick = @config['irc.nick']
397 # Channels where we are quiet
398 # It's nil when we are not quiet, an empty list when we are quiet
399 # in all channels, a list of channels otherwise
402 @client[:welcome] = proc {|data|
403 irclog "joined server #{@client.server} as #{myself}", "server"
405 @plugins.delegate("connect")
407 @config['irc.join_channels'].each { |c|
408 debug "autojoining channel #{c}"
409 if(c =~ /^(\S+)\s+(\S+)$/i)
417 # TODO the next two @client should go into rfc2812.rb, probably
418 # Since capabs are two-steps processes, server.supports[:capab]
419 # should be a three-state: nil, [], [....]
420 asked_for = { :"identify-msg" => false }
421 @client[:isupport] = proc { |data|
422 if server.supports[:capab] and !asked_for[:"identify-msg"]
423 sendq "CAPAB IDENTIFY-MSG"
424 asked_for[:"identify-msg"] = true
427 @client[:datastr] = proc { |data|
428 if data[:text] == "IDENTIFY-MSG"
429 server.capabilities[:"identify-msg"] = true
431 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
435 @client[:privmsg] = proc { |data|
436 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
437 # debug "Message source is #{data[:source].inspect}"
438 # debug "Message target is #{data[:target].inspect}"
439 # debug "Bot is #{myself.inspect}"
442 @config['irc.ignore_users'].each { |mask|
443 if m.source.matches?(server.new_netmask(mask))
452 @plugins.delegate "listen", m
453 @plugins.privmsg(m) if m.address?
456 @client[:notice] = proc { |data|
457 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
458 # pass it off to plugins that want to hear everything
459 @plugins.delegate "listen", message
461 @client[:motd] = proc { |data|
462 data[:motd].each_line { |line|
463 irclog "MOTD: #{line}", "server"
466 @client[:nicktaken] = proc { |data|
467 nickchg "#{data[:nick]}_"
468 @plugins.delegate "nicktaken", data[:nick]
470 @client[:badnick] = proc {|data|
471 warning "bad nick (#{data[:nick]})"
473 @client[:ping] = proc {|data|
474 sendq "PONG #{data[:pingid]}"
476 @client[:pong] = proc {|data|
479 @client[:nick] = proc {|data|
480 source = data[:source]
483 m = NickMessage.new(self, server, source, old, new)
485 debug "my nick is now #{new}"
487 data[:is_on].each { |ch|
488 irclog "@ #{old} is now known as #{new}", ch
490 @plugins.delegate("listen", m)
491 @plugins.delegate("nick", m)
493 @client[:quit] = proc {|data|
494 source = data[:source]
495 message = data[:message]
496 m = QuitMessage.new(self, server, source, source, message)
497 data[:was_on].each { |ch|
498 irclog "@ Quit: #{source}: #{message}", ch
500 @plugins.delegate("listen", m)
501 @plugins.delegate("quit", m)
503 @client[:mode] = proc {|data|
504 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
506 @client[:join] = proc {|data|
507 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
510 @plugins.delegate("listen", m)
511 @plugins.delegate("join", m)
513 @client[:part] = proc {|data|
514 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
517 @plugins.delegate("listen", m)
518 @plugins.delegate("part", m)
520 @client[:kick] = proc {|data|
521 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
524 @plugins.delegate("listen", m)
525 @plugins.delegate("kick", m)
527 @client[:invite] = proc {|data|
528 if data[:target] == myself
529 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
532 @client[:changetopic] = proc {|data|
533 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
536 @plugins.delegate("listen", m)
537 @plugins.delegate("topic", m)
539 @client[:topic] = proc { |data|
540 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
542 @client[:topicinfo] = proc { |data|
543 channel = data[:channel]
544 topic = channel.topic
545 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
546 m = TopicMessage.new(self, server, data[:source], channel, topic)
548 @plugins.delegate("listen", m)
549 @plugins.delegate("topic", m)
551 @client[:names] = proc { |data|
552 @plugins.delegate "names", data[:channel], data[:users]
554 @client[:unknown] = proc { |data|
555 #debug "UNKNOWN: #{data[:serverstring]}"
556 irclog data[:serverstring], ".unknown"
560 # checks if we should be quiet on a channel
561 def quiet_on?(channel)
562 return false unless @quiet
563 return true if @quiet.empty?
564 return @quiet.include?(channel.to_s)
567 def set_quiet(channel=nil)
569 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
575 def reset_quiet(channel=nil)
577 @quiet.delete_if { |x| x == channel.to_s }
583 # things to do when we receive a signal
585 debug "received #{sig}, queueing quit"
587 quit unless @quit_mutex.locked?
588 debug "interrupted #{$interrupted} times"
596 # connect the bot to IRC
599 trap("SIGINT") { got_sig("SIGINT") }
600 trap("SIGTERM") { got_sig("SIGTERM") }
601 trap("SIGHUP") { got_sig("SIGHUP") }
602 rescue ArgumentError => e
603 debug "failed to trap signals (#{e.inspect}): running on Windows?"
605 debug "failed to trap signals: #{e.inspect}"
608 quit if $interrupted > 0
611 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
613 quit if $interrupted > 0
614 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
615 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
616 quit if $interrupted > 0
619 # begin event handling loop
623 quit if $interrupted > 0
627 while @socket.connected?
628 quit if $interrupted > 0
630 # Wait for messages and process them as they arrive. If nothing is
631 # received, we call the ping_server() method that will PING the
632 # server if appropriate, or raise a TimeoutError if no PONG has been
633 # received in the user-chosen timeout since the last PING sent.
635 break unless reply = @socket.gets
637 @client.process reply
643 # I despair of this. Some of my users get "connection reset by peer"
644 # exceptions that ARENT SocketError's. How am I supposed to handle
649 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
650 error "network exception: #{e.class}: #{e}"
651 debug e.backtrace.join("\n")
652 rescue BDB::Fatal => e
653 fatal "fatal bdb error: #{e.class}: #{e}"
654 fatal e.backtrace.join("\n")
656 # Why restart? DB problems are serious stuff ...
657 # restart("Oops, we seem to have registry problems ...")
660 rescue Exception => e
661 error "non-net exception: #{e.class}: #{e}"
662 error e.backtrace.join("\n")
664 fatal "unexpected exception: #{e.class}: #{e}"
665 fatal e.backtrace.join("\n")
672 if @socket.connected?
679 quit if $interrupted > 0
681 log "waiting to reconnect"
682 sleep @config['server.reconnect_wait']
686 # type:: message type
687 # where:: message target
688 # message:: message text
689 # send message +message+ of type +type+ to target +where+
690 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
691 # relevant say() or notice() methods. This one should be used for IRCd
692 # extensions you want to use in modules.
693 def sendmsg(type, where, message, chan=nil, ring=0)
694 # The IRC protocol requires that each raw message must be not longer
695 # than 512 characters. From this length with have to subtract the EOL
696 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
697 # that will be prepended by the server to all of our messages.
699 # The maximum raw message length we can send is therefore 512 - 2 - 2
700 # minus the length of our hostmask.
702 max_len = 508 - myself.fullform.length
704 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
705 # will have a + or - prepended
706 if server.capabilities[:"identify-msg"]
710 # When splitting the message, we'll be prefixing the following string:
711 # (e.g. "PRIVMSG #rbot :")
712 fixed = "#{type} #{where} :"
714 # And this is what's left
715 left = max_len - fixed.length
717 if(left >= message.length)
718 sendq "#{fixed}#{message}", chan, ring
719 log_sent(type, where, message)
722 line = message.slice!(0, left)
723 lastspace = line.rindex(/\s+/)
725 message = line.slice!(lastspace, line.length) + message
726 message.gsub!(/^\s+/, "")
728 sendq "#{fixed}#{line}", chan, ring
729 log_sent(type, where, line)
730 end while(message.length > 0)
733 # queue an arbitraty message for the server
734 def sendq(message="", chan=nil, ring=0)
736 @socket.queue(message, chan, ring)
739 # send a notice message to channel/nick +where+
740 def notice(where, message, mchan="", mring=-1)
756 message.each_line { |line|
758 next unless(line.length > 0)
759 sendmsg "NOTICE", where, line, chan, ring
763 # say something (PRIVMSG) to channel/nick +where+
764 def say(where, message, mchan="", mring=-1)
780 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
782 next unless(line.length > 0)
783 unless quiet_on?(where)
784 sendmsg "PRIVMSG", where, line, chan, ring
789 # perform a CTCP action with message +message+ to channel/nick +where+
790 def action(where, message, mchan="", mring=-1)
806 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
809 irclog "* #{myself} #{message}", where
811 irclog "* #{myself}[#{where}] #{message}", where
815 # quick way to say "okay" (or equivalent) to +where+
817 say where, @lang.get("okay")
820 # log IRC-related message +message+ to a file determined by +where+.
821 # +where+ can be a channel name, or a nick for private message logging
822 def irclog(message, where="server")
823 message = message.chomp
824 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
825 where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
826 unless(@logs.has_key?(where))
827 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
828 @logs[where].sync = true
830 @logs[where].puts "[#{stamp}] #{message}"
831 #debug "[#{stamp}] <#{where}> #{message}"
834 # set topic of channel +where+ to +topic+
835 def topic(where, topic)
836 sendq "TOPIC #{where} :#{topic}", where, 2
839 # disconnect from the server and cleanup all plugins and modules
840 def shutdown(message = nil)
841 @quit_mutex.synchronize do
842 debug "Shutting down ..."
843 ## No we don't restore them ... let everything run through
845 # trap("SIGINT", "DEFAULT")
846 # trap("SIGTERM", "DEFAULT")
847 # trap("SIGHUP", "DEFAULT")
849 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
851 message = @lang.get("quit") if (message.nil? || message.empty?)
852 if @socket.connected?
853 debug "Clearing socket"
855 debug "Sending quit message"
856 @socket.emergency_puts "QUIT :#{message}"
857 debug "Flushing socket"
859 debug "Shutting down socket"
862 debug "Logging quits"
863 server.channels.each { |ch|
864 irclog "@ quit (#{message})", ch
869 @save_mutex.synchronize do
872 # debug "Closing registries"
874 debug "Cleaning up the db environment"
876 log "rbot quit (#{message})"
880 # message:: optional IRC quit message
881 # quit IRC, shutdown the bot
882 def quit(message=nil)
890 # totally shutdown and respawn the bot
891 def restart(message = false)
892 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
894 sleep @config['server.reconnect_wait']
896 # Note, this fails on Windows
900 # call the save method for all of the botmodules
902 @save_mutex.synchronize do
908 # call the rescan method for all of the botmodules
910 @save_mutex.synchronize do
916 # channel:: channel to join
917 # key:: optional channel key if channel is +s
919 def join(channel, key=nil)
921 sendq "JOIN #{channel} :#{key}", channel, 2
923 sendq "JOIN #{channel}", channel, 2
928 def part(channel, message="")
929 sendq "PART #{channel} :#{message}", channel, 2
932 # attempt to change bot's nick to +name+
938 def mode(channel, mode, target)
939 sendq "MODE #{channel} #{mode} #{target}", channel, 2
943 def kick(channel, user, msg)
944 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
947 # m:: message asking for help
948 # topic:: optional topic help is requested for
949 # respond to online help requests
951 topic = nil if topic == ""
954 helpstr = "help topics: "
955 helpstr += @plugins.helptopics
956 helpstr += " (help <topic> for more info)"
958 unless(helpstr = @plugins.help(topic))
959 helpstr = "no help for topic #{topic}"
965 # returns a string describing the current status of the bot (uptime etc)
967 secs_up = Time.new - @startup_time
968 uptime = Utils.secs_to_string secs_up
969 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
970 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
973 # We want to respond to a hung server in a timely manner. If nothing was received
974 # in the user-selected timeout and we haven't PINGed the server yet, we PING
975 # the server. If the PONG is not received within the user-defined timeout, we
976 # assume we're in ping timeout and act accordingly.
978 act_timeout = @config['server.ping_timeout']
979 return if act_timeout <= 0
981 if @last_rec && now > @last_rec + act_timeout
983 # No previous PING pending, send a new one
985 @last_ping = Time.now
987 diff = now - @last_ping
988 if diff > act_timeout
989 debug "no PONG from server in #{diff} seconds, reconnecting"
990 # the actual reconnect is handled in the main loop:
991 raise TimeoutError, "no PONG from server in #{diff} seconds"
997 def stop_server_pings
998 # cancel previous PINGs and reset time of last RECV
1005 def irclogprivmsg(m)
1008 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1010 irclog "* #{m.sourcenick} #{m.message}", m.target
1014 irclog "<#{m.sourcenick}> #{m.message}", m.target
1016 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1021 # log a message. Internal use only.
1022 def log_sent(type, where, message)
1027 irclog "-=#{myself}=- #{message}", where
1029 irclog "[-=#{where}=-] #{message}", where
1034 irclog "<#{myself}> #{message}", where
1036 irclog "[msg(#{where})] #{message}", where
1043 debug "joined channel #{m.channel}"
1044 irclog "@ Joined channel #{m.channel}", m.channel
1046 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1052 debug "left channel #{m.channel}"
1053 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1055 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1061 debug "kicked from channel #{m.channel}"
1062 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1064 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1069 if m.source == myself
1070 irclog "@ I set topic \"#{m.topic}\"", m.channel
1072 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel