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 = "/home/#{Etc.getlogin}/.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 @timer = Timer::Timer.new(1.0) # only need per-second granularity
140 @registry = BotRegistry.new self
141 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
145 @httputil = Utils::HttpUtil.new(self)
146 @lang = Language::Language.new(@config['core.language'])
147 @keywords = Keywords.new(self)
148 @auth = IrcAuth.new(self)
150 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
151 @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
153 @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
154 @nick = @config['irc.nick']
155 if @config['core.address_prefix']
156 @addressing_prefixes = @config['core.address_prefix'].split(" ")
158 @addressing_prefixes = Array.new
161 @client = IrcClient.new
162 @client[:privmsg] = proc { |data|
163 message = PrivMessage.new(self, data[:source], data[:target], data[:message])
166 @client[:notice] = proc { |data|
167 message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
168 # pass it off to plugins that want to hear everything
169 @plugins.delegate "listen", message
171 @client[:motd] = proc { |data|
172 data[:motd].each_line { |line|
173 log "MOTD: #{line}", "server"
176 @client[:nicktaken] = proc { |data|
177 nickchg "#{data[:nick]}_"
179 @client[:badnick] = proc {|data|
180 puts "WARNING, bad nick (#{data[:nick]})"
182 @client[:ping] = proc {|data|
183 # (jump the queue for pongs)
184 @socket.puts "PONG #{data[:pingid]}"
186 @client[:nick] = proc {|data|
187 sourcenick = data[:sourcenick]
189 m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
190 if(sourcenick == @nick)
191 debug "my nick is now #{nick}"
194 @channels.each {|k,v|
195 if(v.users.has_key?(sourcenick))
196 log "@ #{sourcenick} is now known as #{nick}", k
197 v.users[nick] = v.users[sourcenick]
198 v.users.delete(sourcenick)
201 @plugins.delegate("listen", m)
202 @plugins.delegate("nick", m)
204 @client[:quit] = proc {|data|
205 source = data[:source]
206 sourcenick = data[:sourcenick]
207 sourceurl = data[:sourceaddress]
208 message = data[:message]
209 m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
210 if(data[:sourcenick] =~ /#{@nick}/i)
212 @channels.each {|k,v|
213 if(v.users.has_key?(sourcenick))
214 log "@ Quit: #{sourcenick}: #{message}", k
215 v.users.delete(sourcenick)
219 @plugins.delegate("listen", m)
220 @plugins.delegate("quit", m)
222 @client[:mode] = proc {|data|
223 source = data[:source]
224 sourcenick = data[:sourcenick]
225 sourceurl = data[:sourceaddress]
226 channel = data[:channel]
227 targets = data[:targets]
228 modestring = data[:modestring]
229 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
231 @client[:welcome] = proc {|data|
232 log "joined server #{data[:source]} as #{data[:nick]}", "server"
233 debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
234 if data[:nick] && data[:nick].length > 0
238 @plugins.delegate("connect")
240 @config['irc.join_channels'].each {|c|
241 debug "autojoining channel #{c}"
242 if(c =~ /^(\S+)\s+(\S+)$/i)
249 @client[:join] = proc {|data|
250 m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
253 @client[:part] = proc {|data|
254 m = PartMessage.new(self, data[:source], data[:channel], data[:message])
257 @client[:kick] = proc {|data|
258 m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
261 @client[:invite] = proc {|data|
262 if(data[:target] =~ /^#{@nick}$/i)
263 join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
266 @client[:changetopic] = proc {|data|
267 channel = data[:channel]
268 sourcenick = data[:sourcenick]
270 timestamp = data[:unixtime] || Time.now.to_i
271 if(sourcenick == @nick)
272 log "@ I set topic \"#{topic}\"", channel
274 log "@ #{sourcenick} set topic \"#{topic}\"", channel
276 m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
279 @plugins.delegate("listen", m)
280 @plugins.delegate("topic", m)
282 @client[:topic] = @client[:topicinfo] = proc {|data|
283 channel = data[:channel]
284 m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
287 @client[:names] = proc {|data|
288 channel = data[:channel]
290 unless(@channels[channel])
291 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
294 @channels[channel].users.clear
296 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
299 @client[:unknown] = proc {|data|
300 #debug "UNKNOWN: #{data[:serverstring]}"
301 log data[:serverstring], ":unknown"
305 # connect the bot to IRC
307 trap("SIGTERM") { quit }
308 trap("SIGHUP") { quit }
309 trap("SIGINT") { quit }
313 raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
315 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
316 @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
319 # begin event handling loop
328 break unless reply = @socket.gets
329 @client.process reply
332 rescue TimeoutError, SocketError => e
333 puts "network exception: connection closed: #{e}"
334 puts e.backtrace.join("\n")
335 @socket.close # now we reconnect
336 rescue => e # TODO be selective, only grab Network errors
337 puts "unexpected exception: connection closed: #{e}"
338 puts e.backtrace.join("\n")
346 puts "waiting to reconnect"
347 sleep @config['server.reconnect_wait']
351 # type:: message type
352 # where:: message target
353 # message:: message text
354 # send message +message+ of type +type+ to target +where+
355 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
356 # relevant say() or notice() methods. This one should be used for IRCd
357 # extensions you want to use in modules.
358 def sendmsg(type, where, message)
359 # limit it 440 chars + CRLF.. so we have to split long lines
360 left = 440 - type.length - where.length - 3
362 if(left >= message.length)
363 sendq("#{type} #{where} :#{message}")
364 log_sent(type, where, message)
367 line = message.slice!(0, left)
368 lastspace = line.rindex(/\s+/)
370 message = line.slice!(lastspace, line.length) + message
371 message.gsub!(/^\s+/, "")
373 sendq("#{type} #{where} :#{line}")
374 log_sent(type, where, line)
375 end while(message.length > 0)
378 # queue an arbitraty message for the server
379 def sendq(message="")
381 @socket.queue(message)
384 # send a notice message to channel/nick +where+
385 def notice(where, message)
386 message.each_line { |line|
388 next unless(line.length > 0)
389 sendmsg("NOTICE", where, line)
393 # say something (PRIVMSG) to channel/nick +where+
394 def say(where, message)
395 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
397 next unless(line.length > 0)
398 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
399 sendmsg("PRIVMSG", where, line)
404 # perform a CTCP action with message +message+ to channel/nick +where+
405 def action(where, message)
406 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
408 log "* #{@nick} #{message}", where
409 elsif (where =~ /^(\S*)!.*$/)
410 log "* #{@nick}[#{where}] #{message}", $1
412 log "* #{@nick}[#{where}] #{message}", where
416 # quick way to say "okay" (or equivalent) to +where+
418 say where, @lang.get("okay")
421 # log message +message+ to a file determined by +where+. +where+ can be a
422 # channel name, or a nick for private message logging
423 def log(message, where="server")
425 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
426 unless(@logs.has_key?(where))
427 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
428 @logs[where].sync = true
430 @logs[where].puts "[#{stamp}] #{message}"
431 #debug "[#{stamp}] <#{where}> #{message}"
434 # set topic of channel +where+ to +topic+
435 def topic(where, topic)
436 sendq "TOPIC #{where} :#{topic}"
439 # disconnect from the server and cleanup all plugins and modules
440 def shutdown(message = nil)
441 trap("SIGTERM", "DEFAULT")
442 trap("SIGHUP", "DEFAULT")
443 trap("SIGINT", "DEFAULT")
444 message = @lang.get("quit") if (message.nil? || message.empty?)
448 @channels.each_value {|v|
449 log "@ quit (#{message})", v.name
451 @socket.puts "QUIT :#{message}"
455 puts "rbot quit (#{message})"
458 # message:: optional IRC quit message
459 # quit IRC, shutdown the bot
460 def quit(message=nil)
465 # totally shutdown and respawn the bot
467 shutdown("restarting, back in #{@config['server.reconnect_wait']}...")
468 sleep @config['server.reconnect_wait']
473 # call the save method for bot's config, keywords, auth and all plugins
482 # call the rescan method for the bot's lang, keywords and all plugins
489 # channel:: channel to join
490 # key:: optional channel key if channel is +s
492 def join(channel, key=nil)
494 sendq "JOIN #{channel} :#{key}"
496 sendq "JOIN #{channel}"
501 def part(channel, message="")
502 sendq "PART #{channel} :#{message}"
505 # attempt to change bot's nick to +name+
507 # if rbot is already taken, this happens:
508 # <giblet> rbot_, nick rbot
509 # --- rbot_ is now known as rbot__
510 # he should of course just keep his existing nick and report the error :P
516 def mode(channel, mode, target)
517 sendq "MODE #{channel} #{mode} #{target}"
520 # m:: message asking for help
521 # topic:: optional topic help is requested for
522 # respond to online help requests
524 topic = nil if topic == ""
527 helpstr = "help topics: core, auth, keywords"
528 helpstr += @plugins.helptopics
529 helpstr += " (help <topic> for more info)"
532 when /^core\s+(.+)$/i
533 helpstr = corehelp $1
536 when /^auth\s+(.+)$/i
537 helpstr = @auth.help $1
539 helpstr = @keywords.help
540 when /^keywords\s+(.+)$/i
541 helpstr = @keywords.help $1
543 unless(helpstr = @plugins.help(topic))
544 helpstr = "no help for topic #{topic}"
550 # returns a string describing the current status of the bot (uptime etc)
552 secs_up = Time.new - @startup_time
553 uptime = Utils.secs_to_string secs_up
554 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
560 # handle help requests for "core" topics
561 def corehelp(topic="")
564 return "quit [<message>] => quit IRC with message <message>"
566 return "restart => completely stop and restart the bot (including reconnect)"
568 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"
570 return "part <channel> => part channel <channel>"
572 return "hide => part all channels"
574 return "save => save current dynamic data and configuration"
576 return "rescan => reload modules and static facts"
578 return "nick <nick> => attempt to change nick to <nick>"
580 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
582 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
584 return "topic <channel> <message> => set topic of <channel> to <message>"
586 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>"
588 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>"
590 return "version => describes software version"
592 return "botsnack => reward #{@nick} for being good"
594 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
596 return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
600 # handle incoming IRC PRIVMSG +m+
605 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
607 log "* #{m.sourcenick} #{m.message}", m.target
611 log "<#{m.sourcenick}> #{m.message}", m.target
613 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
617 # pass it off to plugins that want to hear everything
618 @plugins.delegate "listen", m
620 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
621 notice m.sourcenick, "\001PING #$1\001"
622 log "@ #{m.sourcenick} pinged me"
628 when (/^join\s+(\S+)\s+(\S+)$/i)
629 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
630 when (/^join\s+(\S+)$/i)
631 join $1 if(@auth.allow?("join", m.source, m.replyto))
633 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
634 when (/^part\s+(\S+)$/i)
635 part $1 if(@auth.allow?("join", m.source, m.replyto))
636 when (/^quit(?:\s+(.*))?$/i)
637 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
639 restart if(@auth.allow?("quit", m.source, m.replyto))
641 join 0 if(@auth.allow?("join", m.source, m.replyto))
643 if(@auth.allow?("config", m.source, m.replyto))
647 when (/^nick\s+(\S+)$/i)
648 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
649 when (/^say\s+(\S+)\s+(.*)$/i)
650 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
651 when (/^action\s+(\S+)\s+(.*)$/i)
652 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
653 when (/^topic\s+(\S+)\s+(.*)$/i)
654 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
655 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
656 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
658 say m.replyto, "pong"
660 if(@auth.allow?("config", m.source, m.replyto))
665 if(auth.allow?("talk", m.source, m.replyto))
667 @channels.each_value {|c| c.quiet = true }
669 when (/^quiet in (\S+)$/i)
671 if(auth.allow?("talk", m.source, m.replyto))
673 where.gsub!(/^here$/, m.target) if m.public?
674 @channels[where].quiet = true if(@channels.has_key?(where))
677 if(auth.allow?("talk", m.source, m.replyto))
678 @channels.each_value {|c| c.quiet = false }
681 when (/^talk in (\S+)$/i)
683 if(auth.allow?("talk", m.source, m.replyto))
684 where.gsub!(/^here$/, m.target) if m.public?
685 @channels[where].quiet = false if(@channels.has_key?(where))
688 when (/^status\??$/i)
689 m.reply status if auth.allow?("status", m.source, m.replyto)
690 when (/^registry stats$/i)
691 if auth.allow?("config", m.source, m.replyto)
692 m.reply @registry.stat.inspect
694 when (/^(help\s+)?config(\s+|$)/)
696 when (/^(version)|(introduce yourself)$/i)
697 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
698 when (/^help(?:\s+(.*))?$/i)
699 say m.replyto, help($1)
700 #TODO move these to a "chatback" plugin
701 when (/^(botsnack|ciggie)$/i)
702 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
703 say m.replyto, @lang.get("thanks") if(m.private?)
704 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
705 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
706 say m.replyto, @lang.get("hello") if(m.private?)
711 # stuff to handle when not addressed
713 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))[\s,-.]+#{@nick}$/i)
714 say m.replyto, @lang.get("hello_X") % m.sourcenick
715 when (/^#{@nick}!*$/)
716 say m.replyto, @lang.get("hello_X") % m.sourcenick
723 # log a message. Internal use only.
724 def log_sent(type, where, message)
728 log "-=#{@nick}=- #{message}", where
729 elsif (where =~ /(\S*)!.*/)
730 log "[-=#{where}=-] #{message}", $1
732 log "[-=#{where}=-] #{message}"
736 log "<#{@nick}> #{message}", where
737 elsif (where =~ /^(\S*)!.*$/)
738 log "[msg(#{where})] #{message}", $1
740 log "[msg(#{where})] #{message}", where
746 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
748 debug "joined channel #{m.channel}"
749 log "@ Joined channel #{m.channel}", m.channel
751 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
752 @channels[m.channel].users[m.sourcenick] = Hash.new
753 @channels[m.channel].users[m.sourcenick]["mode"] = ""
756 @plugins.delegate("listen", m)
757 @plugins.delegate("join", m)
762 debug "left channel #{m.channel}"
763 log "@ Left channel #{m.channel} (#{m.message})", m.channel
764 @channels.delete(m.channel)
766 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
767 @channels[m.channel].users.delete(m.sourcenick)
770 # delegate to plugins
771 @plugins.delegate("listen", m)
772 @plugins.delegate("part", m)
775 # respond to being kicked from a channel
778 debug "kicked from channel #{m.channel}"
779 @channels.delete(m.channel)
780 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
782 @channels[m.channel].users.delete(m.sourcenick)
783 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
786 @plugins.delegate("listen", m)
787 @plugins.delegate("kick", m)
791 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
792 @channels[m.channel].topic = m.topic if !m.topic.nil?
793 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
794 @channels[m.channel].topic.by = m.source if !m.source.nil?
796 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
799 # delegate a privmsg to auth, keyword or plugin handlers
800 def delegate_privmsg(message)
801 [@auth, @plugins, @keywords].each {|m|
802 break if m.privmsg(message)