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 BotConfigArrayValue.new('plugins.path',
246 :wizard => true, :default => ['(default)', '(default)/contrib'],
247 :requires_restart => false,
248 :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
249 :desc => "Where the bot should look for plugin. List multiple directories using commas to separate. Use '(default)' for default prepackaged plugins collection, '(default)/contrib' for prepackaged unsupported plugins collection")
251 BotConfig.register BotConfigEnumValue.new('send.newlines',
252 :values => ['split', 'join'], :default => 'split',
253 :on_change => Proc.new { |bot, v|
254 bot.set_default_send_options :newlines => v.to_sym
256 :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")
257 BotConfig.register BotConfigStringValue.new('send.join_with',
259 :on_change => Proc.new { |bot, v|
260 bot.set_default_send_options :join_with => v.dup
262 :desc => "String used to replace newlines when send.newlines is set to join")
263 BotConfig.register BotConfigIntegerValue.new('send.max_lines',
265 :validate => Proc.new { |v| v >= 0 },
266 :on_change => Proc.new { |bot, v|
267 bot.set_default_send_options :max_lines => v
269 :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
270 BotConfig.register BotConfigEnumValue.new('send.overlong',
271 :values => ['split', 'truncate'], :default => 'split',
272 :on_change => Proc.new { |bot, v|
273 bot.set_default_send_options :overlong => v.to_sym
275 :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")
276 BotConfig.register BotConfigStringValue.new('send.split_at',
278 :on_change => Proc.new { |bot, v|
279 bot.set_default_send_options :split_at => Regexp.new(v)
281 :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
282 BotConfig.register BotConfigBooleanValue.new('send.purge_split',
284 :on_change => Proc.new { |bot, v|
285 bot.set_default_send_options :purge_split => v
287 :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
288 BotConfig.register BotConfigStringValue.new('send.truncate_text',
289 :default => "#{Reverse}...#{Reverse}",
290 :on_change => Proc.new { |bot, v|
291 bot.set_default_send_options :truncate_text => v.dup
293 :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")
295 @argv = params[:argv]
297 unless FileTest.directory? Config::coredir
298 error "core directory '#{Config::coredir}' not found, did you setup.rb?"
302 unless FileTest.directory? Config::datadir
303 error "data directory '#{Config::datadir}' not found, did you setup.rb?"
307 unless botclass and not botclass.empty?
308 # We want to find a sensible default.
309 # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
310 # * On Windows (at least the NT versions) we want to put our stuff in the
311 # Application Data folder.
312 # We don't use any particular O/S detection magic, exploiting the fact that
313 # Etc.getpwuid is nil on Windows
314 if Etc.getpwuid(Process::Sys.geteuid)
315 botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
317 if ENV.has_key?('APPDATA')
318 botclass = ENV['APPDATA'].dup
319 botclass.gsub!("\\","/")
324 botclass = File.expand_path(botclass)
325 @botclass = botclass.gsub(/\/$/, "")
327 unless FileTest.directory? botclass
328 log "no #{botclass} directory found, creating from templates.."
329 if FileTest.exist? botclass
330 error "file #{botclass} exists but isn't a directory"
333 FileUtils.cp_r Config::datadir+'/templates', botclass
336 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
337 Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
338 Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
340 # Time at which the last PING was sent
342 # Time at which the last line was RECV'd from the server
345 @startup_time = Time.new
348 @config = BotConfig.configmanager
349 @config.bot_associate(self)
352 fatal e.backtrace.join("\n")
357 if @config['core.run_as_daemon']
361 @logfile = @config['log.file']
362 if @logfile.class!=String || @logfile.empty?
363 @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
366 # See http://blog.humlab.umu.se/samuel/archives/000107.html
367 # for the backgrounding code
373 rescue NotImplementedError
374 warning "Could not background, fork not supported"
376 warning "Could not background. #{e.inspect}"
379 # File.umask 0000 # Ensure sensible umask. Adjust as needed.
380 log "Redirecting standard input/output/error"
382 STDIN.reopen "/dev/null"
384 # On Windows, there's not such thing as /dev/null
387 def STDOUT.write(str=nil)
391 def STDERR.write(str=nil)
392 if str.to_s.match(/:\d+: warning:/)
401 # Set the new logfile and loglevel. This must be done after the daemonizing
402 $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
403 $logger.datetime_format= $dateformat
404 $logger.level = @config['log.level']
405 $logger.level = $cl_loglevel if $cl_loglevel
406 $logger.level = 0 if $debug
410 @registry = BotRegistry.new self
412 @timer = Timer::Timer.new(1.0) # only need per-second granularity
413 @save_mutex = Mutex.new
414 if @config['core.save_every'] > 0
415 @save_timer = @timer.add(@config['core.save_every']) { save }
419 @quit_mutex = Mutex.new
424 @lang = Language::Language.new(self, @config['core.language'])
427 @auth = Auth::authmanager
428 @auth.bot_associate(self)
429 # @auth.load("#{botclass}/botusers.yaml")
432 fatal e.backtrace.join("\n")
436 @auth.everyone.set_default_permission("*", true)
437 @auth.botowner.password= @config['auth.password']
439 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
440 @plugins = Plugins::pluginmanager
441 @plugins.bot_associate(self)
445 Utils.set_safe_save_dir("#{botclass}/safe_save")
446 @httputil = Utils::HttpUtil.new(self)
449 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
452 # Channels where we are quiet
453 # Array of channels names where the bot should be quiet
454 # '*' means all channels
458 @client[:welcome] = proc {|data|
459 irclog "joined server #{@client.server} as #{myself}", "server"
461 @plugins.delegate("connect")
463 @config['irc.join_channels'].each { |c|
464 debug "autojoining channel #{c}"
465 if(c =~ /^(\S+)\s+(\S+)$/i)
473 # TODO the next two @client should go into rfc2812.rb, probably
474 # Since capabs are two-steps processes, server.supports[:capab]
475 # should be a three-state: nil, [], [....]
476 asked_for = { :"identify-msg" => false }
477 @client[:isupport] = proc { |data|
478 if server.supports[:capab] and !asked_for[:"identify-msg"]
479 sendq "CAPAB IDENTIFY-MSG"
480 asked_for[:"identify-msg"] = true
483 @client[:datastr] = proc { |data|
484 if data[:text] == "IDENTIFY-MSG"
485 server.capabilities[:"identify-msg"] = true
487 debug "Not handling RPL_DATASTR #{data[:servermessage]}"
491 @client[:privmsg] = proc { |data|
492 m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
493 # debug "Message source is #{data[:source].inspect}"
494 # debug "Message target is #{data[:target].inspect}"
495 # debug "Bot is #{myself.inspect}"
498 @config['irc.ignore_users'].each { |mask|
499 if m.source.matches?(server.new_netmask(mask))
508 @plugins.delegate "listen", m
509 @plugins.privmsg(m) if m.address?
511 @plugins.delegate "unreplied", m
515 @client[:notice] = proc { |data|
516 message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
517 # pass it off to plugins that want to hear everything
518 @plugins.delegate "listen", message
520 @client[:motd] = proc { |data|
521 data[:motd].each_line { |line|
522 irclog "MOTD: #{line}", "server"
525 @client[:nicktaken] = proc { |data|
526 new = "#{data[:nick]}_"
528 # If we're setting our nick at connection because our choice was taken,
529 # we have to fix our nick manually, because there will be no NICK message
530 # yo inform us that our nick has been changed.
531 if data[:target] == '*'
532 debug "setting my connection nick to #{new}"
535 @plugins.delegate "nicktaken", data[:nick]
537 @client[:badnick] = proc {|data|
538 arning "bad nick (#{data[:nick]})"
540 @client[:ping] = proc {|data|
541 sendq "PONG #{data[:pingid]}"
543 @client[:pong] = proc {|data|
546 @client[:nick] = proc {|data|
547 # debug "Message source is #{data[:source].inspect}"
548 # debug "Bot is #{myself.inspect}"
549 source = data[:source]
552 m = NickMessage.new(self, server, source, old, new)
554 debug "my nick is now #{new}"
556 data[:is_on].each { |ch|
557 irclog "@ #{old} is now known as #{new}", ch
559 @plugins.delegate("listen", m)
560 @plugins.delegate("nick", m)
562 @client[:quit] = proc {|data|
563 source = data[:source]
564 message = data[:message]
565 m = QuitMessage.new(self, server, source, source, message)
566 data[:was_on].each { |ch|
567 irclog "@ Quit: #{source}: #{message}", ch
569 @plugins.delegate("listen", m)
570 @plugins.delegate("quit", m)
572 @client[:mode] = proc {|data|
573 irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
575 @client[:join] = proc {|data|
576 m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
579 @plugins.delegate("listen", m)
580 @plugins.delegate("join", m)
582 @client[:part] = proc {|data|
583 m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
586 @plugins.delegate("listen", m)
587 @plugins.delegate("part", m)
589 @client[:kick] = proc {|data|
590 m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
593 @plugins.delegate("listen", m)
594 @plugins.delegate("kick", m)
596 @client[:invite] = proc {|data|
597 if data[:target] == myself
598 join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
601 @client[:changetopic] = proc {|data|
602 m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
605 @plugins.delegate("listen", m)
606 @plugins.delegate("topic", m)
608 @client[:topic] = proc { |data|
609 irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
611 @client[:topicinfo] = proc { |data|
612 channel = data[:channel]
613 topic = channel.topic
614 irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
615 m = TopicMessage.new(self, server, data[:source], channel, topic)
617 @plugins.delegate("listen", m)
618 @plugins.delegate("topic", m)
620 @client[:names] = proc { |data|
621 @plugins.delegate "names", data[:channel], data[:users]
623 @client[:unknown] = proc { |data|
624 #debug "UNKNOWN: #{data[:serverstring]}"
625 irclog data[:serverstring], ".unknown"
628 set_default_send_options :newlines => @config['send.newlines'].to_sym,
629 :join_with => @config['send.join_with'].dup,
630 :max_lines => @config['send.max_lines'],
631 :overlong => @config['send.overlong'].to_sym,
632 :split_at => Regexp.new(@config['send.split_at']),
633 :purge_split => @config['send.purge_split'],
634 :truncate_text => @config['send.truncate_text'].dup
637 def setup_plugins_path
638 @plugins.clear_botmodule_dirs
639 @plugins.add_botmodule_dir(Config::coredir + "/utils")
640 @plugins.add_botmodule_dir(Config::coredir)
641 @plugins.add_botmodule_dir("#{botclass}/plugins")
643 @config['plugins.path'].each do |_|
644 path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
645 @plugins.add_botmodule_dir(path)
649 def set_default_send_options(opts={})
650 # Default send options for NOTICE and PRIVMSG
651 unless defined? @default_send_options
652 @default_send_options = {
653 :queue_channel => nil, # use default queue channel
654 :queue_ring => nil, # use default queue ring
655 :newlines => :split, # or :join
656 :join_with => ' ', # by default, use a single space
657 :max_lines => 0, # maximum number of lines to send with a single command
658 :overlong => :split, # or :truncate
659 # TODO an array of splitpoints would be preferrable for this option:
660 :split_at => /\s+/, # by default, split overlong lines at whitespace
661 :purge_split => true, # should the split string be removed?
662 :truncate_text => "#{Reverse}...#{Reverse}" # text to be appened when truncating
665 @default_send_options.update opts unless opts.empty?
668 # checks if we should be quiet on a channel
669 def quiet_on?(channel)
670 return @quiet.include?('*') || @quiet.include?(channel.downcase)
673 def set_quiet(channel)
675 ch = channel.downcase.dup
676 @quiet << ch unless @quiet.include?(ch)
683 def reset_quiet(channel)
685 @quiet.delete channel.downcase
691 # things to do when we receive a signal
693 debug "received #{sig}, queueing quit"
695 quit unless @quit_mutex.locked?
696 debug "interrupted #{$interrupted} times"
704 # connect the bot to IRC
707 trap("SIGINT") { got_sig("SIGINT") }
708 trap("SIGTERM") { got_sig("SIGTERM") }
709 trap("SIGHUP") { got_sig("SIGHUP") }
710 rescue ArgumentError => e
711 debug "failed to trap signals (#{e.inspect}): running on Windows?"
713 debug "failed to trap signals: #{e.inspect}"
716 quit if $interrupted > 0
719 raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
721 quit if $interrupted > 0
723 realname = @config['irc.name'].clone || 'Ruby bot'
724 realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
726 @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
727 @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :#{realname}"
728 quit if $interrupted > 0
729 myself.nick = @config['irc.nick']
730 myself.user = @config['irc.user']
733 # begin event handling loop
737 quit if $interrupted > 0
742 while @socket.connected?
743 quit if $interrupted > 0
745 # Wait for messages and process them as they arrive. If nothing is
746 # received, we call the ping_server() method that will PING the
747 # server if appropriate, or raise a TimeoutError if no PONG has been
748 # received in the user-chosen timeout since the last PING sent.
750 break unless reply = @socket.gets
752 @client.process reply
758 # I despair of this. Some of my users get "connection reset by peer"
759 # exceptions that ARENT SocketError's. How am I supposed to handle
764 rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
765 error "network exception: #{e.class}: #{e}"
766 debug e.backtrace.join("\n")
768 rescue BDB::Fatal => e
769 fatal "fatal bdb error: #{e.class}: #{e}"
770 fatal e.backtrace.join("\n")
772 # Why restart? DB problems are serious stuff ...
773 # restart("Oops, we seem to have registry problems ...")
776 rescue Exception => e
777 error "non-net exception: #{e.class}: #{e}"
778 error e.backtrace.join("\n")
781 fatal "unexpected exception: #{e.class}: #{e}"
782 fatal e.backtrace.join("\n")
789 log "\n\nDisconnected\n\n"
791 quit if $interrupted > 0
793 log "\n\nWaiting to reconnect\n\n"
794 sleep @config['server.reconnect_wait']
798 # type:: message type
799 # where:: message target
800 # message:: message text
801 # send message +message+ of type +type+ to target +where+
802 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
803 # relevant say() or notice() methods. This one should be used for IRCd
804 # extensions you want to use in modules.
805 def sendmsg(type, where, original_message, options={})
806 opts = @default_send_options.merge(options)
808 # For starters, set up appropriate queue channels and rings
809 mchan = opts[:queue_channel]
810 mring = opts[:queue_ring]
827 message = original_message.to_s.gsub(/[\r\n]+/, "\n")
830 lines = [message.gsub("\n", opts[:join_with])]
833 message.each_line { |line|
835 next unless(line.size > 0)
839 raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
842 # The IRC protocol requires that each raw message must be not longer
843 # than 512 characters. From this length with have to subtract the EOL
844 # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
845 # that will be prepended by the server to all of our messages.
847 # The maximum raw message length we can send is therefore 512 - 2 - 2
848 # minus the length of our hostmask.
850 max_len = 508 - myself.fullform.size
852 # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
853 # will have a + or - prepended
854 if server.capabilities[:"identify-msg"]
858 # When splitting the message, we'll be prefixing the following string:
859 # (e.g. "PRIVMSG #rbot :")
860 fixed = "#{type} #{where} :"
862 # And this is what's left
863 left = max_len - fixed.size
868 split_at = opts[:split_at]
870 truncate = opts[:truncate_text]
871 truncate = @default_send_options[:truncate_text] if truncate.size > left
872 truncate = "" if truncate.size > left
874 raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
877 # Counter to check the number of lines sent by this command
879 max_lines = opts[:max_lines]
884 if max_lines > 0 and cmd_lines == max_lines - 1
885 truncate = opts[:truncate_text]
886 truncate = @default_send_options[:truncate_text] if truncate.size > left
887 truncate = "" if truncate.size > left
890 if(left >= msg.size) and not maxed
891 sendq "#{fixed}#{msg}", chan, ring
892 log_sent(type, where, msg)
897 line.replace msg.slice(0, left-truncate.size)
898 # line.sub!(/\s+\S*$/, truncate)
900 raise "PROGRAMMER ERROR! #{line.inspect} of size #{line.size} > #{left}" if line.size > left
901 sendq "#{fixed}#{line}", chan, ring
902 log_sent(type, where, line)
905 line.replace msg.slice!(0, left)
906 lastspace = line.rindex(opts[:split_at])
908 msg.replace line.slice!(lastspace, line.size) + msg
909 msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
911 sendq "#{fixed}#{line}", chan, ring
912 log_sent(type, where, line)
914 end while(msg.size > 0)
918 # queue an arbitraty message for the server
919 def sendq(message="", chan=nil, ring=0)
921 @socket.queue(message, chan, ring)
924 # send a notice message to channel/nick +where+
925 def notice(where, message, options={})
926 return if where.kind_of?(Channel) and quiet_on?(where)
927 sendmsg "NOTICE", where, message, options
930 # say something (PRIVMSG) to channel/nick +where+
931 def say(where, message, options={})
932 return if where.kind_of?(Channel) and quiet_on?(where)
933 sendmsg "PRIVMSG", where, message, options
936 # perform a CTCP action with message +message+ to channel/nick +where+
937 def action(where, message, options={})
938 return if where.kind_of?(Channel) and quiet_on?(where)
939 mchan = options.fetch(:queue_channel, nil)
940 mring = options.fetch(:queue_ring, nil)
956 # FIXME doesn't check message length. Can we make this exploit sendmsg?
957 sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
960 irclog "* #{myself} #{message}", where
962 irclog "* #{myself}[#{where}] #{message}", where
966 # quick way to say "okay" (or equivalent) to +where+
968 say where, @lang.get("okay")
971 # log IRC-related message +message+ to a file determined by +where+.
972 # +where+ can be a channel name, or a nick for private message logging
973 def irclog(message, where="server")
974 message = message.chomp
975 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
976 where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
977 unless(@logs.has_key?(where))
978 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
979 @logs[where].sync = true
981 @logs[where].puts "[#{stamp}] #{message}"
982 #debug "[#{stamp}] <#{where}> #{message}"
985 # set topic of channel +where+ to +topic+
986 def topic(where, topic)
987 sendq "TOPIC #{where} :#{topic}", where, 2
990 def disconnect(message = nil)
991 message = @lang.get("quit") if (message.nil? || message.empty?)
992 if @socket.connected?
993 debug "Clearing socket"
995 debug "Sending quit message"
996 @socket.emergency_puts "QUIT :#{message}"
997 debug "Flushing socket"
999 debug "Shutting down socket"
1002 debug "Logging quits"
1003 server.channels.each { |ch|
1004 irclog "@ quit (#{message})", ch
1010 # disconnect from the server and cleanup all plugins and modules
1011 def shutdown(message = nil)
1012 @quit_mutex.synchronize do
1013 debug "Shutting down ..."
1014 ## No we don't restore them ... let everything run through
1016 # trap("SIGINT", "DEFAULT")
1017 # trap("SIGTERM", "DEFAULT")
1018 # trap("SIGHUP", "DEFAULT")
1020 # debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1026 @save_mutex.synchronize do
1029 # debug "Closing registries"
1031 debug "Cleaning up the db environment"
1033 log "rbot quit (#{message})"
1037 # message:: optional IRC quit message
1038 # quit IRC, shutdown the bot
1039 def quit(message=nil)
1047 # totally shutdown and respawn the bot
1048 def restart(message = false)
1049 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1051 sleep @config['server.reconnect_wait']
1053 # Note, this fails on Windows
1057 # call the save method for all of the botmodules
1059 @save_mutex.synchronize do
1065 # call the rescan method for all of the botmodules
1067 @save_mutex.synchronize do
1073 # channel:: channel to join
1074 # key:: optional channel key if channel is +s
1076 def join(channel, key=nil)
1078 sendq "JOIN #{channel} :#{key}", channel, 2
1080 sendq "JOIN #{channel}", channel, 2
1085 def part(channel, message="")
1086 sendq "PART #{channel} :#{message}", channel, 2
1089 # attempt to change bot's nick to +name+
1091 sendq "NICK #{name}"
1095 def mode(channel, mode, target)
1096 sendq "MODE #{channel} #{mode} #{target}", channel, 2
1100 def kick(channel, user, msg)
1101 sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1104 # m:: message asking for help
1105 # topic:: optional topic help is requested for
1106 # respond to online help requests
1108 topic = nil if topic == ""
1111 helpstr = "help topics: "
1112 helpstr += @plugins.helptopics
1113 helpstr += " (help <topic> for more info)"
1115 unless(helpstr = @plugins.help(topic))
1116 helpstr = "no help for topic #{topic}"
1122 # returns a string describing the current status of the bot (uptime etc)
1124 secs_up = Time.new - @startup_time
1125 uptime = Utils.secs_to_string secs_up
1126 # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1127 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1130 # We want to respond to a hung server in a timely manner. If nothing was received
1131 # in the user-selected timeout and we haven't PINGed the server yet, we PING
1132 # the server. If the PONG is not received within the user-defined timeout, we
1133 # assume we're in ping timeout and act accordingly.
1135 act_timeout = @config['server.ping_timeout']
1136 return if act_timeout <= 0
1138 if @last_rec && now > @last_rec + act_timeout
1140 # No previous PING pending, send a new one
1142 @last_ping = Time.now
1144 diff = now - @last_ping
1145 if diff > act_timeout
1146 debug "no PONG from server in #{diff} seconds, reconnecting"
1147 # the actual reconnect is handled in the main loop:
1148 raise TimeoutError, "no PONG from server in #{diff} seconds"
1154 def stop_server_pings
1155 # cancel previous PINGs and reset time of last RECV
1162 def irclogprivmsg(m)
1165 irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1167 irclog "* #{m.sourcenick} #{m.message}", m.target
1171 irclog "<#{m.sourcenick}> #{m.message}", m.target
1173 irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1178 # log a message. Internal use only.
1179 def log_sent(type, where, message)
1184 irclog "-=#{myself}=- #{message}", where
1186 irclog "[-=#{where}=-] #{message}", where
1191 irclog "<#{myself}> #{message}", where
1193 irclog "[msg(#{where})] #{message}", where
1200 debug "joined channel #{m.channel}"
1201 irclog "@ Joined channel #{m.channel}", m.channel
1203 irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1209 debug "left channel #{m.channel}"
1210 irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1212 irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1218 debug "kicked from channel #{m.channel}"
1219 irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1221 irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1226 if m.source == myself
1227 irclog "@ I set topic \"#{m.topic}\"", m.channel
1229 irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel