5 $debug = false unless $debug
6 # print +message+ if debugging is enabled
8 print "DEBUG: #{message}\n" if($debug && message)
13 require 'rbot/rbotconfig'
17 require 'rbot/rfc2812'
18 require 'rbot/keywords'
19 require 'rbot/ircsocket'
22 require 'rbot/plugins'
23 require 'rbot/channel'
24 require 'rbot/message'
25 require 'rbot/language'
27 require 'rbot/registry'
28 require 'rbot/httputil'
32 # Main bot class, which manages the various components, receives messages,
33 # handles them or passes them to plugins, and contains core functionality.
35 # the bot's current nickname
38 # the bot's IrcAuth data
41 # the bot's BotConfig data
44 # the botclass for this bot (determines configdir among other things)
47 # used to perform actions periodically (saves configuration once per minute
54 # bot's configured addressing prefixes
55 attr_reader :addressing_prefixes
57 # channel info for channels the bot is in
63 # bot's object registry, plugins get an interface to this for persistant
64 # storage (hash interface tied to a bdb file, plugins use Accessors to store
65 # and restore objects in their own namespaces.)
68 # bot's httputil help object, for fetching resources via http. Sets up
69 # proxies etc as defined by the bot configuration/environment
72 # create a new IrcBot with botclass +botclass+
73 def initialize(botclass, params = {})
74 # BotConfig for the core bot
75 BotConfig.register BotConfigStringValue.new('server.name',
76 :default => "localhost", :requires_restart => true,
77 :desc => "What server should the bot connect to?",
79 BotConfig.register BotConfigIntegerValue.new('server.port',
80 :default => 6667, :type => :integer, :requires_restart => true,
81 :desc => "What port should the bot connect to?",
82 :validate => Proc.new {|v| v > 0}, :wizard => true)
83 BotConfig.register BotConfigStringValue.new('server.password',
84 :default => false, :requires_restart => true,
85 :desc => "Password for connecting to this server (if required)",
87 BotConfig.register BotConfigStringValue.new('server.bindhost',
88 :default => false, :requires_restart => true,
89 :desc => "Specific local host or IP for the bot to bind to (if required)",
91 BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
92 :default => 5, :validate => Proc.new{|v| v >= 0},
93 :desc => "Seconds to wait before attempting to reconnect, on disconnect")
94 BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
95 :desc => "IRC nickname the bot should attempt to use", :wizard => true,
96 :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
97 BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
98 :requires_restart => true,
99 :desc => "local user the bot should appear to be", :wizard => true)
100 BotConfig.register BotConfigArrayValue.new('irc.join_channels',
101 :default => [], :wizard => true,
102 :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'")
103 BotConfig.register BotConfigIntegerValue.new('core.save_every',
104 :default => 60, :validate => Proc.new{|v| v >= 0},
105 # TODO change timer via on_change proc
106 :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example")
107 BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
108 :default => 2.0, :validate => Proc.new{|v| v >= 0},
109 :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
110 :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
111 BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
112 :default => 4, :validate => Proc.new{|v| v >= 0},
113 :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines, with non-burst limits of 512 bytes/2 seconds",
114 :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
116 @argv = params[:argv]
118 unless FileTest.directory? Config::datadir
119 puts "data directory '#{Config::datadir}' not found, did you install.rb?"
123 botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass
124 @botclass = botclass.gsub(/\/$/, "")
126 unless FileTest.directory? botclass
127 puts "no #{botclass} directory found, creating from templates.."
128 if FileTest.exist? botclass
129 puts "Error: file #{botclass} exists but isn't a directory"
132 FileUtils.cp_r Config::datadir+'/templates', botclass
135 Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
137 @startup_time = Time.new
138 @config = BotConfig.new(self)
139 # TODO background self after botconfig has a chance to run wizard
140 @timer = Timer::Timer.new(1.0) # only need per-second granularity
141 @registry = BotRegistry.new self
142 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
146 @httputil = Utils::HttpUtil.new(self)
147 @lang = Language::Language.new(@config['core.language'])
148 @keywords = Keywords.new(self)
149 @auth = IrcAuth.new(self)
151 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
152 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
154 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
155 @nick = @config['irc.nick']
157 @client = IrcClient.new
158 @client[:privmsg] = proc { |data|
159 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
162 @client[:notice] = proc { |data|
163 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
164 # pass it off to plugins that want to hear everything
165 @plugins.delegate "listen", message
167 @client[:motd] = proc { |data|
168 data[:motd].each_line { |line|
169 log "MOTD: #{line}", "server"
172 @client[:nicktaken] = proc { |data|
173 nickchg "#{data[:nick]}_"
175 @client[:badnick] = proc {|data|
176 puts "WARNING, bad nick (#{data[:nick]})"
178 @client[:ping] = proc {|data|
179 # (jump the queue for pongs)
180 @socket.puts "PONG #{data[:pingid]}"
182 @client[:nick] = proc {|data|
183 sourcenick = data[:sourcenick]
185 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
186 if(sourcenick == @nick)
187 debug "my nick is now #{nick}"
190 @channels.each {|k,v|
191 if(v.users.has_key?(sourcenick))
192 log "@ #{sourcenick} is now known as #{nick}", k
193 v.users[nick] = v.users[sourcenick]
194 v.users.delete(sourcenick)
197 @plugins.delegate("listen", m)
198 @plugins.delegate("nick", m)
200 @client[:quit] = proc {|data|
201 source = data[:source]
202 sourcenick = data[:sourcenick]
203 sourceurl = data[:sourceaddress]
204 message = data[:message]
205 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
206 if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
208 @channels.each {|k,v|
209 if(v.users.has_key?(sourcenick))
210 log "@ Quit: #{sourcenick}: #{message}", k
211 v.users.delete(sourcenick)
215 @plugins.delegate("listen", m)
216 @plugins.delegate("quit", m)
218 @client[:mode] = proc {|data|
219 source = data[:source]
220 sourcenick = data[:sourcenick]
221 sourceurl = data[:sourceaddress]
222 channel = data[:channel]
223 targets = data[:targets]
224 modestring = data[:modestring]
225 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
227 @client[:welcome] = proc {|data|
228 log "joined server #{data[:source]} as #{data[:nick]}", "server"
229 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
230 if data[:nick] && data[:nick].length > 0
234 @plugins.delegate("connect")
236 @config['irc.join_channels'].each {|c|
237 debug "autojoining channel #{c}"
238 if(c =~ /^(\S+)\s+(\S+)$/i)
245 @client[:join] = proc {|data|
246 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
249 @client[:part] = proc {|data|
250 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
253 @client[:kick] = proc {|data|
254 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
257 @client[:invite] = proc {|data|
258 if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
259 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
262 @client[:changetopic] = proc {|data|
263 channel = data[:channel]
264 sourcenick = data[:sourcenick]
266 timestamp = data[:unixtime] || Time.now.to_i
267 if(sourcenick == @nick)
268 log "@ I set topic \"#{topic}\"", channel
270 log "@ #{sourcenick} set topic \"#{topic}\"", channel
272 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
275 @plugins.delegate("listen", m)
276 @plugins.delegate("topic", m)
278 @client[:topic] = @client[:topicinfo] = proc {|data|
279 channel = data[:channel]
280 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
283 @client[:names] = proc {|data|
284 channel = data[:channel]
286 unless(@channels[channel])
287 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
290 @channels[channel].users.clear
292 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
295 @client[:unknown] = proc {|data|
296 #debug "UNKNOWN: #{data[:serverstring]}"
297 log data[:serverstring], ":unknown"
301 # connect the bot to IRC
303 trap("SIGTERM") { quit }
304 trap("SIGHUP") { quit }
305 trap("SIGINT") { quit }
309 raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
311 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
312 @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
315 # begin event handling loop
324 break unless reply = @socket.gets
325 @client.process reply
328 rescue TimeoutError, SocketError => e
329 puts "network exception: connection closed: #{e}"
330 puts e.backtrace.join("\n")
331 @socket.close # now we reconnect
332 rescue => e # TODO be selective, only grab Network errors
333 puts "unexpected exception: connection closed: #{e}"
334 puts e.backtrace.join("\n")
342 puts "waiting to reconnect"
343 sleep @config['server.reconnect_wait']
347 # type:: message type
348 # where:: message target
349 # message:: message text
350 # send message +message+ of type +type+ to target +where+
351 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
352 # relevant say() or notice() methods. This one should be used for IRCd
353 # extensions you want to use in modules.
354 def sendmsg(type, where, message)
355 # limit it 440 chars + CRLF.. so we have to split long lines
356 left = 440 - type.length - where.length - 3
358 if(left >= message.length)
359 sendq("#{type} #{where} :#{message}")
360 log_sent(type, where, message)
363 line = message.slice!(0, left)
364 lastspace = line.rindex(/\s+/)
366 message = line.slice!(lastspace, line.length) + message
367 message.gsub!(/^\s+/, "")
369 sendq("#{type} #{where} :#{line}")
370 log_sent(type, where, line)
371 end while(message.length > 0)
374 # queue an arbitraty message for the server
375 def sendq(message="")
377 @socket.queue(message)
380 # send a notice message to channel/nick +where+
381 def notice(where, message)
382 message.each_line { |line|
384 next unless(line.length > 0)
385 sendmsg("NOTICE", where, line)
389 # say something (PRIVMSG) to channel/nick +where+
390 def say(where, message)
391 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
393 next unless(line.length > 0)
394 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
395 sendmsg("PRIVMSG", where, line)
400 # perform a CTCP action with message +message+ to channel/nick +where+
401 def action(where, message)
402 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
404 log "* #{@nick} #{message}", where
405 elsif (where =~ /^(\S*)!.*$/)
406 log "* #{@nick}[#{where}] #{message}", $1
408 log "* #{@nick}[#{where}] #{message}", where
412 # quick way to say "okay" (or equivalent) to +where+
414 say where, @lang.get("okay")
417 # log message +message+ to a file determined by +where+. +where+ can be a
418 # channel name, or a nick for private message logging
419 def log(message, where="server")
421 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
422 unless(@logs.has_key?(where))
423 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
424 @logs[where].sync = true
426 @logs[where].puts "[#{stamp}] #{message}"
427 #debug "[#{stamp}] <#{where}> #{message}"
430 # set topic of channel +where+ to +topic+
431 def topic(where, topic)
432 sendq "TOPIC #{where} :#{topic}"
435 # disconnect from the server and cleanup all plugins and modules
436 def shutdown(message = nil)
437 trap("SIGTERM", "DEFAULT")
438 trap("SIGHUP", "DEFAULT")
439 trap("SIGINT", "DEFAULT")
440 message = @lang.get("quit") if (message.nil? || message.empty?)
444 @channels.each_value {|v|
445 log "@ quit (#{message})", v.name
447 @socket.puts "QUIT :#{message}"
451 puts "rbot quit (#{message})"
454 # message:: optional IRC quit message
455 # quit IRC, shutdown the bot
456 def quit(message=nil)
461 # totally shutdown and respawn the bot
462 def restart(message = false)
463 msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
465 sleep @config['server.reconnect_wait']
470 # call the save method for bot's config, keywords, auth and all plugins
479 # call the rescan method for the bot's lang, keywords and all plugins
486 # channel:: channel to join
487 # key:: optional channel key if channel is +s
489 def join(channel, key=nil)
491 sendq "JOIN #{channel} :#{key}"
493 sendq "JOIN #{channel}"
498 def part(channel, message="")
499 sendq "PART #{channel} :#{message}"
502 # attempt to change bot's nick to +name+
508 def mode(channel, mode, target)
509 sendq "MODE #{channel} #{mode} #{target}"
512 # m:: message asking for help
513 # topic:: optional topic help is requested for
514 # respond to online help requests
516 topic = nil if topic == ""
519 helpstr = "help topics: core, auth, keywords"
520 helpstr += @plugins.helptopics
521 helpstr += " (help <topic> for more info)"
524 when /^core\s+(.+)$/i
525 helpstr = corehelp $1
528 when /^auth\s+(.+)$/i
529 helpstr = @auth.help $1
531 helpstr = @keywords.help
532 when /^keywords\s+(.+)$/i
533 helpstr = @keywords.help $1
535 unless(helpstr = @plugins.help(topic))
536 helpstr = "no help for topic #{topic}"
542 # returns a string describing the current status of the bot (uptime etc)
544 secs_up = Time.new - @startup_time
545 uptime = Utils.secs_to_string secs_up
546 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
552 # handle help requests for "core" topics
553 def corehelp(topic="")
556 return "quit [<message>] => quit IRC with message <message>"
558 return "restart => completely stop and restart the bot (including reconnect)"
560 return "join <channel> [<key>] => join channel <channel> with secret key <key> if specified. #{@nick} also responds to invites if you have the required access level"
562 return "part <channel> => part channel <channel>"
564 return "hide => part all channels"
566 return "save => save current dynamic data and configuration"
568 return "rescan => reload modules and static facts"
570 return "nick <nick> => attempt to change nick to <nick>"
572 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
574 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
576 return "topic <channel> <message> => set topic of <channel> to <message>"
578 return "quiet [in here|<channel>] => with no arguments, stop speaking in all channels, if \"in here\", stop speaking in this channel, or stop speaking in <channel>"
580 return "talk [in here|<channel>] => with no arguments, resume speaking in all channels, if \"in here\", resume speaking in this channel, or resume speaking in <channel>"
582 return "version => describes software version"
584 return "botsnack => reward #{@nick} for being good"
586 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
588 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
592 # handle incoming IRC PRIVMSG +m+
597 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
599 log "* #{m.sourcenick} #{m.message}", m.target
603 log "<#{m.sourcenick}> #{m.message}", m.target
605 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
609 # pass it off to plugins that want to hear everything
610 @plugins.delegate "listen", m
612 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
613 notice m.sourcenick, "\001PING #$1\001"
614 log "@ #{m.sourcenick} pinged me"
620 when (/^join\s+(\S+)\s+(\S+)$/i)
621 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
622 when (/^join\s+(\S+)$/i)
623 join $1 if(@auth.allow?("join", m.source, m.replyto))
625 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
626 when (/^part\s+(\S+)$/i)
627 part $1 if(@auth.allow?("join", m.source, m.replyto))
628 when (/^quit(?:\s+(.*))?$/i)
629 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
630 when (/^restart(?:\s+(.*))?$/i)
631 restart $1 if(@auth.allow?("quit", m.source, m.replyto))
633 join 0 if(@auth.allow?("join", m.source, m.replyto))
635 if(@auth.allow?("config", m.source, m.replyto))
639 when (/^nick\s+(\S+)$/i)
640 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
641 when (/^say\s+(\S+)\s+(.*)$/i)
642 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
643 when (/^action\s+(\S+)\s+(.*)$/i)
644 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
645 when (/^topic\s+(\S+)\s+(.*)$/i)
646 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
647 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
648 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
650 say m.replyto, "pong"
652 if(@auth.allow?("config", m.source, m.replyto))
657 if(auth.allow?("talk", m.source, m.replyto))
659 @channels.each_value {|c| c.quiet = true }
661 when (/^quiet in (\S+)$/i)
663 if(auth.allow?("talk", m.source, m.replyto))
665 where.gsub!(/^here$/, m.target) if m.public?
666 @channels[where].quiet = true if(@channels.has_key?(where))
669 if(auth.allow?("talk", m.source, m.replyto))
670 @channels.each_value {|c| c.quiet = false }
673 when (/^talk in (\S+)$/i)
675 if(auth.allow?("talk", m.source, m.replyto))
676 where.gsub!(/^here$/, m.target) if m.public?
677 @channels[where].quiet = false if(@channels.has_key?(where))
680 when (/^status\??$/i)
681 m.reply status if auth.allow?("status", m.source, m.replyto)
682 when (/^registry stats$/i)
683 if auth.allow?("config", m.source, m.replyto)
684 m.reply @registry.stat.inspect
686 when (/^(help\s+)?config(\s+|$)/)
688 when (/^(version)|(introduce yourself)$/i)
689 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
690 when (/^help(?:\s+(.*))?$/i)
691 say m.replyto, help($1)
692 #TODO move these to a "chatback" plugin
693 when (/^(botsnack|ciggie)$/i)
694 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
695 say m.replyto, @lang.get("thanks") if(m.private?)
696 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
697 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
698 say m.replyto, @lang.get("hello") if(m.private?)
703 # stuff to handle when not addressed
705 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
706 say m.replyto, @lang.get("hello_X") % m.sourcenick
707 when (/^#{Regexp.escape(@nick)}!*$/)
708 say m.replyto, @lang.get("hello_X") % m.sourcenick
715 # log a message. Internal use only.
716 def log_sent(type, where, message)
720 log "-=#{@nick}=- #{message}", where
721 elsif (where =~ /(\S*)!.*/)
722 log "[-=#{where}=-] #{message}", $1
724 log "[-=#{where}=-] #{message}"
728 log "<#{@nick}> #{message}", where
729 elsif (where =~ /^(\S*)!.*$/)
730 log "[msg(#{where})] #{message}", $1
732 log "[msg(#{where})] #{message}", where
738 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
740 debug "joined channel #{m.channel}"
741 log "@ Joined channel #{m.channel}", m.channel
743 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
744 @channels[m.channel].users[m.sourcenick] = Hash.new
745 @channels[m.channel].users[m.sourcenick]["mode"] = ""
748 @plugins.delegate("listen", m)
749 @plugins.delegate("join", m)
754 debug "left channel #{m.channel}"
755 log "@ Left channel #{m.channel} (#{m.message})", m.channel
756 @channels.delete(m.channel)
758 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
759 @channels[m.channel].users.delete(m.sourcenick)
762 # delegate to plugins
763 @plugins.delegate("listen", m)
764 @plugins.delegate("part", m)
767 # respond to being kicked from a channel
770 debug "kicked from channel #{m.channel}"
771 @channels.delete(m.channel)
772 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
774 @channels[m.channel].users.delete(m.sourcenick)
775 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
778 @plugins.delegate("listen", m)
779 @plugins.delegate("kick", m)
783 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
784 @channels[m.channel].topic = m.topic if !m.topic.nil?
785 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
786 @channels[m.channel].topic.by = m.source if !m.source.nil?
788 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
791 # delegate a privmsg to auth, keyword or plugin handlers
792 def delegate_privmsg(message)
793 [@auth, @plugins, @keywords].each {|m|
794 break if m.privmsg(message)