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_reader :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 BotConfigStringValue.new('server.name',
151 :default => "localhost", :requires_restart => true,
152 :desc => "What server should the bot connect to?",
154 BotConfig.register BotConfigIntegerValue.new('server.port',
155 :default => 6667, :type => :integer, :requires_restart => true,
156 :desc => "What port should the bot connect to?",
157 :validate => Proc.new {|v| v > 0}, :wizard => true)
158 BotConfig.register BotConfigBooleanValue.new('server.ssl',
159 :default => false, :requires_restart => true, :wizard => true,
160 :desc => "Use SSL to connect to this server?")
161 BotConfig.register BotConfigStringValue.new('server.password',
162 :default => false, :requires_restart => true,
163 :desc => "Password for connecting to this server (if required)",
165 BotConfig.register BotConfigStringValue.new('server.bindhost',
166 :default => false, :requires_restart => true,
167 :desc => "Specific local host or IP for the bot to bind to (if required)",
169 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
170 :default => 5, :validate => Proc.new{|v| v >= 0},
171 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
172 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
173 :default => 2.0, :validate => Proc.new{|v| v >= 0},
174 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
175 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
176 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
177 :default => 4, :validate => Proc.new{|v| v >= 0},
178 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
179 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
180 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
181 :default => 30, :validate => Proc.new{|v| v >= 0},
182 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
184 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
185 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
186 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
187 BotConfig.register BotConfigStringValue.new('irc.name',
188 :default => "Ruby bot", :requires_restart => true,
189 :desc => "IRC realname the bot should use")
190 BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
191 :default => true, :requires_restart => true,
192 :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
193 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
194 :requires_restart => true,
195 :desc => "local user the bot should appear to be", :wizard => true)
196 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
197 :default => [], :wizard => true,
198 :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'")
199 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
201 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
203 BotConfig.register BotConfigIntegerValue.new('core.save_every',
204 :default => 60, :validate => Proc.new{|v| v >= 0},
205 :on_change => Proc.new { |bot, v|
208 @timer.reschedule(@save_timer, v)
209 @timer.unblock(@save_timer)
211 @timer.block(@save_timer)
215 @save_timer = @timer.add(v) { bot.save }
217 # Nothing to do when v == 0
220 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
222 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
223 :default => false, :requires_restart => true,
224 :desc => "Should the bot run as a daemon?")
226 BotConfig.register BotConfigStringValue.new('log.file',
227 :default => false, :requires_restart => true,
228 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
229 BotConfig.register BotConfigIntegerValue.new('log.level',
230 :default => 1, :requires_restart => false,
231 :validate => Proc.new { |v| (0..5).include?(v) },
232 :on_change => Proc.new { |bot, v|
235 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
236 BotConfig.register BotConfigIntegerValue.new('log.keep',
237 :default => 1, :requires_restart => true,
238 :validate => Proc.new { |v| v >= 0 },
239 :desc => "How many old console messages logfiles to keep")
240 BotConfig.register BotConfigIntegerValue.new('log.max_size',
241 :default => 10, :requires_restart => true,
242 :validate => Proc.new { |v| v > 0 },
243 :desc => "Maximum console messages logfile size (in megabytes)")
245 BotConfig.register BotConfigEnumValue.new('send.newlines',
246 :values => ['split', 'join'], :default => 'split',
247 :on_change => Proc.new { |bot, v|
248 bot.set_default_send_options :newlines => v.to_sym
250 :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")
251 BotConfig.register BotConfigStringValue.new('send.join_with',
253 :on_change => Proc.new { |bot, v|
254 bot.set_default_send_options :join_with => v.dup
256 :desc => "String used to replace newlines when send.newlines is set to join")
257 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
259 :validate => Proc.new { |v| v >= 0 },
260 :on_change => Proc.new { |bot, v|
261 bot.set_default_send_options :max_lines => v
263 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
264 BotConfig.register BotConfigEnumValue.new('send.overlong',
265 :values => ['split', 'truncate'], :default => 'split',
266 :on_change => Proc.new { |bot, v|
267 bot.set_default_send_options :overlong => v.to_sym
269 :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")
270 BotConfig.register BotConfigStringValue.new('send.split_at',
272 :on_change => Proc.new { |bot, v|
273 bot.set_default_send_options :split_at => Regexp.new(v)
275 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
276 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
278 :on_change => Proc.new { |bot, v|
279 bot.set_default_send_options :purge_split => v
281 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
282 BotConfig.register BotConfigStringValue.new('send.truncate_text',
283 :default => "#{Reverse}...#{Reverse}",
284 :on_change => Proc.new { |bot, v|
285 bot.set_default_send_options :truncate_text => v.dup
287 :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")
289 @argv = params[:argv]
291 unless FileTest.directory? Config::coredir
292 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
296 unless FileTest.directory? Config::datadir
297 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
301 unless botclass and not botclass.empty?
302 # We want to find a sensible default.
303 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
304 # * On Windows (at least the NT versions) we want to put our stuff in the
305 # Application Data folder.
306 # We don't use any particular O/S detection magic, exploiting the fact that
307 # Etc.getpwuid is nil on Windows
308 if Etc.getpwuid(Process::Sys.geteuid)
309 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
311 if ENV.has_key?('APPDATA')
312 botclass = ENV['APPDATA'].dup
313 botclass.gsub!("\\","/")
318 botclass = File.expand_path(botclass)
319 @botclass = botclass.gsub(/\/$/, "")
321 unless FileTest.directory? botclass
322 log "no #{botclass} directory found, creating from templates.."
323 if FileTest.exist? botclass
324 error "file #{botclass} exists but isn't a directory"
327 FileUtils.cp_r Config::datadir+'/templates', botclass
330 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
331 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
332 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
334 # Time at which the last PING was sent
336 # Time at which the last line was RECV'd from the server
339 @startup_time = Time.new
342 @config = BotConfig.configmanager
343 @config.bot_associate(self)
346 fatal e.backtrace.join("\n")
351 if @config['core.run_as_daemon']
355 @logfile = @config['log.file']
356 if @logfile.class!=String || @logfile.empty?
357 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
360 # See http://blog.humlab.umu.se/samuel/archives/000107.html
361 # for the backgrounding code
367 rescue NotImplementedError
368 warning "Could not background, fork not supported"
370 warning "Could not background. #{e.inspect}"
373 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
374 log "Redirecting standard input/output/error"
376 STDIN.reopen "/dev/null"
378 # On Windows, there's not such thing as /dev/null
381 def STDOUT.write(str=nil)
385 def STDERR.write(str=nil)
386 if str.to_s.match(/:\d+: warning:/)
395 # Set the new logfile and loglevel. This must be done after the daemonizing
396 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
397 $logger.datetime_format= $dateformat
398 $logger.level = @config['log.level']
399 $logger.level = $cl_loglevel if $cl_loglevel
400 $logger.level = 0 if $debug
404 @registry = BotRegistry.new self
406 @timer = Timer::Timer.new(1.0) # only need per-second granularity
407 @save_mutex = Mutex.new
408 if @config['core.save_every'] > 0
409 @save_timer = @timer.add(@config['core.save_every']) { save }
413 @quit_mutex = Mutex.new
418 @lang = Language::Language.new(self, @config['core.language'])
421 @auth = Auth::authmanager
422 @auth.bot_associate(self)
423 # @auth.load("#{botclass}/botusers.yaml")
426 fatal e.backtrace.join("\n")
430 @auth.everyone.set_default_permission("*", true)
431 @auth.botowner.password= @config['auth.password']
433 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
434 @plugins = Plugins::pluginmanager
435 @plugins.bot_associate(self)
436 @plugins.add_botmodule_dir(Config::coredir + "/utils")
437 @plugins.add_botmodule_dir(Config::coredir)
438 @plugins.add_botmodule_dir("#{botclass}/plugins")
439 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
442 Utils.set_safe_save_dir("#{botclass}/safe_save")
443 @httputil = Utils::HttpUtil.new(self)
446 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
449 # Channels where we are quiet
450 # Array of channels names where the bot should be quiet
451 # '*' means all channels
455 @client[:welcome] = proc {|data|
456 irclog "joined server #{@client.server} as #{myself}", "server"
458 @plugins.delegate("connect")
460 @config['irc.join_channels'].each { |c|
461 debug "autojoining channel #{c}"
462 if(c =~ /^(\S+)\s+(\S+)$/i)
470 # TODO the next two @client should go into rfc2812.rb, probably
471 # Since capabs are two-steps processes, server.supports[:capab]
472 # should be a three-state: nil, [], [....]
473 asked_for = { :"identify-msg" => false }
474 @client[:isupport] = proc { |data|
475 if server.supports[:capab] and !asked_for[:"identify-msg"]
476 sendq "CAPAB IDENTIFY-MSG"
477 asked_for[:"identify-msg"] = true
480 @client[:datastr] = proc { |data|
481 if data[:text] == "IDENTIFY-MSG"
482 server.capabilities[:"identify-msg"] = true
484 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
488 @client[:privmsg] = proc { |data|
489 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
490 # debug "Message source is #{data[:source].inspect}"
491 # debug "Message target is #{data[:target].inspect}"
492 # debug "Bot is #{myself.inspect}"
495 @config['irc.ignore_users'].each { |mask|
496 if m.source.matches?(server.new_netmask(mask))
505 @plugins.delegate "listen", m
506 @plugins.privmsg(m) if m.address?
508 @plugins.delegate "unreplied", m
512 @client[:notice] = proc { |data|
513 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
514 # pass it off to plugins that want to hear everything
515 @plugins.delegate "listen", message
517 @client[:motd] = proc { |data|
518 data[:motd].each_line { |line|
519 irclog "MOTD: #{line}", "server"
522 @client[:nicktaken] = proc { |data|
523 new = "#{data[:nick]}_"
525 # If we're setting our nick at connection because our choice was taken,
526 # we have to fix our nick manually, because there will be no NICK message
527 # yo inform us that our nick has been changed.
528 if data[:target] == '*'
529 debug "setting my connection nick to #{new}"
532 @plugins.delegate "nicktaken", data[:nick]
534 @client[:badnick] = proc {|data|
535 arning "bad nick (#{data[:nick]})"
537 @client[:ping] = proc {|data|
538 sendq "PONG #{data[:pingid]}"
540 @client[:pong] = proc {|data|
543 @client[:nick] = proc {|data|
544 # debug "Message source is #{data[:source].inspect}"
545 # debug "Bot is #{myself.inspect}"
546 source = data[:source]
549 m = NickMessage.new(self, server, source, old, new)
551 debug "my nick is now #{new}"
553 data[:is_on].each { |ch|
554 irclog "@ #{old} is now known as #{new}", ch
556 @plugins.delegate("listen", m)
557 @plugins.delegate("nick", m)
559 @client[:quit] = proc {|data|
560 source = data[:source]
561 message = data[:message]
562 m = QuitMessage.new(self, server, source, source, message)
563 data[:was_on].each { |ch|
564 irclog "@ Quit: #{source}: #{message}", ch
566 @plugins.delegate("listen", m)
567 @plugins.delegate("quit", m)
569 @client[:mode] = proc {|data|
570 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
572 @client[:join] = proc {|data|
573 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
576 @plugins.delegate("listen", m)
577 @plugins.delegate("join", m)
579 @client[:part] = proc {|data|
580 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
583 @plugins.delegate("listen", m)
584 @plugins.delegate("part", m)
586 @client[:kick] = proc {|data|
587 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
590 @plugins.delegate("listen", m)
591 @plugins.delegate("kick", m)
593 @client[:invite] = proc {|data|
594 if data[:target] == myself
595 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
598 @client[:changetopic] = proc {|data|
599 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
602 @plugins.delegate("listen", m)
603 @plugins.delegate("topic", m)
605 @client[:topic] = proc { |data|
606 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
608 @client[:topicinfo] = proc { |data|
609 channel = data[:channel]
610 topic = channel.topic
611 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
612 m = TopicMessage.new(self, server, data[:source], channel, topic)
614 @plugins.delegate("listen", m)
615 @plugins.delegate("topic", m)
617 @client[:names] = proc { |data|
618 @plugins.delegate "names", data[:channel], data[:users]
620 @client[:unknown] = proc { |data|
621 #debug "UNKNOWN: #{data[:serverstring]}"
622 irclog data[:serverstring], ".unknown"
625 set_default_send_options :newlines => @config['send.newlines'].to_sym,
626 :join_with => @config['send.join_with'].dup,
627 :max_lines => @config['send.max_lines'],
628 :overlong => @config['send.overlong'].to_sym,
629 :split_at => Regexp.new(@config['send.split_at']),
630 :purge_split => @config['send.purge_split'],
631 :truncate_text => @config['send.truncate_text'].dup
634 def set_default_send_options(opts={})
635 # Default send options for NOTICE and PRIVMSG
636 unless defined? @default_send_options
637 @default_send_options = {
638 :queue_channel => nil, # use default queue channel
639 :queue_ring => nil, # use default queue ring
640 :newlines => :split, # or :join
641 :join_with => ' ', # by default, use a single space
642 :max_lines => 0, # maximum number of lines to send with a single command
643 :overlong => :split, # or :truncate
644 # TODO an array of splitpoints would be preferrable for this option:
645 :split_at => /\s+/, # by default, split overlong lines at whitespace
646 :purge_split => true, # should the split string be removed?
647 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
650 @default_send_options.update opts unless opts.empty?
653 # checks if we should be quiet on a channel
654 def quiet_on?(channel)
655 return @quiet.include?('*') || @quiet.include?(channel.downcase)
658 def set_quiet(channel)
660 ch = channel.downcase.dup
661 @quiet << ch unless @quiet.include?(ch)
668 def reset_quiet(channel)
670 @quiet.delete channel.downcase
676 # things to do when we receive a signal
678 debug "received #{sig}, queueing quit"
680 quit unless @quit_mutex.locked?
681 debug "interrupted #{$interrupted} times"
689 # connect the bot to IRC
692 trap("SIGINT") { got_sig("SIGINT") }
693 trap("SIGTERM") { got_sig("SIGTERM") }
694 trap("SIGHUP") { got_sig("SIGHUP") }
695 rescue ArgumentError => e
696 debug "failed to trap signals (#{e.inspect}): running on Windows?"
698 debug "failed to trap signals: #{e.inspect}"
701 quit if $interrupted > 0
704 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
706 quit if $interrupted > 0
708 realname = @config['irc.name'].clone || 'Ruby bot'
709 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
711 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
712 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :#{realname}"
713 quit if $interrupted > 0
714 myself.nick = @config['irc.nick']
715 myself.user = @config['irc.user']
718 # begin event handling loop
722 quit if $interrupted > 0
727 while @socket.connected?
728 quit if $interrupted > 0
730 # Wait for messages and process them as they arrive. If nothing is
731 # received, we call the ping_server() method that will PING the
732 # server if appropriate, or raise a TimeoutError if no PONG has been
733 # received in the user-chosen timeout since the last PING sent.
735 break unless reply = @socket.gets
737 @client.process reply
743 # I despair of this. Some of my users get "connection reset by peer"
744 # exceptions that ARENT SocketError's. How am I supposed to handle
749 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
750 error "network exception: #{e.class}: #{e}"
751 debug e.backtrace.join("\n")
753 rescue BDB::Fatal => e
754 fatal "fatal bdb error: #{e.class}: #{e}"
755 fatal e.backtrace.join("\n")
757 # Why restart? DB problems are serious stuff ...
758 # restart("Oops, we seem to have registry problems ...")
761 rescue Exception => e
762 error "non-net exception: #{e.class}: #{e}"
763 error e.backtrace.join("\n")
766 fatal "unexpected exception: #{e.class}: #{e}"
767 fatal e.backtrace.join("\n")
774 log "\n\nDisconnected\n\n"
776 quit if $interrupted > 0
778 log "\n\nWaiting to reconnect\n\n"
779 sleep @config['server.reconnect_wait']
783 # type:: message type
784 # where:: message target
785 # message:: message text
786 # send message +message+ of type +type+ to target +where+
787 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
788 # relevant say() or notice() methods. This one should be used for IRCd
789 # extensions you want to use in modules.
790 def sendmsg(type, where, original_message, options={})
791 opts = @default_send_options.merge(options)
793 # For starters, set up appropriate queue channels and rings
794 mchan = opts[:queue_channel]
795 mring = opts[:queue_ring]
812 message = original_message.to_s.gsub(/[\r\n]+/, "\n")
815 lines = [message.gsub("\n", opts[:join_with])]
818 message.each_line { |line|
820 next unless(line.size > 0)
824 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
827 # The IRC protocol requires that each raw message must be not longer
828 # than 512 characters. From this length with have to subtract the EOL
829 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
830 # that will be prepended by the server to all of our messages.
832 # The maximum raw message length we can send is therefore 512 - 2 - 2
833 # minus the length of our hostmask.
835 max_len = 508 - myself.fullform.size
837 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
838 # will have a + or - prepended
839 if server.capabilities[:"identify-msg"]
843 # When splitting the message, we'll be prefixing the following string:
844 # (e.g. "PRIVMSG #rbot :")
845 fixed = "#{type} #{where} :"
847 # And this is what's left
848 left = max_len - fixed.size
853 split_at = opts[:split_at]
855 truncate = opts[:truncate_text]
856 truncate = @default_send_options[:truncate_text] if truncate.size > left
857 truncate = "" if truncate.size > left
859 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
862 # Counter to check the number of lines sent by this command
864 max_lines = opts[:max_lines]
869 if max_lines > 0 and cmd_lines == max_lines - 1
870 truncate = opts[:truncate_text]
871 truncate = @default_send_options[:truncate_text] if truncate.size > left
872 truncate = "" if truncate.size > left
875 if(left >= msg.size) and not maxed
876 sendq "#{fixed}#{msg}", chan, ring
877 log_sent(type, where, msg)
882 line.replace msg.slice(0, left-truncate.size)
883 # line.sub!(/\s+\S*$/, truncate)
885 raise "PROGRAMMER ERROR! #{line.inspect} of size #{line.size} > #{left}" if line.size > left
886 sendq "#{fixed}#{line}", chan, ring
887 log_sent(type, where, line)
890 line.replace msg.slice!(0, left)
891 lastspace = line.rindex(opts[:split_at])
893 msg.replace line.slice!(lastspace, line.size) + msg
894 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
896 sendq "#{fixed}#{line}", chan, ring
897 log_sent(type, where, line)
899 end while(msg.size > 0)
903 # queue an arbitraty message for the server
904 def sendq(message="", chan=nil, ring=0)
906 @socket.queue(message, chan, ring)
909 # send a notice message to channel/nick +where+
910 def notice(where, message, options={})
911 return if where.kind_of?(Channel) and quiet_on?(where)
912 sendmsg "NOTICE", where, message, options
915 # say something (PRIVMSG) to channel/nick +where+
916 def say(where, message, options={})
917 return if where.kind_of?(Channel) and quiet_on?(where)
918 sendmsg "PRIVMSG", where, message, options
921 # perform a CTCP action with message +message+ to channel/nick +where+
922 def action(where, message, options={})
923 return if where.kind_of?(Channel) and quiet_on?(where)
924 mchan = options.fetch(:queue_channel, nil)
925 mring = options.fetch(:queue_ring, nil)
941 # FIXME doesn't check message length. Can we make this exploit sendmsg?
942 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
945 irclog "* #{myself} #{message}", where
947 irclog "* #{myself}[#{where}] #{message}", where
951 # quick way to say "okay" (or equivalent) to +where+
953 say where, @lang.get("okay")
956 # log IRC-related message +message+ to a file determined by +where+.
957 # +where+ can be a channel name, or a nick for private message logging
958 def irclog(message, where="server")
959 message = message.chomp
960 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
961 where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
962 unless(@logs.has_key?(where))
963 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
964 @logs[where].sync = true
966 @logs[where].puts "[#{stamp}] #{message}"
967 #debug "[#{stamp}] <#{where}> #{message}"
970 # set topic of channel +where+ to +topic+
971 def topic(where, topic)
972 sendq "TOPIC #{where} :#{topic}", where, 2
975 def disconnect(message = nil)
976 message = @lang.get("quit") if (message.nil? || message.empty?)
977 if @socket.connected?
978 debug "Clearing socket"
980 debug "Sending quit message"
981 @socket.emergency_puts "QUIT :#{message}"
982 debug "Flushing socket"
984 debug "Shutting down socket"
987 debug "Logging quits"
988 server.channels.each { |ch|
989 irclog "@ quit (#{message})", ch
995 # disconnect from the server and cleanup all plugins and modules
996 def shutdown(message = nil)
997 @quit_mutex.synchronize do
998 debug "Shutting down ..."
999 ## No we don't restore them ... let everything run through
1001 # trap("SIGINT", "DEFAULT")
1002 # trap("SIGTERM", "DEFAULT")
1003 # trap("SIGHUP", "DEFAULT")
1005 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1011 @save_mutex.synchronize do
1014 # debug "Closing registries"
1016 debug "Cleaning up the db environment"
1018 log "rbot quit (#{message})"
1022 # message:: optional IRC quit message
1023 # quit IRC, shutdown the bot
1024 def quit(message=nil)
1032 # totally shutdown and respawn the bot
1033 def restart(message = false)
1034 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1036 sleep @config['server.reconnect_wait']
1038 # Note, this fails on Windows
1042 # call the save method for all of the botmodules
1044 @save_mutex.synchronize do
1050 # call the rescan method for all of the botmodules
1052 @save_mutex.synchronize do
1058 # channel:: channel to join
1059 # key:: optional channel key if channel is +s
1061 def join(channel, key=nil)
1063 sendq "JOIN #{channel} :#{key}", channel, 2
1065 sendq "JOIN #{channel}", channel, 2
1070 def part(channel, message="")
1071 sendq "PART #{channel} :#{message}", channel, 2
1074 # attempt to change bot's nick to +name+
1076 sendq "NICK #{name}"
1080 def mode(channel, mode, target)
1081 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1085 def kick(channel, user, msg)
1086 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1089 # m:: message asking for help
1090 # topic:: optional topic help is requested for
1091 # respond to online help requests
1093 topic = nil if topic == ""
1096 helpstr = "help topics: "
1097 helpstr += @plugins.helptopics
1098 helpstr += " (help <topic> for more info)"
1100 unless(helpstr = @plugins.help(topic))
1101 helpstr = "no help for topic #{topic}"
1107 # returns a string describing the current status of the bot (uptime etc)
1109 secs_up = Time.new - @startup_time
1110 uptime = Utils.secs_to_string secs_up
1111 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1112 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1115 # We want to respond to a hung server in a timely manner. If nothing was received
1116 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1117 # the server. If the PONG is not received within the user-defined timeout, we
1118 # assume we're in ping timeout and act accordingly.
1120 act_timeout = @config['server.ping_timeout']
1121 return if act_timeout <= 0
1123 if @last_rec && now > @last_rec + act_timeout
1125 # No previous PING pending, send a new one
1127 @last_ping = Time.now
1129 diff = now - @last_ping
1130 if diff > act_timeout
1131 debug "no PONG from server in #{diff} seconds, reconnecting"
1132 # the actual reconnect is handled in the main loop:
1133 raise TimeoutError, "no PONG from server in #{diff} seconds"
1139 def stop_server_pings
1140 # cancel previous PINGs and reset time of last RECV
1147 def irclogprivmsg(m)
1150 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1152 irclog "* #{m.sourcenick} #{m.message}", m.target
1156 irclog "<#{m.sourcenick}> #{m.message}", m.target
1158 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1163 # log a message. Internal use only.
1164 def log_sent(type, where, message)
1169 irclog "-=#{myself}=- #{message}", where
1171 irclog "[-=#{where}=-] #{message}", where
1176 irclog "<#{myself}> #{message}", where
1178 irclog "[msg(#{where})] #{message}", where
1185 debug "joined channel #{m.channel}"
1186 irclog "@ Joined channel #{m.channel}", m.channel
1188 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1194 debug "left channel #{m.channel}"
1195 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1197 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1203 debug "kicked from channel #{m.channel}"
1204 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1206 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1211 if m.source == myself
1212 irclog "@ I set topic \"#{m.topic}\"", m.channel
1214 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel