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'
72 # require 'rbot/utils'
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 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
96 # the bot's BotConfig data
99 # the botclass for this bot (determines configdir among other things)
100 attr_reader :botclass
102 # used to perform actions periodically (saves configuration once per minute
106 # synchronize with this mutex while touching permanent data files:
107 # saving, flushing, cleaning up ...
108 attr_reader :save_mutex
110 # bot's Language data
117 # bot's object registry, plugins get an interface to this for persistant
118 # storage (hash interface tied to a bdb file, plugins use Accessors to store
119 # and restore objects in their own namespaces.)
120 attr_reader :registry
122 # bot's plugins. This is an instance of class Plugins
125 # bot's httputil help object, for fetching resources via http. Sets up
126 # proxies etc as defined by the bot configuration/environment
127 attr_accessor :httputil
129 # server we are connected to
135 # bot User in the client/server connection
141 # bot User in the client/server connection
146 # create a new Bot with botclass +botclass+
147 def initialize(botclass, params = {})
148 # BotConfig for the core bot
149 # TODO should we split socket stuff into ircsocket, etc?
150 BotConfig.register BotConfigArrayValue.new('server.list',
151 :default => ['irc://localhost'], :wizard => true,
152 :requires_restart => true,
153 :desc => "List of irc servers rbot should try to connect to. Use comma to separate values. Servers are in format 'server.doma.in:port'. If port is not specified, default value (6667) is used.")
154 BotConfig.register BotConfigBooleanValue.new('server.ssl',
155 :default => false, :requires_restart => true, :wizard => true,
156 :desc => "Use SSL to connect to this server?")
157 BotConfig.register BotConfigStringValue.new('server.password',
158 :default => false, :requires_restart => true,
159 :desc => "Password for connecting to this server (if required)",
161 BotConfig.register BotConfigStringValue.new('server.bindhost',
162 :default => false, :requires_restart => true,
163 :desc => "Specific local host or IP for the bot to bind to (if required)",
165 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
166 :default => 5, :validate => Proc.new{|v| v >= 0},
167 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
168 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
169 :default => 2.0, :validate => Proc.new{|v| v >= 0},
170 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
171 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
172 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
173 :default => 4, :validate => Proc.new{|v| v >= 0},
174 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
175 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
176 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
177 :default => 30, :validate => Proc.new{|v| v >= 0},
178 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
180 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
181 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
182 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
183 BotConfig.register BotConfigStringValue.new('irc.name',
184 :default => "Ruby bot", :requires_restart => true,
185 :desc => "IRC realname the bot should use")
186 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
187 :default => true, :requires_restart => true,
188 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
189 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
190 :requires_restart => true,
191 :desc => "local user the bot should appear to be", :wizard => true)
192 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
193 :default => [], :wizard => true,
194 :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'")
195 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
197 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
199 BotConfig.register BotConfigIntegerValue.new('core.save_every',
200 :default => 60, :validate => Proc.new{|v| v >= 0},
201 :on_change => Proc.new { |bot, v|
204 @timer.reschedule(@save_timer, v)
205 @timer.unblock(@save_timer)
207 @timer.block(@save_timer)
211 @save_timer = @timer.add(v) { bot.save }
213 # Nothing to do when v == 0
216 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
218 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
219 :default => false, :requires_restart => true,
220 :desc => "Should the bot run as a daemon?")
222 BotConfig.register BotConfigStringValue.new('log.file',
223 :default => false, :requires_restart => true,
224 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
225 BotConfig.register BotConfigIntegerValue.new('log.level',
226 :default => 1, :requires_restart => false,
227 :validate => Proc.new { |v| (0..5).include?(v) },
228 :on_change => Proc.new { |bot, v|
231 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
232 BotConfig.register BotConfigIntegerValue.new('log.keep',
233 :default => 1, :requires_restart => true,
234 :validate => Proc.new { |v| v >= 0 },
235 :desc => "How many old console messages logfiles to keep")
236 BotConfig.register BotConfigIntegerValue.new('log.max_size',
237 :default => 10, :requires_restart => true,
238 :validate => Proc.new { |v| v > 0 },
239 :desc => "Maximum console messages logfile size (in megabytes)")
241 BotConfig.register BotConfigArrayValue.new('plugins.path',
242 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
243 :requires_restart => false,
244 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
245 :desc => "Where the bot should look for plugins. List multiple directories using commas to separate. Use '(default)' for default prepackaged plugins collection, '(default)/contrib' for prepackaged unsupported plugins collection")
247 BotConfig.register BotConfigEnumValue.new('send.newlines',
248 :values => ['split', 'join'], :default => 'split',
249 :on_change => Proc.new { |bot, v|
250 bot.set_default_send_options :newlines => v.to_sym
252 :desc => "When set to split, messages with embedded newlines will be sent as separate lines. When set to join, newlines will be replaced by the value of join_with")
253 BotConfig.register BotConfigStringValue.new('send.join_with',
255 :on_change => Proc.new { |bot, v|
256 bot.set_default_send_options :join_with => v.dup
258 :desc => "String used to replace newlines when send.newlines is set to join")
259 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
261 :validate => Proc.new { |v| v >= 0 },
262 :on_change => Proc.new { |bot, v|
263 bot.set_default_send_options :max_lines => v
265 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
266 BotConfig.register BotConfigEnumValue.new('send.overlong',
267 :values => ['split', 'truncate'], :default => 'split',
268 :on_change => Proc.new { |bot, v|
269 bot.set_default_send_options :overlong => v.to_sym
271 :desc => "When set to split, messages which are too long to fit in a single IRC line are split into multiple lines. When set to truncate, long messages are truncated to fit the IRC line length")
272 BotConfig.register BotConfigStringValue.new('send.split_at',
274 :on_change => Proc.new { |bot, v|
275 bot.set_default_send_options :split_at => Regexp.new(v)
277 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
278 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
280 :on_change => Proc.new { |bot, v|
281 bot.set_default_send_options :purge_split => v
283 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
284 BotConfig.register BotConfigStringValue.new('send.truncate_text',
285 :default => "#{Reverse}...#{Reverse}",
286 :on_change => Proc.new { |bot, v|
287 bot.set_default_send_options :truncate_text => v.dup
289 :desc => "When truncating overlong messages (see send.overlong) or when sending too many lines per message (see send.max_lines) replace the end of the last line with this text")
291 @argv = params[:argv]
293 unless FileTest.directory? Config::coredir
294 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
298 unless FileTest.directory? Config::datadir
299 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
303 unless botclass and not botclass.empty?
304 # We want to find a sensible default.
305 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
306 # * On Windows (at least the NT versions) we want to put our stuff in the
307 # Application Data folder.
308 # We don't use any particular O/S detection magic, exploiting the fact that
309 # Etc.getpwuid is nil on Windows
310 if Etc.getpwuid(Process::Sys.geteuid)
311 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
313 if ENV.has_key?('APPDATA')
314 botclass = ENV['APPDATA'].dup
315 botclass.gsub!("\\","/")
320 botclass = File.expand_path(botclass)
321 @botclass = botclass.gsub(/\/$/, "")
323 unless FileTest.directory? botclass
324 log "no #{botclass} directory found, creating from templates.."
325 if FileTest.exist? botclass
326 error "file #{botclass} exists but isn't a directory"
329 FileUtils.cp_r Config::datadir+'/templates', botclass
332 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
333 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
334 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
336 # Time at which the last PING was sent
338 # Time at which the last line was RECV'd from the server
341 @startup_time = Time.new
344 @config = BotConfig.configmanager
345 @config.bot_associate(self)
348 fatal e.backtrace.join("\n")
353 if @config['core.run_as_daemon']
357 @logfile = @config['log.file']
358 if @logfile.class!=String || @logfile.empty?
359 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
362 # See http://blog.humlab.umu.se/samuel/archives/000107.html
363 # for the backgrounding code
369 rescue NotImplementedError
370 warning "Could not background, fork not supported"
372 warning "Could not background. #{e.inspect}"
375 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
376 log "Redirecting standard input/output/error"
378 STDIN.reopen "/dev/null"
380 # On Windows, there's not such thing as /dev/null
383 def STDOUT.write(str=nil)
387 def STDERR.write(str=nil)
388 if str.to_s.match(/:\d+: warning:/)
397 # Set the new logfile and loglevel. This must be done after the daemonizing
398 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
399 $logger.datetime_format= $dateformat
400 $logger.level = @config['log.level']
401 $logger.level = $cl_loglevel if $cl_loglevel
402 $logger.level = 0 if $debug
406 @registry = BotRegistry.new self
408 @timer = Timer::Timer.new(1.0) # only need per-second granularity
409 @save_mutex = Mutex.new
410 if @config['core.save_every'] > 0
411 @save_timer = @timer.add(@config['core.save_every']) { save }
415 @quit_mutex = Mutex.new
420 @lang = Language::Language.new(self, @config['core.language'])
423 @auth = Auth::authmanager
424 @auth.bot_associate(self)
425 # @auth.load("#{botclass}/botusers.yaml")
428 fatal e.backtrace.join("\n")
432 @auth.everyone.set_default_permission("*", true)
433 @auth.botowner.password= @config['auth.password']
435 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
436 @plugins = Plugins::manager
437 @plugins.bot_associate(self)
440 if @config['server.name']
441 debug "upgrading configuration (server.name => server.list)"
442 srv_uri = 'irc://' + @config['server.name']
443 srv_uri += ":#{@config['server.port']}" if @config['server.port']
444 @config.items['server.list'.to_sym].set_string(srv_uri)
445 @config.delete('server.name'.to_sym)
446 @config.delete('server.port'.to_sym)
447 debug "server.list is now #{@config['server.list'].inspect}"
450 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
455 # Channels where we are quiet
456 # Array of channels names where the bot should be quiet
457 # '*' means all channels
461 @client[:welcome] = proc {|data|
462 irclog "joined server #{@client.server} as #{myself}", "server"
464 @plugins.delegate("connect")
466 @config['irc.join_channels'].each { |c|
467 debug "autojoining channel #{c}"
468 if(c =~ /^(\S+)\s+(\S+)$/i)
476 # TODO the next two @client should go into rfc2812.rb, probably
477 # Since capabs are two-steps processes, server.supports[:capab]
478 # should be a three-state: nil, [], [....]
479 asked_for = { :"identify-msg" => false }
480 @client[:isupport] = proc { |data|
481 if server.supports[:capab] and !asked_for[:"identify-msg"]
482 sendq "CAPAB IDENTIFY-MSG"
483 asked_for[:"identify-msg"] = true
486 @client[:datastr] = proc { |data|
487 if data[:text] == "IDENTIFY-MSG"
488 server.capabilities[:"identify-msg"] = true
490 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
494 @client[:privmsg] = proc { |data|
495 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
496 # debug "Message source is #{data[:source].inspect}"
497 # debug "Message target is #{data[:target].inspect}"
498 # debug "Bot is #{myself.inspect}"
501 @config['irc.ignore_users'].each { |mask|
502 if m.source.matches?(server.new_netmask(mask))
511 @plugins.delegate "listen", m
512 @plugins.privmsg(m) if m.address?
514 @plugins.delegate "unreplied", m
518 @client[:notice] = proc { |data|
519 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
520 # pass it off to plugins that want to hear everything
521 @plugins.delegate "listen", message
523 @client[:motd] = proc { |data|
524 data[:motd].each_line { |line|
525 irclog "MOTD: #{line}", "server"
528 @client[:nicktaken] = proc { |data|
529 new = "#{data[:nick]}_"
531 # If we're setting our nick at connection because our choice was taken,
532 # we have to fix our nick manually, because there will be no NICK message
533 # to inform us that our nick has been changed.
534 if data[:target] == '*'
535 debug "setting my connection nick to #{new}"
538 @plugins.delegate "nicktaken", data[:nick]
540 @client[:badnick] = proc {|data|
541 arning "bad nick (#{data[:nick]})"
543 @client[:ping] = proc {|data|
544 sendq "PONG #{data[:pingid]}"
546 @client[:pong] = proc {|data|
549 @client[:nick] = proc {|data|
550 # debug "Message source is #{data[:source].inspect}"
551 # debug "Bot is #{myself.inspect}"
552 source = data[:source]
555 m = NickMessage.new(self, server, source, old, new)
557 debug "my nick is now #{new}"
559 data[:is_on].each { |ch|
560 irclog "@ #{old} is now known as #{new}", ch
562 @plugins.delegate("listen", m)
563 @plugins.delegate("nick", m)
565 @client[:quit] = proc {|data|
566 source = data[:source]
567 message = data[:message]
568 m = QuitMessage.new(self, server, source, source, message)
569 data[:was_on].each { |ch|
570 irclog "@ Quit: #{source}: #{message}", ch
572 @plugins.delegate("listen", m)
573 @plugins.delegate("quit", m)
575 @client[:mode] = proc {|data|
576 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
578 @client[:join] = proc {|data|
579 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
582 @plugins.delegate("listen", m)
583 @plugins.delegate("join", m)
585 @client[:part] = proc {|data|
586 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
589 @plugins.delegate("listen", m)
590 @plugins.delegate("part", m)
592 @client[:kick] = proc {|data|
593 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
596 @plugins.delegate("listen", m)
597 @plugins.delegate("kick", m)
599 @client[:invite] = proc {|data|
600 if data[:target] == myself
601 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
604 @client[:changetopic] = proc {|data|
605 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
608 @plugins.delegate("listen", m)
609 @plugins.delegate("topic", m)
611 @client[:topic] = proc { |data|
612 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
614 @client[:topicinfo] = proc { |data|
615 channel = data[:channel]
616 topic = channel.topic
617 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
618 m = TopicMessage.new(self, server, data[:source], channel, topic)
620 @plugins.delegate("listen", m)
621 @plugins.delegate("topic", m)
623 @client[:names] = proc { |data|
624 @plugins.delegate "names", data[:channel], data[:users]
626 @client[:unknown] = proc { |data|
627 #debug "UNKNOWN: #{data[:serverstring]}"
628 irclog data[:serverstring], ".unknown"
631 set_default_send_options :newlines => @config['send.newlines'].to_sym,
632 :join_with => @config['send.join_with'].dup,
633 :max_lines => @config['send.max_lines'],
634 :overlong => @config['send.overlong'].to_sym,
635 :split_at => Regexp.new(@config['send.split_at']),
636 :purge_split => @config['send.purge_split'],
637 :truncate_text => @config['send.truncate_text'].dup
640 def setup_plugins_path
641 @plugins.clear_botmodule_dirs
642 @plugins.add_botmodule_dir(Config::coredir + "/utils")
643 @plugins.add_botmodule_dir(Config::coredir)
644 @plugins.add_botmodule_dir("#{botclass}/plugins")
646 @config['plugins.path'].each do |_|
647 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
648 @plugins.add_botmodule_dir(path)
652 def set_default_send_options(opts={})
653 # Default send options for NOTICE and PRIVMSG
654 unless defined? @default_send_options
655 @default_send_options = {
656 :queue_channel => nil, # use default queue channel
657 :queue_ring => nil, # use default queue ring
658 :newlines => :split, # or :join
659 :join_with => ' ', # by default, use a single space
660 :max_lines => 0, # maximum number of lines to send with a single command
661 :overlong => :split, # or :truncate
662 # TODO an array of splitpoints would be preferrable for this option:
663 :split_at => /\s+/, # by default, split overlong lines at whitespace
664 :purge_split => true, # should the split string be removed?
665 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
668 @default_send_options.update opts unless opts.empty?
671 # checks if we should be quiet on a channel
672 def quiet_on?(channel)
673 return @quiet.include?('*') || @quiet.include?(channel.downcase)
676 def set_quiet(channel)
678 ch = channel.downcase.dup
679 @quiet << ch unless @quiet.include?(ch)
686 def reset_quiet(channel)
688 @quiet.delete channel.downcase
694 # things to do when we receive a signal
696 debug "received #{sig}, queueing quit"
698 quit unless @quit_mutex.locked?
699 debug "interrupted #{$interrupted} times"
707 # connect the bot to IRC
710 trap("SIGINT") { got_sig("SIGINT") }
711 trap("SIGTERM") { got_sig("SIGTERM") }
712 trap("SIGHUP") { got_sig("SIGHUP") }
713 rescue ArgumentError => e
714 debug "failed to trap signals (#{e.inspect}): running on Windows?"
716 debug "failed to trap signals: #{e.inspect}"
719 quit if $interrupted > 0
722 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
724 quit if $interrupted > 0
726 realname = @config['irc.name'].clone || 'Ruby bot'
727 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
729 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
730 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
731 quit if $interrupted > 0
732 myself.nick = @config['irc.nick']
733 myself.user = @config['irc.user']
736 # begin event handling loop
740 quit if $interrupted > 0
745 while @socket.connected?
746 quit if $interrupted > 0
748 # Wait for messages and process them as they arrive. If nothing is
749 # received, we call the ping_server() method that will PING the
750 # server if appropriate, or raise a TimeoutError if no PONG has been
751 # received in the user-chosen timeout since the last PING sent.
753 break unless reply = @socket.gets
755 @client.process reply
761 # I despair of this. Some of my users get "connection reset by peer"
762 # exceptions that ARENT SocketError's. How am I supposed to handle
767 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
768 error "network exception: #{e.class}: #{e}"
769 debug e.backtrace.join("\n")
771 rescue BDB::Fatal => e
772 fatal "fatal bdb error: #{e.class}: #{e}"
773 fatal e.backtrace.join("\n")
775 # Why restart? DB problems are serious stuff ...
776 # restart("Oops, we seem to have registry problems ...")
779 rescue Exception => e
780 error "non-net exception: #{e.class}: #{e}"
781 error e.backtrace.join("\n")
784 fatal "unexpected exception: #{e.class}: #{e}"
785 fatal e.backtrace.join("\n")
792 log "\n\nDisconnected\n\n"
794 quit if $interrupted > 0
796 log "\n\nWaiting to reconnect\n\n"
797 sleep @config['server.reconnect_wait']
801 # type:: message type
802 # where:: message target
803 # message:: message text
804 # send message +message+ of type +type+ to target +where+
805 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
806 # relevant say() or notice() methods. This one should be used for IRCd
807 # extensions you want to use in modules.
808 def sendmsg(type, where, original_message, options={})
809 opts = @default_send_options.merge(options)
811 # For starters, set up appropriate queue channels and rings
812 mchan = opts[:queue_channel]
813 mring = opts[:queue_ring]
830 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
834 messages << [multi_line.gsub("\n", opts[:join_with])]
836 multi_line.each_line { |line|
838 next unless(line.size > 0)
842 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
845 # The IRC protocol requires that each raw message must be not longer
846 # than 512 characters. From this length with have to subtract the EOL
847 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
848 # that will be prepended by the server to all of our messages.
850 # The maximum raw message length we can send is therefore 512 - 2 - 2
851 # minus the length of our hostmask.
853 max_len = 508 - myself.fullform.size
855 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
856 # will have a + or - prepended
857 if server.capabilities[:"identify-msg"]
861 # When splitting the message, we'll be prefixing the following string:
862 # (e.g. "PRIVMSG #rbot :")
863 fixed = "#{type} #{where} :"
865 # And this is what's left
866 left = max_len - fixed.size
868 truncate = opts[:truncate_text]
869 truncate = @default_send_options[:truncate_text] if truncate.size > left
870 truncate = "" if truncate.size > left
872 all_lines = messages.map { |line|
879 sub_lines = Array.new
881 sub_lines << msg.slice!(0, left)
883 lastspace = sub_lines.last.rindex(opts[:split_at])
885 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
886 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
891 line.slice(0, left - truncate.size) << truncate
893 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
898 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
899 lines = all_lines[0...opts[:max_lines]]
900 new_last = lines.last.slice(0, left - truncate.size) << truncate
901 lines.last.replace(new_last)
908 sendq "#{fixed}#{line}", chan, ring
909 log_sent(type, where, line)
913 # queue an arbitraty message for the server
914 def sendq(message="", chan=nil, ring=0)
916 @socket.queue(message, chan, ring)
919 # send a notice message to channel/nick +where+
920 def notice(where, message, options={})
921 return if where.kind_of?(Channel) and quiet_on?(where)
922 sendmsg "NOTICE", where, message, options
925 # say something (PRIVMSG) to channel/nick +where+
926 def say(where, message, options={})
927 return if where.kind_of?(Channel) and quiet_on?(where)
928 sendmsg "PRIVMSG", where, message, options
931 # perform a CTCP action with message +message+ to channel/nick +where+
932 def action(where, message, options={})
933 return if where.kind_of?(Channel) and quiet_on?(where)
934 mchan = options.fetch(:queue_channel, nil)
935 mring = options.fetch(:queue_ring, nil)
951 # FIXME doesn't check message length. Can we make this exploit sendmsg?
952 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
955 irclog "* #{myself} #{message}", where
957 irclog "* #{myself}[#{where}] #{message}", where
961 # quick way to say "okay" (or equivalent) to +where+
963 say where, @lang.get("okay")
966 # log IRC-related message +message+ to a file determined by +where+.
967 # +where+ can be a channel name, or a nick for private message logging
968 def irclog(message, where="server")
969 message = message.chomp
970 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
971 if where.class <= Server
974 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
976 unless(@logs.has_key?(where_str))
977 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
978 @logs[where_str].sync = true
980 @logs[where_str].puts "[#{stamp}] #{message}"
981 #debug "[#{stamp}] <#{where}> #{message}"
984 # set topic of channel +where+ to +topic+
985 def topic(where, topic)
986 sendq "TOPIC #{where} :#{topic}", where, 2
989 def disconnect(message = nil)
990 message = @lang.get("quit") if (message.nil? || message.empty?)
991 if @socket.connected?
992 debug "Clearing socket"
994 debug "Sending quit message"
995 @socket.emergency_puts "QUIT :#{message}"
996 debug "Flushing socket"
998 debug "Shutting down socket"
1001 debug "Logging quits"
1002 server.channels.each { |ch|
1003 irclog "@ quit (#{message})", ch
1009 # disconnect from the server and cleanup all plugins and modules
1010 def shutdown(message = nil)
1011 @quit_mutex.synchronize do
1012 debug "Shutting down ..."
1013 ## No we don't restore them ... let everything run through
1015 # trap("SIGINT", "DEFAULT")
1016 # trap("SIGTERM", "DEFAULT")
1017 # trap("SIGHUP", "DEFAULT")
1019 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1025 @save_mutex.synchronize do
1028 # debug "Closing registries"
1030 debug "Cleaning up the db environment"
1032 log "rbot quit (#{message})"
1036 # message:: optional IRC quit message
1037 # quit IRC, shutdown the bot
1038 def quit(message=nil)
1046 # totally shutdown and respawn the bot
1047 def restart(message = false)
1048 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1050 sleep @config['server.reconnect_wait']
1052 # Note, this fails on Windows
1056 # call the save method for all of the botmodules
1058 @save_mutex.synchronize do
1064 # call the rescan method for all of the botmodules
1066 @save_mutex.synchronize do
1072 # channel:: channel to join
1073 # key:: optional channel key if channel is +s
1075 def join(channel, key=nil)
1077 sendq "JOIN #{channel} :#{key}", channel, 2
1079 sendq "JOIN #{channel}", channel, 2
1084 def part(channel, message="")
1085 sendq "PART #{channel} :#{message}", channel, 2
1088 # attempt to change bot's nick to +name+
1090 sendq "NICK #{name}"
1094 def mode(channel, mode, target)
1095 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1099 def kick(channel, user, msg)
1100 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1103 # m:: message asking for help
1104 # topic:: optional topic help is requested for
1105 # respond to online help requests
1107 topic = nil if topic == ""
1110 helpstr = "help topics: "
1111 helpstr += @plugins.helptopics
1112 helpstr += " (help <topic> for more info)"
1114 unless(helpstr = @plugins.help(topic))
1115 helpstr = "no help for topic #{topic}"
1121 # returns a string describing the current status of the bot (uptime etc)
1123 secs_up = Time.new - @startup_time
1124 uptime = Utils.secs_to_string secs_up
1125 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1126 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1129 # We want to respond to a hung server in a timely manner. If nothing was received
1130 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1131 # the server. If the PONG is not received within the user-defined timeout, we
1132 # assume we're in ping timeout and act accordingly.
1134 act_timeout = @config['server.ping_timeout']
1135 return if act_timeout <= 0
1137 if @last_rec && now > @last_rec + act_timeout
1139 # No previous PING pending, send a new one
1141 @last_ping = Time.now
1143 diff = now - @last_ping
1144 if diff > act_timeout
1145 debug "no PONG from server in #{diff} seconds, reconnecting"
1146 # the actual reconnect is handled in the main loop:
1147 raise TimeoutError, "no PONG from server in #{diff} seconds"
1153 def stop_server_pings
1154 # cancel previous PINGs and reset time of last RECV
1161 def irclogprivmsg(m)
1164 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1166 irclog "* #{m.source} #{m.message}", m.target
1170 irclog "<#{m.source}> #{m.message}", m.target
1172 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1177 # log a message. Internal use only.
1178 def log_sent(type, where, message)
1183 irclog "-=#{myself}=- #{message}", where
1185 irclog "[-=#{where}=-] #{message}", where
1190 irclog "<#{myself}> #{message}", where
1192 irclog "[msg(#{where})] #{message}", where
1199 debug "joined channel #{m.channel}"
1200 irclog "@ Joined channel #{m.channel}", m.channel
1202 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1208 debug "left channel #{m.channel}"
1209 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1211 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1217 debug "kicked from channel #{m.channel}"
1218 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1220 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1225 if m.source == myself
1226 irclog "@ I set topic \"#{m.topic}\"", m.channel
1228 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel