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
20 q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
21 q.seplist(self.backtrace, lambda { "\n" }) { |v| v } if self.backtrace
26 def rawlog(level, message=nil, who_pos=1)
28 if call_stack.length > who_pos
29 who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
33 # Output each line. To distinguish between separate messages and multi-line
34 # messages originating at the same time, we blank #{who} after the first message
36 # Also, we output strings as-is but for other objects we use pretty_inspect
41 str = message.pretty_inspect
44 $logger.add(level, l.chomp, who)
50 $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
54 $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
57 def debug(message=nil, who_pos=1)
58 rawlog(Logger::Severity::DEBUG, message, who_pos)
61 def log(message=nil, who_pos=1)
62 rawlog(Logger::Severity::INFO, message, who_pos)
65 def warning(message=nil, who_pos=1)
66 rawlog(Logger::Severity::WARN, message, who_pos)
69 def error(message=nil, who_pos=1)
70 rawlog(Logger::Severity::ERROR, message, who_pos)
73 def fatal(message=nil, who_pos=1)
74 rawlog(Logger::Severity::FATAL, message, who_pos)
79 warning "warning test"
83 # The following global is used for the improved signal handling.
87 require 'rbot/rbotconfig'
89 # require 'rbot/utils'
92 require 'rbot/rfc2812'
93 require 'rbot/ircsocket'
94 require 'rbot/botuser'
96 require 'rbot/plugins'
97 # require 'rbot/channel'
98 require 'rbot/message'
99 require 'rbot/language'
100 require 'rbot/dbhash'
101 require 'rbot/registry'
102 # require 'rbot/httputil'
106 # Main bot class, which manages the various components, receives messages,
107 # handles them or passes them to plugins, and contains core functionality.
109 COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
110 # the bot's Auth data
113 # the bot's BotConfig data
116 # the botclass for this bot (determines configdir among other things)
117 attr_reader :botclass
119 # used to perform actions periodically (saves configuration once per minute
123 # synchronize with this mutex while touching permanent data files:
124 # saving, flushing, cleaning up ...
125 attr_reader :save_mutex
127 # bot's Language data
134 # bot's object registry, plugins get an interface to this for persistant
135 # storage (hash interface tied to a bdb file, plugins use Accessors to store
136 # and restore objects in their own namespaces.)
137 attr_reader :registry
139 # bot's plugins. This is an instance of class Plugins
142 # bot's httputil help object, for fetching resources via http. Sets up
143 # proxies etc as defined by the bot configuration/environment
144 attr_accessor :httputil
146 # server we are connected to
152 # bot User in the client/server connection
158 # bot User in the client/server connection
163 # create a new Bot with botclass +botclass+
164 def initialize(botclass, params = {})
165 # BotConfig for the core bot
166 # TODO should we split socket stuff into ircsocket, etc?
167 BotConfig.register BotConfigArrayValue.new('server.list',
168 :default => ['irc://localhost'], :wizard => true,
169 :requires_restart => true,
170 :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.")
171 BotConfig.register BotConfigBooleanValue.new('server.ssl',
172 :default => false, :requires_restart => true, :wizard => true,
173 :desc => "Use SSL to connect to this server?")
174 BotConfig.register BotConfigStringValue.new('server.password',
175 :default => false, :requires_restart => true,
176 :desc => "Password for connecting to this server (if required)",
178 BotConfig.register BotConfigStringValue.new('server.bindhost',
179 :default => false, :requires_restart => true,
180 :desc => "Specific local host or IP for the bot to bind to (if required)",
182 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
183 :default => 5, :validate => Proc.new{|v| v >= 0},
184 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
185 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
186 :default => 2.0, :validate => Proc.new{|v| v >= 0},
187 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
188 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
189 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
190 :default => 4, :validate => Proc.new{|v| v >= 0},
191 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
192 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
193 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
194 :default => 30, :validate => Proc.new{|v| v >= 0},
195 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
197 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
198 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
199 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
200 BotConfig.register BotConfigStringValue.new('irc.name',
201 :default => "Ruby bot", :requires_restart => true,
202 :desc => "IRC realname the bot should use")
203 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
204 :default => true, :requires_restart => true,
205 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
206 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
207 :requires_restart => true,
208 :desc => "local user the bot should appear to be", :wizard => true)
209 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
210 :default => [], :wizard => true,
211 :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'")
212 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
214 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
216 BotConfig.register BotConfigIntegerValue.new('core.save_every',
217 :default => 60, :validate => Proc.new{|v| v >= 0},
218 :on_change => Proc.new { |bot, v|
221 @timer.reschedule(@save_timer, v)
222 @timer.unblock(@save_timer)
224 @timer.block(@save_timer)
228 @save_timer = @timer.add(v) { bot.save }
230 # Nothing to do when v == 0
233 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
235 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
236 :default => false, :requires_restart => true,
237 :desc => "Should the bot run as a daemon?")
239 BotConfig.register BotConfigStringValue.new('log.file',
240 :default => false, :requires_restart => true,
241 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
242 BotConfig.register BotConfigIntegerValue.new('log.level',
243 :default => 1, :requires_restart => false,
244 :validate => Proc.new { |v| (0..5).include?(v) },
245 :on_change => Proc.new { |bot, v|
248 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
249 BotConfig.register BotConfigIntegerValue.new('log.keep',
250 :default => 1, :requires_restart => true,
251 :validate => Proc.new { |v| v >= 0 },
252 :desc => "How many old console messages logfiles to keep")
253 BotConfig.register BotConfigIntegerValue.new('log.max_size',
254 :default => 10, :requires_restart => true,
255 :validate => Proc.new { |v| v > 0 },
256 :desc => "Maximum console messages logfile size (in megabytes)")
258 BotConfig.register BotConfigArrayValue.new('plugins.path',
259 :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
260 :requires_restart => false,
261 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
262 :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")
264 BotConfig.register BotConfigEnumValue.new('send.newlines',
265 :values => ['split', 'join'], :default => 'split',
266 :on_change => Proc.new { |bot, v|
267 bot.set_default_send_options :newlines => v.to_sym
269 :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")
270 BotConfig.register BotConfigStringValue.new('send.join_with',
272 :on_change => Proc.new { |bot, v|
273 bot.set_default_send_options :join_with => v.dup
275 :desc => "String used to replace newlines when send.newlines is set to join")
276 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
278 :validate => Proc.new { |v| v >= 0 },
279 :on_change => Proc.new { |bot, v|
280 bot.set_default_send_options :max_lines => v
282 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
283 BotConfig.register BotConfigEnumValue.new('send.overlong',
284 :values => ['split', 'truncate'], :default => 'split',
285 :on_change => Proc.new { |bot, v|
286 bot.set_default_send_options :overlong => v.to_sym
288 :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")
289 BotConfig.register BotConfigStringValue.new('send.split_at',
291 :on_change => Proc.new { |bot, v|
292 bot.set_default_send_options :split_at => Regexp.new(v)
294 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
295 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
297 :on_change => Proc.new { |bot, v|
298 bot.set_default_send_options :purge_split => v
300 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
301 BotConfig.register BotConfigStringValue.new('send.truncate_text',
302 :default => "#{Reverse}...#{Reverse}",
303 :on_change => Proc.new { |bot, v|
304 bot.set_default_send_options :truncate_text => v.dup
306 :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")
308 @argv = params[:argv]
309 @run_dir = params[:run_dir] || Dir.pwd
311 unless FileTest.directory? Config::coredir
312 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
316 unless FileTest.directory? Config::datadir
317 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
321 unless botclass and not botclass.empty?
322 # We want to find a sensible default.
323 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
324 # * On Windows (at least the NT versions) we want to put our stuff in the
325 # Application Data folder.
326 # We don't use any particular O/S detection magic, exploiting the fact that
327 # Etc.getpwuid is nil on Windows
328 if Etc.getpwuid(Process::Sys.geteuid)
329 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
331 if ENV.has_key?('APPDATA')
332 botclass = ENV['APPDATA'].dup
333 botclass.gsub!("\\","/")
338 botclass = File.expand_path(botclass)
339 @botclass = botclass.gsub(/\/$/, "")
341 unless FileTest.directory? botclass
342 log "no #{botclass} directory found, creating from templates.."
343 if FileTest.exist? botclass
344 error "file #{botclass} exists but isn't a directory"
347 FileUtils.cp_r Config::datadir+'/templates', botclass
350 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
351 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
352 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
354 # Time at which the last PING was sent
356 # Time at which the last line was RECV'd from the server
359 @startup_time = Time.new
362 @config = BotConfig.configmanager
363 @config.bot_associate(self)
364 rescue Exception => e
370 if @config['core.run_as_daemon']
374 @logfile = @config['log.file']
375 if @logfile.class!=String || @logfile.empty?
376 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
379 # See http://blog.humlab.umu.se/samuel/archives/000107.html
380 # for the backgrounding code
386 rescue NotImplementedError
387 warning "Could not background, fork not supported"
390 rescue Exception => e
391 warning "Could not background. #{e.pretty_inspect}"
394 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
395 log "Redirecting standard input/output/error"
397 STDIN.reopen "/dev/null"
399 # On Windows, there's not such thing as /dev/null
402 def STDOUT.write(str=nil)
406 def STDERR.write(str=nil)
407 if str.to_s.match(/:\d+: warning:/)
416 # Set the new logfile and loglevel. This must be done after the daemonizing
417 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
418 $logger.datetime_format= $dateformat
419 $logger.level = @config['log.level']
420 $logger.level = $cl_loglevel if $cl_loglevel
421 $logger.level = 0 if $debug
425 @registry = BotRegistry.new self
427 @timer = Timer::Timer.new(1.0) # only need per-second granularity
428 @save_mutex = Mutex.new
429 if @config['core.save_every'] > 0
430 @save_timer = @timer.add(@config['core.save_every']) { save }
434 @quit_mutex = Mutex.new
439 @lang = Language::Language.new(self, @config['core.language'])
442 @auth = Auth::authmanager
443 @auth.bot_associate(self)
444 # @auth.load("#{botclass}/botusers.yaml")
445 rescue Exception => e
450 @auth.everyone.set_default_permission("*", true)
451 @auth.botowner.password= @config['auth.password']
453 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
454 @plugins = Plugins::manager
455 @plugins.bot_associate(self)
458 if @config['server.name']
459 debug "upgrading configuration (server.name => server.list)"
460 srv_uri = 'irc://' + @config['server.name']
461 srv_uri += ":#{@config['server.port']}" if @config['server.port']
462 @config.items['server.list'.to_sym].set_string(srv_uri)
463 @config.delete('server.name'.to_sym)
464 @config.delete('server.port'.to_sym)
465 debug "server.list is now #{@config['server.list'].inspect}"
468 @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
473 # Channels where we are quiet
474 # Array of channels names where the bot should be quiet
475 # '*' means all channels
479 @client[:welcome] = proc {|data|
480 irclog "joined server #{@client.server} as #{myself}", "server"
482 @plugins.delegate("connect")
484 @config['irc.join_channels'].each { |c|
485 debug "autojoining channel #{c}"
486 if(c =~ /^(\S+)\s+(\S+)$/i)
494 # TODO the next two @client should go into rfc2812.rb, probably
495 # Since capabs are two-steps processes, server.supports[:capab]
496 # should be a three-state: nil, [], [....]
497 asked_for = { :"identify-msg" => false }
498 @client[:isupport] = proc { |data|
499 if server.supports[:capab] and !asked_for[:"identify-msg"]
500 sendq "CAPAB IDENTIFY-MSG"
501 asked_for[:"identify-msg"] = true
504 @client[:datastr] = proc { |data|
505 if data[:text] == "IDENTIFY-MSG"
506 server.capabilities[:"identify-msg"] = true
508 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
512 @client[:privmsg] = proc { |data|
513 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
514 # debug "Message source is #{data[:source].inspect}"
515 # debug "Message target is #{data[:target].inspect}"
516 # debug "Bot is #{myself.inspect}"
519 @config['irc.ignore_users'].each { |mask|
520 if m.source.matches?(server.new_netmask(mask))
529 @plugins.delegate "listen", m
530 @plugins.privmsg(m) if m.address?
532 @plugins.delegate "unreplied", m
536 @client[:notice] = proc { |data|
537 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
538 # pass it off to plugins that want to hear everything
539 @plugins.delegate "listen", message
541 @client[:motd] = proc { |data|
542 data[:motd].each_line { |line|
543 irclog "MOTD: #{line}", "server"
546 @client[:nicktaken] = proc { |data|
547 new = "#{data[:nick]}_"
549 # If we're setting our nick at connection because our choice was taken,
550 # we have to fix our nick manually, because there will be no NICK message
551 # to inform us that our nick has been changed.
552 if data[:target] == '*'
553 debug "setting my connection nick to #{new}"
556 @plugins.delegate "nicktaken", data[:nick]
558 @client[:badnick] = proc {|data|
559 arning "bad nick (#{data[:nick]})"
561 @client[:ping] = proc {|data|
562 sendq "PONG #{data[:pingid]}"
564 @client[:pong] = proc {|data|
567 @client[:nick] = proc {|data|
568 # debug "Message source is #{data[:source].inspect}"
569 # debug "Bot is #{myself.inspect}"
570 source = data[:source]
573 m = NickMessage.new(self, server, source, old, new)
575 debug "my nick is now #{new}"
577 data[:is_on].each { |ch|
578 irclog "@ #{old} is now known as #{new}", ch
580 @plugins.delegate("listen", m)
581 @plugins.delegate("nick", m)
583 @client[:quit] = proc {|data|
584 source = data[:source]
585 message = data[:message]
586 m = QuitMessage.new(self, server, source, source, message)
587 data[:was_on].each { |ch|
588 irclog "@ Quit: #{source}: #{message}", ch
590 @plugins.delegate("listen", m)
591 @plugins.delegate("quit", m)
593 @client[:mode] = proc {|data|
594 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
596 @client[:join] = proc {|data|
597 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
600 @plugins.delegate("listen", m)
601 @plugins.delegate("join", m)
603 @client[:part] = proc {|data|
604 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
607 @plugins.delegate("listen", m)
608 @plugins.delegate("part", m)
610 @client[:kick] = proc {|data|
611 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
614 @plugins.delegate("listen", m)
615 @plugins.delegate("kick", m)
617 @client[:invite] = proc {|data|
618 if data[:target] == myself
619 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
622 @client[:changetopic] = proc {|data|
623 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
626 @plugins.delegate("listen", m)
627 @plugins.delegate("topic", m)
629 @client[:topic] = proc { |data|
630 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
632 @client[:topicinfo] = proc { |data|
633 channel = data[:channel]
634 topic = channel.topic
635 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
636 m = TopicMessage.new(self, server, data[:source], channel, topic)
638 @plugins.delegate("listen", m)
639 @plugins.delegate("topic", m)
641 @client[:names] = proc { |data|
642 @plugins.delegate "names", data[:channel], data[:users]
644 @client[:unknown] = proc { |data|
645 #debug "UNKNOWN: #{data[:serverstring]}"
646 irclog data[:serverstring], ".unknown"
649 set_default_send_options :newlines => @config['send.newlines'].to_sym,
650 :join_with => @config['send.join_with'].dup,
651 :max_lines => @config['send.max_lines'],
652 :overlong => @config['send.overlong'].to_sym,
653 :split_at => Regexp.new(@config['send.split_at']),
654 :purge_split => @config['send.purge_split'],
655 :truncate_text => @config['send.truncate_text'].dup
658 def setup_plugins_path
659 @plugins.clear_botmodule_dirs
660 @plugins.add_botmodule_dir(Config::coredir + "/utils")
661 @plugins.add_botmodule_dir(Config::coredir)
662 @plugins.add_botmodule_dir("#{botclass}/plugins")
664 @config['plugins.path'].each do |_|
665 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
666 @plugins.add_botmodule_dir(path)
670 def set_default_send_options(opts={})
671 # Default send options for NOTICE and PRIVMSG
672 unless defined? @default_send_options
673 @default_send_options = {
674 :queue_channel => nil, # use default queue channel
675 :queue_ring => nil, # use default queue ring
676 :newlines => :split, # or :join
677 :join_with => ' ', # by default, use a single space
678 :max_lines => 0, # maximum number of lines to send with a single command
679 :overlong => :split, # or :truncate
680 # TODO an array of splitpoints would be preferrable for this option:
681 :split_at => /\s+/, # by default, split overlong lines at whitespace
682 :purge_split => true, # should the split string be removed?
683 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
686 @default_send_options.update opts unless opts.empty?
689 # checks if we should be quiet on a channel
690 def quiet_on?(channel)
691 return @quiet.include?('*') || @quiet.include?(channel.downcase)
694 def set_quiet(channel)
696 ch = channel.downcase.dup
697 @quiet << ch unless @quiet.include?(ch)
704 def reset_quiet(channel)
706 @quiet.delete channel.downcase
712 # things to do when we receive a signal
714 debug "received #{sig}, queueing quit"
716 quit unless @quit_mutex.locked?
717 debug "interrupted #{$interrupted} times"
725 # connect the bot to IRC
728 trap("SIGINT") { got_sig("SIGINT") }
729 trap("SIGTERM") { got_sig("SIGTERM") }
730 trap("SIGHUP") { got_sig("SIGHUP") }
731 rescue ArgumentError => e
732 debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
733 rescue Exception => e
734 debug "failed to trap signals: #{e.pretty_inspect}"
737 quit if $interrupted > 0
740 raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
742 quit if $interrupted > 0
744 realname = @config['irc.name'].clone || 'Ruby bot'
745 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
747 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
748 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
749 quit if $interrupted > 0
750 myself.nick = @config['irc.nick']
751 myself.user = @config['irc.user']
754 # begin event handling loop
758 quit if $interrupted > 0
763 while @socket.connected?
764 quit if $interrupted > 0
766 # Wait for messages and process them as they arrive. If nothing is
767 # received, we call the ping_server() method that will PING the
768 # server if appropriate, or raise a TimeoutError if no PONG has been
769 # received in the user-chosen timeout since the last PING sent.
771 break unless reply = @socket.gets
773 @client.process reply
779 # I despair of this. Some of my users get "connection reset by peer"
780 # exceptions that ARENT SocketError's. How am I supposed to handle
785 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
786 error "network exception: #{e.pretty_inspect}"
788 rescue BDB::Fatal => e
789 fatal "fatal bdb error: #{e.pretty_inspect}"
791 # Why restart? DB problems are serious stuff ...
792 # restart("Oops, we seem to have registry problems ...")
795 rescue Exception => e
796 error "non-net exception: #{e.pretty_inspect}"
799 fatal "unexpected exception: #{e.pretty_inspect}"
806 log "\n\nDisconnected\n\n"
808 quit if $interrupted > 0
810 log "\n\nWaiting to reconnect\n\n"
811 sleep @config['server.reconnect_wait']
815 # type:: message type
816 # where:: message target
817 # message:: message text
818 # send message +message+ of type +type+ to target +where+
819 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
820 # relevant say() or notice() methods. This one should be used for IRCd
821 # extensions you want to use in modules.
822 def sendmsg(type, where, original_message, options={})
823 opts = @default_send_options.merge(options)
825 # For starters, set up appropriate queue channels and rings
826 mchan = opts[:queue_channel]
827 mring = opts[:queue_ring]
844 multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
848 messages << [multi_line.gsub("\n", opts[:join_with])]
850 multi_line.each_line { |line|
852 next unless(line.size > 0)
856 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
859 # The IRC protocol requires that each raw message must be not longer
860 # than 512 characters. From this length with have to subtract the EOL
861 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
862 # that will be prepended by the server to all of our messages.
864 # The maximum raw message length we can send is therefore 512 - 2 - 2
865 # minus the length of our hostmask.
867 max_len = 508 - myself.fullform.size
869 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
870 # will have a + or - prepended
871 if server.capabilities[:"identify-msg"]
875 # When splitting the message, we'll be prefixing the following string:
876 # (e.g. "PRIVMSG #rbot :")
877 fixed = "#{type} #{where} :"
879 # And this is what's left
880 left = max_len - fixed.size
882 truncate = opts[:truncate_text]
883 truncate = @default_send_options[:truncate_text] if truncate.size > left
884 truncate = "" if truncate.size > left
886 all_lines = messages.map { |line|
893 sub_lines = Array.new
895 sub_lines << msg.slice!(0, left)
897 lastspace = sub_lines.last.rindex(opts[:split_at])
899 msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
900 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
905 line.slice(0, left - truncate.size) << truncate
907 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
912 if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
913 lines = all_lines[0...opts[:max_lines]]
914 new_last = lines.last.slice(0, left - truncate.size) << truncate
915 lines.last.replace(new_last)
921 sendq "#{fixed}#{line}", chan, ring
922 log_sent(type, where, line)
926 # queue an arbitraty message for the server
927 def sendq(message="", chan=nil, ring=0)
929 @socket.queue(message, chan, ring)
932 # send a notice message to channel/nick +where+
933 def notice(where, message, options={})
934 return if where.kind_of?(Channel) and quiet_on?(where)
935 sendmsg "NOTICE", where, message, options
938 # say something (PRIVMSG) to channel/nick +where+
939 def say(where, message, options={})
940 return if where.kind_of?(Channel) and quiet_on?(where)
941 sendmsg "PRIVMSG", where, message, options
944 # perform a CTCP action with message +message+ to channel/nick +where+
945 def action(where, message, options={})
946 return if where.kind_of?(Channel) and quiet_on?(where)
947 mchan = options.fetch(:queue_channel, nil)
948 mring = options.fetch(:queue_ring, nil)
964 # FIXME doesn't check message length. Can we make this exploit sendmsg?
965 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
968 irclog "* #{myself} #{message}", where
970 irclog "* #{myself}[#{where}] #{message}", where
974 # quick way to say "okay" (or equivalent) to +where+
976 say where, @lang.get("okay")
979 # log IRC-related message +message+ to a file determined by +where+.
980 # +where+ can be a channel name, or a nick for private message logging
981 def irclog(message, where="server")
982 message = message.chomp
983 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
984 if where.class <= Server
987 where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
989 unless(@logs.has_key?(where_str))
990 @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
991 @logs[where_str].sync = true
993 @logs[where_str].puts "[#{stamp}] #{message}"
994 #debug "[#{stamp}] <#{where}> #{message}"
997 # set topic of channel +where+ to +topic+
998 def topic(where, topic)
999 sendq "TOPIC #{where} :#{topic}", where, 2
1002 def disconnect(message = nil)
1003 message = @lang.get("quit") if (message.nil? || message.empty?)
1004 if @socket.connected?
1005 debug "Clearing socket"
1007 debug "Sending quit message"
1008 @socket.emergency_puts "QUIT :#{message}"
1009 debug "Flushing socket"
1011 debug "Shutting down socket"
1014 debug "Logging quits"
1015 server.channels.each { |ch|
1016 irclog "@ quit (#{message})", ch
1022 # disconnect from the server and cleanup all plugins and modules
1023 def shutdown(message = nil)
1024 @quit_mutex.synchronize do
1025 debug "Shutting down ..."
1026 ## No we don't restore them ... let everything run through
1028 # trap("SIGINT", "DEFAULT")
1029 # trap("SIGTERM", "DEFAULT")
1030 # trap("SIGHUP", "DEFAULT")
1032 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1038 @save_mutex.synchronize do
1041 # debug "Closing registries"
1043 debug "Cleaning up the db environment"
1045 log "rbot quit (#{message})"
1049 # message:: optional IRC quit message
1050 # quit IRC, shutdown the bot
1051 def quit(message=nil)
1059 # totally shutdown and respawn the bot
1060 def restart(message = false)
1061 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1063 sleep @config['server.reconnect_wait']
1066 # Note, this fails on Windows
1067 debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1070 rescue Exception => e
1076 # call the save method for all of the botmodules
1078 @save_mutex.synchronize do
1084 # call the rescan method for all of the botmodules
1086 @save_mutex.synchronize do
1092 # channel:: channel to join
1093 # key:: optional channel key if channel is +s
1095 def join(channel, key=nil)
1097 sendq "JOIN #{channel} :#{key}", channel, 2
1099 sendq "JOIN #{channel}", channel, 2
1104 def part(channel, message="")
1105 sendq "PART #{channel} :#{message}", channel, 2
1108 # attempt to change bot's nick to +name+
1110 sendq "NICK #{name}"
1114 def mode(channel, mode, target)
1115 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1119 def kick(channel, user, msg)
1120 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1123 # m:: message asking for help
1124 # topic:: optional topic help is requested for
1125 # respond to online help requests
1127 topic = nil if topic == ""
1130 helpstr = "help topics: "
1131 helpstr += @plugins.helptopics
1132 helpstr += " (help <topic> for more info)"
1134 unless(helpstr = @plugins.help(topic))
1135 helpstr = "no help for topic #{topic}"
1141 # returns a string describing the current status of the bot (uptime etc)
1143 secs_up = Time.new - @startup_time
1144 uptime = Utils.secs_to_string secs_up
1145 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1146 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1149 # We want to respond to a hung server in a timely manner. If nothing was received
1150 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1151 # the server. If the PONG is not received within the user-defined timeout, we
1152 # assume we're in ping timeout and act accordingly.
1154 act_timeout = @config['server.ping_timeout']
1155 return if act_timeout <= 0
1157 if @last_rec && now > @last_rec + act_timeout
1159 # No previous PING pending, send a new one
1161 @last_ping = Time.now
1163 diff = now - @last_ping
1164 if diff > act_timeout
1165 debug "no PONG from server in #{diff} seconds, reconnecting"
1166 # the actual reconnect is handled in the main loop:
1167 raise TimeoutError, "no PONG from server in #{diff} seconds"
1173 def stop_server_pings
1174 # cancel previous PINGs and reset time of last RECV
1181 def irclogprivmsg(m)
1184 irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1186 irclog "* #{m.source} #{m.message}", m.target
1190 irclog "<#{m.source}> #{m.message}", m.target
1192 irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1197 # log a message. Internal use only.
1198 def log_sent(type, where, message)
1203 irclog "-=#{myself}=- #{message}", where
1205 irclog "[-=#{where}=-] #{message}", where
1210 irclog "<#{myself}> #{message}", where
1212 irclog "[msg(#{where})] #{message}", where
1219 debug "joined channel #{m.channel}"
1220 irclog "@ Joined channel #{m.channel}", m.channel
1222 irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1228 debug "left channel #{m.channel}"
1229 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1231 irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1237 debug "kicked from channel #{m.channel}"
1238 irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1240 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1245 if m.source == myself
1246 irclog "@ I set topic \"#{m.topic}\"", m.channel
1248 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel