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 # the bot's IrcAuth data
95 # the bot's BotConfig data
98 # the botclass for this bot (determines configdir among other things)
101 # used to perform actions periodically (saves configuration once per minute
105 # synchronize with this mutex while touching permanent data files:
106 # saving, flushing, cleaning up ...
107 attr_reader :save_mutex
109 # bot's Language data
116 # bot's object registry, plugins get an interface to this for persistant
117 # storage (hash interface tied to a bdb file, plugins use Accessors to store
118 # and restore objects in their own namespaces.)
119 attr_reader :registry
121 # bot's plugins. This is an instance of class Plugins
124 # bot's httputil help object, for fetching resources via http. Sets up
125 # proxies etc as defined by the bot configuration/environment
126 attr_reader :httputil
128 # server we are connected to
134 # bot User in the client/server connection
140 # bot User in the client/server connection
145 # create a new IrcBot with botclass +botclass+
146 def initialize(botclass, params = {})
147 # BotConfig for the core bot
148 # TODO should we split socket stuff into ircsocket, etc?
149 BotConfig.register BotConfigStringValue.new('server.name',
150 :default => "localhost", :requires_restart => true,
151 :desc => "What server should the bot connect to?",
153 BotConfig.register BotConfigIntegerValue.new('server.port',
154 :default => 6667, :type => :integer, :requires_restart => true,
155 :desc => "What port should the bot connect to?",
156 :validate => Proc.new {|v| v > 0}, :wizard => true)
157 BotConfig.register BotConfigBooleanValue.new('server.ssl',
158 :default => false, :requires_restart => true, :wizard => true,
159 :desc => "Use SSL to connect to this server?")
160 BotConfig.register BotConfigStringValue.new('server.password',
161 :default => false, :requires_restart => true,
162 :desc => "Password for connecting to this server (if required)",
164 BotConfig.register BotConfigStringValue.new('server.bindhost',
165 :default => false, :requires_restart => true,
166 :desc => "Specific local host or IP for the bot to bind to (if required)",
168 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
169 :default => 5, :validate => Proc.new{|v| v >= 0},
170 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
171 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
172 :default => 2.0, :validate => Proc.new{|v| v >= 0},
173 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
174 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
175 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
176 :default => 4, :validate => Proc.new{|v| v >= 0},
177 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
178 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
179 BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
180 :default => 30, :validate => Proc.new{|v| v >= 0},
181 :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
183 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
184 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
185 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
186 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
187 :requires_restart => true,
188 :desc => "local user the bot should appear to be", :wizard => true)
189 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
190 :default => [], :wizard => true,
191 :desc => "What channels the bot should always join at startup. List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'")
192 BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
194 :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
196 BotConfig.register BotConfigIntegerValue.new('core.save_every',
197 :default => 60, :validate => Proc.new{|v| v >= 0},
198 :on_change => Proc.new { |bot, v|
201 @timer.reschedule(@save_timer, v)
202 @timer.unblock(@save_timer)
204 @timer.block(@save_timer)
208 @save_timer = @timer.add(v) { bot.save }
210 # Nothing to do when v == 0
213 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
215 BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
216 :default => false, :requires_restart => true,
217 :desc => "Should the bot run as a daemon?")
219 BotConfig.register BotConfigStringValue.new('log.file',
220 :default => false, :requires_restart => true,
221 :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
222 BotConfig.register BotConfigIntegerValue.new('log.level',
223 :default => 1, :requires_restart => false,
224 :validate => Proc.new { |v| (0..5).include?(v) },
225 :on_change => Proc.new { |bot, v|
228 :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
229 BotConfig.register BotConfigIntegerValue.new('log.keep',
230 :default => 1, :requires_restart => true,
231 :validate => Proc.new { |v| v >= 0 },
232 :desc => "How many old console messages logfiles to keep")
233 BotConfig.register BotConfigIntegerValue.new('log.max_size',
234 :default => 10, :requires_restart => true,
235 :validate => Proc.new { |v| v > 0 },
236 :desc => "Maximum console messages logfile size (in megabytes)")
238 BotConfig.register BotConfigEnumValue.new('send.newlines',
239 :values => ['split', 'join'], :default => 'split',
240 :on_change => Proc.new { |bot, v|
241 bot.set_default_send_options :newlines => v.to_sym
243 :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")
244 BotConfig.register BotConfigStringValue.new('send.join_with',
246 :on_change => Proc.new { |bot, v|
247 bot.set_default_send_options :join_with => v.dup
249 :desc => "String used to replace newlines when send.newlines is set to join")
250 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
252 :validate => Proc.new { |v| v >= 0 },
253 :on_change => Proc.new { |bot, v|
254 bot.set_default_send_options :max_lines => v
256 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
257 BotConfig.register BotConfigEnumValue.new('send.overlong',
258 :values => ['split', 'truncate'], :default => 'split',
259 :on_change => Proc.new { |bot, v|
260 bot.set_default_send_options :overlong => v.to_sym
262 :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")
263 BotConfig.register BotConfigStringValue.new('send.split_at',
265 :on_change => Proc.new { |bot, v|
266 bot.set_default_send_options :split_at => Regexp.new(v)
268 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
269 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
271 :on_change => Proc.new { |bot, v|
272 bot.set_default_send_options :purge_split => v
274 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
275 BotConfig.register BotConfigStringValue.new('send.truncate_text',
276 :default => "#{Reverse}...#{Reverse}",
277 :on_change => Proc.new { |bot, v|
278 bot.set_default_send_options :truncate_text => v.dup
280 :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")
282 @argv = params[:argv]
284 unless FileTest.directory? Config::coredir
285 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
289 unless FileTest.directory? Config::datadir
290 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
294 unless botclass and not botclass.empty?
295 # We want to find a sensible default.
296 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
297 # * On Windows (at least the NT versions) we want to put our stuff in the
298 # Application Data folder.
299 # We don't use any particular O/S detection magic, exploiting the fact that
300 # Etc.getpwuid is nil on Windows
301 if Etc.getpwuid(Process::Sys.geteuid)
302 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
304 if ENV.has_key?('APPDATA')
305 botclass = ENV['APPDATA'].dup
306 botclass.gsub!("\\","/")
311 botclass = File.expand_path(botclass)
312 @botclass = botclass.gsub(/\/$/, "")
314 unless FileTest.directory? botclass
315 log "no #{botclass} directory found, creating from templates.."
316 if FileTest.exist? botclass
317 error "file #{botclass} exists but isn't a directory"
320 FileUtils.cp_r Config::datadir+'/templates', botclass
323 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
324 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
325 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
327 # Time at which the last PING was sent
329 # Time at which the last line was RECV'd from the server
332 @startup_time = Time.new
335 @config = BotConfig.configmanager
336 @config.bot_associate(self)
339 fatal e.backtrace.join("\n")
344 if @config['core.run_as_daemon']
348 @logfile = @config['log.file']
349 if @logfile.class!=String || @logfile.empty?
350 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
353 # See http://blog.humlab.umu.se/samuel/archives/000107.html
354 # for the backgrounding code
360 rescue NotImplementedError
361 warning "Could not background, fork not supported"
363 warning "Could not background. #{e.inspect}"
366 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
367 log "Redirecting standard input/output/error"
369 STDIN.reopen "/dev/null"
371 # On Windows, there's not such thing as /dev/null
374 def STDOUT.write(str=nil)
376 return str.to_s.length
378 def STDERR.write(str=nil)
379 if str.to_s.match(/:\d+: warning:/)
384 return str.to_s.length
388 # Set the new logfile and loglevel. This must be done after the daemonizing
389 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
390 $logger.datetime_format= $dateformat
391 $logger.level = @config['log.level']
392 $logger.level = $cl_loglevel if $cl_loglevel
393 $logger.level = 0 if $debug
397 @registry = BotRegistry.new self
399 @timer = Timer::Timer.new(1.0) # only need per-second granularity
400 @save_mutex = Mutex.new
401 if @config['core.save_every'] > 0
402 @save_timer = @timer.add(@config['core.save_every']) { save }
406 @quit_mutex = Mutex.new
411 @lang = Language::Language.new(self, @config['core.language'])
414 @auth = Auth::authmanager
415 @auth.bot_associate(self)
416 # @auth.load("#{botclass}/botusers.yaml")
419 fatal e.backtrace.join("\n")
423 @auth.everyone.set_default_permission("*", true)
424 @auth.botowner.password= @config['auth.password']
426 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
427 @plugins = Plugins::pluginmanager
428 @plugins.bot_associate(self)
429 @plugins.add_botmodule_dir(Config::coredir + "/utils")
430 @plugins.add_botmodule_dir(Config::coredir)
431 @plugins.add_botmodule_dir("#{botclass}/plugins")
432 @plugins.add_botmodule_dir(Config::datadir + "/plugins")
435 Utils.set_safe_save_dir("#{botclass}/safe_save")
436 @httputil = Utils::HttpUtil.new(self)
439 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
440 @client = IrcClient.new
441 myself.nick = @config['irc.nick']
443 # Channels where we are quiet
444 # It's nil when we are not quiet, an empty list when we are quiet
445 # in all channels, a list of channels otherwise
448 @client[:welcome] = proc {|data|
449 irclog "joined server #{@client.server} as #{myself}", "server"
451 @plugins.delegate("connect")
453 @config['irc.join_channels'].each { |c|
454 debug "autojoining channel #{c}"
455 if(c =~ /^(\S+)\s+(\S+)$/i)
463 # TODO the next two @client should go into rfc2812.rb, probably
464 # Since capabs are two-steps processes, server.supports[:capab]
465 # should be a three-state: nil, [], [....]
466 asked_for = { :"identify-msg" => false }
467 @client[:isupport] = proc { |data|
468 if server.supports[:capab] and !asked_for[:"identify-msg"]
469 sendq "CAPAB IDENTIFY-MSG"
470 asked_for[:"identify-msg"] = true
473 @client[:datastr] = proc { |data|
474 if data[:text] == "IDENTIFY-MSG"
475 server.capabilities[:"identify-msg"] = true
477 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
481 @client[:privmsg] = proc { |data|
482 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
483 # debug "Message source is #{data[:source].inspect}"
484 # debug "Message target is #{data[:target].inspect}"
485 # debug "Bot is #{myself.inspect}"
488 @config['irc.ignore_users'].each { |mask|
489 if m.source.matches?(server.new_netmask(mask))
498 @plugins.delegate "listen", m
499 @plugins.privmsg(m) if m.address?
502 @client[:notice] = proc { |data|
503 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
504 # pass it off to plugins that want to hear everything
505 @plugins.delegate "listen", message
507 @client[:motd] = proc { |data|
508 data[:motd].each_line { |line|
509 irclog "MOTD: #{line}", "server"
512 @client[:nicktaken] = proc { |data|
513 nickchg "#{data[:nick]}_"
514 @plugins.delegate "nicktaken", data[:nick]
516 @client[:badnick] = proc {|data|
517 warning "bad nick (#{data[:nick]})"
519 @client[:ping] = proc {|data|
520 sendq "PONG #{data[:pingid]}"
522 @client[:pong] = proc {|data|
525 @client[:nick] = proc {|data|
526 source = data[:source]
529 m = NickMessage.new(self, server, source, old, new)
531 debug "my nick is now #{new}"
533 data[:is_on].each { |ch|
534 irclog "@ #{old} is now known as #{new}", ch
536 @plugins.delegate("listen", m)
537 @plugins.delegate("nick", m)
539 @client[:quit] = proc {|data|
540 source = data[:source]
541 message = data[:message]
542 m = QuitMessage.new(self, server, source, source, message)
543 data[:was_on].each { |ch|
544 irclog "@ Quit: #{source}: #{message}", ch
546 @plugins.delegate("listen", m)
547 @plugins.delegate("quit", m)
549 @client[:mode] = proc {|data|
550 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
552 @client[:join] = proc {|data|
553 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
556 @plugins.delegate("listen", m)
557 @plugins.delegate("join", m)
559 @client[:part] = proc {|data|
560 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
563 @plugins.delegate("listen", m)
564 @plugins.delegate("part", m)
566 @client[:kick] = proc {|data|
567 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
570 @plugins.delegate("listen", m)
571 @plugins.delegate("kick", m)
573 @client[:invite] = proc {|data|
574 if data[:target] == myself
575 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
578 @client[:changetopic] = proc {|data|
579 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
582 @plugins.delegate("listen", m)
583 @plugins.delegate("topic", m)
585 @client[:topic] = proc { |data|
586 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
588 @client[:topicinfo] = proc { |data|
589 channel = data[:channel]
590 topic = channel.topic
591 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
592 m = TopicMessage.new(self, server, data[:source], channel, topic)
594 @plugins.delegate("listen", m)
595 @plugins.delegate("topic", m)
597 @client[:names] = proc { |data|
598 @plugins.delegate "names", data[:channel], data[:users]
600 @client[:unknown] = proc { |data|
601 #debug "UNKNOWN: #{data[:serverstring]}"
602 irclog data[:serverstring], ".unknown"
605 set_default_send_options :newlines => @config['send.newlines'].to_sym,
606 :join_with => @config['send.join_with'].dup,
607 :max_lines => @config['send.max_lines'],
608 :overlong => @config['send.overlong'].to_sym,
609 :split_at => Regexp.new(@config['send.split_at']),
610 :purge_split => @config['send.purge_split'],
611 :truncate_text => @config['send.truncate_text'].dup
614 def set_default_send_options(opts={})
615 # Default send options for NOTICE and PRIVMSG
616 unless defined? @default_send_options
617 @default_send_options = {
618 :queue_channel => nil, # use default queue channel
619 :queue_ring => nil, # use default queue ring
620 :newlines => :split, # or :join
621 :join_with => ' ', # by default, use a single space
622 :max_lines => 0, # maximum number of lines to send with a single command
623 :overlong => :split, # or :truncate
624 # TODO an array of splitpoints would be preferrable for this option:
625 :split_at => /\s+/, # by default, split overlong lines at whitespace
626 :purge_split => true, # should the split string be removed?
627 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
630 @default_send_options.update opts unless opts.empty?
633 # checks if we should be quiet on a channel
634 def quiet_on?(channel)
635 return false unless @quiet
636 return true if @quiet.empty?
637 return @quiet.include?(channel.to_s)
640 def set_quiet(channel=nil)
642 @quiet << channel.to_s unless @quiet.include?(channel.to_s)
648 def reset_quiet(channel=nil)
650 @quiet.delete_if { |x| x == channel.to_s }
656 # things to do when we receive a signal
658 debug "received #{sig}, queueing quit"
660 quit unless @quit_mutex.locked?
661 debug "interrupted #{$interrupted} times"
669 # connect the bot to IRC
672 trap("SIGINT") { got_sig("SIGINT") }
673 trap("SIGTERM") { got_sig("SIGTERM") }
674 trap("SIGHUP") { got_sig("SIGHUP") }
675 rescue ArgumentError => e
676 debug "failed to trap signals (#{e.inspect}): running on Windows?"
678 debug "failed to trap signals: #{e.inspect}"
681 quit if $interrupted > 0
684 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
686 quit if $interrupted > 0
687 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
688 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
689 quit if $interrupted > 0
692 # begin event handling loop
696 quit if $interrupted > 0
700 while @socket.connected?
701 quit if $interrupted > 0
703 # Wait for messages and process them as they arrive. If nothing is
704 # received, we call the ping_server() method that will PING the
705 # server if appropriate, or raise a TimeoutError if no PONG has been
706 # received in the user-chosen timeout since the last PING sent.
708 break unless reply = @socket.gets
710 @client.process reply
716 # I despair of this. Some of my users get "connection reset by peer"
717 # exceptions that ARENT SocketError's. How am I supposed to handle
722 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
723 error "network exception: #{e.class}: #{e}"
724 debug e.backtrace.join("\n")
725 rescue BDB::Fatal => e
726 fatal "fatal bdb error: #{e.class}: #{e}"
727 fatal e.backtrace.join("\n")
729 # Why restart? DB problems are serious stuff ...
730 # restart("Oops, we seem to have registry problems ...")
733 rescue Exception => e
734 error "non-net exception: #{e.class}: #{e}"
735 error e.backtrace.join("\n")
737 fatal "unexpected exception: #{e.class}: #{e}"
738 fatal e.backtrace.join("\n")
745 if @socket.connected?
752 quit if $interrupted > 0
754 log "waiting to reconnect"
755 sleep @config['server.reconnect_wait']
759 # type:: message type
760 # where:: message target
761 # message:: message text
762 # send message +message+ of type +type+ to target +where+
763 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
764 # relevant say() or notice() methods. This one should be used for IRCd
765 # extensions you want to use in modules.
766 def sendmsg(type, where, original_message, options={})
767 opts = @default_send_options.merge(options)
769 # For starters, set up appropriate queue channels and rings
770 mchan = opts[:queue_channel]
771 mring = opts[:queue_ring]
788 message = original_message.to_s.gsub(/[\r\n]+/, "\n")
791 lines = [message.gsub("\n", opts[:join_with])]
794 message.each_line { |line|
796 next unless(line.length > 0)
800 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
803 # The IRC protocol requires that each raw message must be not longer
804 # than 512 characters. From this length with have to subtract the EOL
805 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
806 # that will be prepended by the server to all of our messages.
808 # The maximum raw message length we can send is therefore 512 - 2 - 2
809 # minus the length of our hostmask.
811 max_len = 508 - myself.fullform.length
813 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
814 # will have a + or - prepended
815 if server.capabilities[:"identify-msg"]
819 # When splitting the message, we'll be prefixing the following string:
820 # (e.g. "PRIVMSG #rbot :")
821 fixed = "#{type} #{where} :"
823 # And this is what's left
824 left = max_len - fixed.length
829 split_at = opts[:split_at]
831 truncate = opts[:truncate_text]
832 truncate = @default_send_options[:truncate_text] if truncate.length > left
833 truncate = "" if truncate.length > left
835 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
838 # Counter to check the number of lines sent by this command
840 max_lines = opts[:max_lines]
845 if max_lines > 0 and cmd_lines == max_lines - 1
846 truncate = opts[:truncate_text]
847 truncate = @default_send_options[:truncate_text] if truncate.length > left
848 truncate = "" if truncate.length > left
851 if(left >= msg.length) and not maxed
852 sendq "#{fixed}#{msg}", chan, ring
853 log_sent(type, where, msg)
858 line.replace msg.slice(0, left-truncate.length)
859 # line.sub!(/\s+\S*$/, truncate)
861 raise "PROGRAMMER ERROR! #{line.inspect} of length #{line.length} > #{left}" if line.length > left
862 sendq "#{fixed}#{line}", chan, ring
863 log_sent(type, where, line)
866 line.replace msg.slice!(0, left)
867 lastspace = line.rindex(opts[:split_at])
869 msg.replace line.slice!(lastspace, line.length) + msg
870 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
872 sendq "#{fixed}#{line}", chan, ring
873 log_sent(type, where, line)
875 end while(msg.length > 0)
879 # queue an arbitraty message for the server
880 def sendq(message="", chan=nil, ring=0)
882 @socket.queue(message, chan, ring)
885 # send a notice message to channel/nick +where+
886 def notice(where, message, options={})
887 unless quiet_on?(where)
888 sendmsg "NOTICE", where, message, options
892 # say something (PRIVMSG) to channel/nick +where+
893 def say(where, message, options={})
894 unless quiet_on?(where)
895 sendmsg "PRIVMSG", where, message, options
899 # perform a CTCP action with message +message+ to channel/nick +where+
900 def action(where, message, options={})
901 mchan = options.fetch(:queue_channel, nil)
902 mring = options.fetch(:queue_ring, nil)
918 # FIXME doesn't check message length. Can we make this exploit sendmsg?
919 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
922 irclog "* #{myself} #{message}", where
924 irclog "* #{myself}[#{where}] #{message}", where
928 # quick way to say "okay" (or equivalent) to +where+
930 say where, @lang.get("okay")
933 # log IRC-related message +message+ to a file determined by +where+.
934 # +where+ can be a channel name, or a nick for private message logging
935 def irclog(message, where="server")
936 message = message.chomp
937 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
938 where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
939 unless(@logs.has_key?(where))
940 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
941 @logs[where].sync = true
943 @logs[where].puts "[#{stamp}] #{message}"
944 #debug "[#{stamp}] <#{where}> #{message}"
947 # set topic of channel +where+ to +topic+
948 def topic(where, topic)
949 sendq "TOPIC #{where} :#{topic}", where, 2
952 # disconnect from the server and cleanup all plugins and modules
953 def shutdown(message = nil)
954 @quit_mutex.synchronize do
955 debug "Shutting down ..."
956 ## No we don't restore them ... let everything run through
958 # trap("SIGINT", "DEFAULT")
959 # trap("SIGTERM", "DEFAULT")
960 # trap("SIGHUP", "DEFAULT")
962 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
964 message = @lang.get("quit") if (message.nil? || message.empty?)
965 if @socket.connected?
966 debug "Clearing socket"
968 debug "Sending quit message"
969 @socket.emergency_puts "QUIT :#{message}"
970 debug "Flushing socket"
972 debug "Shutting down socket"
975 debug "Logging quits"
976 server.channels.each { |ch|
977 irclog "@ quit (#{message})", ch
982 @save_mutex.synchronize do
985 # debug "Closing registries"
987 debug "Cleaning up the db environment"
989 log "rbot quit (#{message})"
993 # message:: optional IRC quit message
994 # quit IRC, shutdown the bot
995 def quit(message=nil)
1003 # totally shutdown and respawn the bot
1004 def restart(message = false)
1005 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1007 sleep @config['server.reconnect_wait']
1009 # Note, this fails on Windows
1013 # call the save method for all of the botmodules
1015 @save_mutex.synchronize do
1021 # call the rescan method for all of the botmodules
1023 @save_mutex.synchronize do
1029 # channel:: channel to join
1030 # key:: optional channel key if channel is +s
1032 def join(channel, key=nil)
1034 sendq "JOIN #{channel} :#{key}", channel, 2
1036 sendq "JOIN #{channel}", channel, 2
1041 def part(channel, message="")
1042 sendq "PART #{channel} :#{message}", channel, 2
1045 # attempt to change bot's nick to +name+
1047 sendq "NICK #{name}"
1051 def mode(channel, mode, target)
1052 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1056 def kick(channel, user, msg)
1057 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1060 # m:: message asking for help
1061 # topic:: optional topic help is requested for
1062 # respond to online help requests
1064 topic = nil if topic == ""
1067 helpstr = "help topics: "
1068 helpstr += @plugins.helptopics
1069 helpstr += " (help <topic> for more info)"
1071 unless(helpstr = @plugins.help(topic))
1072 helpstr = "no help for topic #{topic}"
1078 # returns a string describing the current status of the bot (uptime etc)
1080 secs_up = Time.new - @startup_time
1081 uptime = Utils.secs_to_string secs_up
1082 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1083 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1086 # We want to respond to a hung server in a timely manner. If nothing was received
1087 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1088 # the server. If the PONG is not received within the user-defined timeout, we
1089 # assume we're in ping timeout and act accordingly.
1091 act_timeout = @config['server.ping_timeout']
1092 return if act_timeout <= 0
1094 if @last_rec && now > @last_rec + act_timeout
1096 # No previous PING pending, send a new one
1098 @last_ping = Time.now
1100 diff = now - @last_ping
1101 if diff > act_timeout
1102 debug "no PONG from server in #{diff} seconds, reconnecting"
1103 # the actual reconnect is handled in the main loop:
1104 raise TimeoutError, "no PONG from server in #{diff} seconds"
1110 def stop_server_pings
1111 # cancel previous PINGs and reset time of last RECV
1118 def irclogprivmsg(m)
1121 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1123 irclog "* #{m.sourcenick} #{m.message}", m.target
1127 irclog "<#{m.sourcenick}> #{m.message}", m.target
1129 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1134 # log a message. Internal use only.
1135 def log_sent(type, where, message)
1140 irclog "-=#{myself}=- #{message}", where
1142 irclog "[-=#{where}=-] #{message}", where
1147 irclog "<#{myself}> #{message}", where
1149 irclog "[msg(#{where})] #{message}", where
1156 debug "joined channel #{m.channel}"
1157 irclog "@ Joined channel #{m.channel}", m.channel
1159 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1165 debug "left channel #{m.channel}"
1166 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1168 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1174 debug "kicked from channel #{m.channel}"
1175 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1177 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1182 if m.source == myself
1183 irclog "@ I set topic \"#{m.topic}\"", m.channel
1185 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel