1 # Copyright (C) 2002 Tom Gilbert.
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to
5 # deal in the Software without restriction, including without limitation the
6 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 # sell copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
10 # The above copyright notice and this permission notice shall be included in
11 # all copies of the Software and its documentation and acknowledgment shall be
12 # given in the documentation and software packages that this Software was
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 # THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 require 'rbot/rfc2812'
27 require 'rbot/keywords'
29 require 'rbot/ircsocket'
32 require 'rbot/plugins'
33 require 'rbot/channel'
35 require 'rbot/message'
36 require 'rbot/language'
38 require 'rbot/registry'
39 require 'rbot/httputil'
40 require 'rbot/rbotconfig'
44 # Main bot class, which receives messages, handles them or passes them to
45 # plugins, and stores runtime data
47 # the bot's current nickname
50 # the bot's IrcAuth data
53 # the bot's BotConfig data
56 # the botclass for this bot (determines configdir among other things)
59 # used to perform actions periodically (saves configuration once per minute
66 # bot's configured addressing prefixes
67 attr_reader :addressing_prefixes
69 # channel info for channels the bot is in
72 # bot's object registry, plugins get an interface to this for persistant
73 # storage (hash interface tied to a bdb file, plugins use Accessors to store
74 # and restore objects in their own namespaces.)
77 # bot's httputil help object, for fetching resources via http. Sets up
78 # proxies etc as defined by the bot configuration/environment
81 # create a new IrcBot with botclass +botclass+
82 def initialize(botclass)
83 unless FileTest.directory? Config::DATADIR
84 puts "no data directory '#{Config::DATADIR}' found, did you run install.rb?"
88 botclass = "/home/#{Etc.getlogin}/.rbot" unless botclass
89 @botclass = botclass.gsub(/\/$/, "")
91 unless FileTest.directory? botclass
92 puts "no #{botclass} directory found, creating from templates.."
93 if FileTest.exist? botclass
94 puts "Error: file #{botclass} exists but isn't a directory"
97 FileUtils.cp_r Config::DATADIR+'/templates', botclass
100 Dir.mkdir("#{botclass}/logs") if(!File.exist?("#{botclass}/logs"))
102 @startup_time = Time.new
103 @config = Irc::BotConfig.new(self)
104 @timer = Timer::Timer.new
105 @registry = BotRegistry.new self
106 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
110 @httputil = Irc::HttpUtil.new(self)
111 @lang = Irc::Language.new(@config['core.language'])
112 @keywords = Irc::Keywords.new(self)
113 @auth = Irc::IrcAuth.new(self)
114 @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
116 @socket = Irc::IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
117 @nick = @config['irc.nick']
118 if @config['core.address_prefix']
119 @addressing_prefixes = @config['core.address_prefix'].split(" ")
121 @addressing_prefixes = Array.new
124 @client = Irc::IrcClient.new
125 @client["PRIVMSG"] = proc { |data|
126 message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
129 @client["NOTICE"] = proc { |data|
130 message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
131 # pass it off to plugins that want to hear everything
132 @plugins.delegate "listen", message
134 @client["MOTD"] = proc { |data|
135 data['MOTD'].each_line { |line|
136 log "MOTD: #{line}", "server"
139 @client["NICKTAKEN"] = proc { |data|
142 @client["BADNICK"] = proc {|data|
143 puts "WARNING, bad nick (#{data['NICK']})"
145 @client["PING"] = proc {|data|
146 # (jump the queue for pongs)
147 @socket.puts "PONG #{data['PINGID']}"
149 @client["NICK"] = proc {|data|
150 sourcenick = data["SOURCENICK"]
152 m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"])
153 if(sourcenick == @nick)
156 @channels.each {|k,v|
157 if(v.users.has_key?(sourcenick))
158 log "@ #{sourcenick} is now known as #{nick}", k
159 v.users[nick] = v.users[sourcenick]
160 v.users.delete(sourcenick)
163 @plugins.delegate("listen", m)
164 @plugins.delegate("nick", m)
166 @client["QUIT"] = proc {|data|
167 source = data["SOURCE"]
168 sourcenick = data["SOURCENICK"]
169 sourceurl = data["SOURCEADDRESS"]
170 message = data["MESSAGE"]
171 m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"])
172 if(data["SOURCENICK"] =~ /#{@nick}/i)
174 @channels.each {|k,v|
175 if(v.users.has_key?(sourcenick))
176 log "@ Quit: #{sourcenick}: #{message}", k
177 v.users.delete(sourcenick)
181 @plugins.delegate("listen", m)
182 @plugins.delegate("quit", m)
184 @client["MODE"] = proc {|data|
185 source = data["SOURCE"]
186 sourcenick = data["SOURCENICK"]
187 sourceurl = data["SOURCEADDRESS"]
188 channel = data["CHANNEL"]
189 targets = data["TARGETS"]
190 modestring = data["MODESTRING"]
191 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
193 @client["WELCOME"] = proc {|data|
194 log "joined server #{data['SOURCE']} as #{data['NICK']}", "server"
195 debug "I think my nick is #{@nick}, server thinks #{data['NICK']}"
196 if data['NICK'] && data['NICK'].length > 0
199 if(@config['irc.quser'])
200 puts "authing with Q using #{@config['quakenet.user']} #{@config['quakenet.auth']}"
201 @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config['quakenet.user']} #{@config['quakenet.auth']}"
204 if(@config['irc.join_channels'])
205 @config['irc.join_channels'].split(", ").each {|c|
206 puts "autojoining channel #{c}"
207 if(c =~ /^(\S+)\s+(\S+)$/i)
215 @client["JOIN"] = proc {|data|
216 m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
219 @client["PART"] = proc {|data|
220 m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
223 @client["KICK"] = proc {|data|
224 m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"])
227 @client["INVITE"] = proc {|data|
228 if(data["TARGET"] =~ /^#{@nick}$/i)
229 join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"]))
232 @client["CHANGETOPIC"] = proc {|data|
233 channel = data["CHANNEL"]
234 sourcenick = data["SOURCENICK"]
235 topic = data["TOPIC"]
236 timestamp = data["UNIXTIME"] || Time.now.to_i
237 if(sourcenick == @nick)
238 log "@ I set topic \"#{topic}\"", channel
240 log "@ #{sourcenick} set topic \"#{topic}\"", channel
242 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"])
245 @plugins.delegate("listen", m)
246 @plugins.delegate("topic", m)
248 @client["TOPIC"] = @client["TOPICINFO"] = proc {|data|
249 channel = data["CHANNEL"]
250 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"])
253 @client["NAMES"] = proc {|data|
254 channel = data["CHANNEL"]
255 users = data["USERS"]
256 unless(@channels[channel])
257 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
260 @channels[channel].users.clear
262 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
265 @client["UNKNOWN"] = proc {|data|
266 debug "UNKNOWN: #{data['SERVERSTRING']}"
270 # connect the bot to IRC
272 trap("SIGTERM") { quit }
273 trap("SIGHUP") { quit }
274 trap("SIGINT") { quit }
278 raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
280 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
281 @socket.puts "NICK #{@nick}\nUSER #{@config['server.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
284 # begin event handling loop
294 if @socket.select socket_timeout
295 break unless reply = @socket.gets
296 @client.process reply
301 puts "connection closed: #{e}"
302 puts e.backtrace.join("\n")
309 puts "waiting to reconnect"
314 # type:: message type
315 # where:: message target
316 # message:: message text
317 # send message +message+ of type +type+ to target +where+
318 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
319 # relevant say() or notice() methods. This one should be used for IRCd
320 # extensions you want to use in modules.
321 def sendmsg(type, where, message)
322 # limit it 440 chars + CRLF.. so we have to split long lines
323 left = 440 - type.length - where.length - 3
325 if(left >= message.length)
326 sendq("#{type} #{where} :#{message}")
327 log_sent(type, where, message)
330 line = message.slice!(0, left)
331 lastspace = line.rindex(/\s+/)
333 message = line.slice!(lastspace, line.length) + message
334 message.gsub!(/^\s+/, "")
336 sendq("#{type} #{where} :#{line}")
337 log_sent(type, where, line)
338 end while(message.length > 0)
341 def sendq(message="")
343 @socket.queue(message)
346 # send a notice message to channel/nick +where+
347 def notice(where, message)
348 message.each_line { |line|
350 next unless(line.length > 0)
351 sendmsg("NOTICE", where, line)
355 # say something (PRIVMSG) to channel/nick +where+
356 def say(where, message)
357 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
359 next unless(line.length > 0)
360 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
361 sendmsg("PRIVMSG", where, line)
366 # perform a CTCP action with message +message+ to channel/nick +where+
367 def action(where, message)
368 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
370 log "* #{@nick} #{message}", where
371 elsif (where =~ /^(\S*)!.*$/)
372 log "* #{@nick}[#{where}] #{message}", $1
374 log "* #{@nick}[#{where}] #{message}", where
378 # quick way to say "okay" (or equivalent) to +where+
380 say where, @lang.get("okay")
383 # log message +message+ to a file determined by +where+. +where+ can be a
384 # channel name, or a nick for private message logging
385 def log(message, where="server")
387 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
388 unless(@logs.has_key?(where))
389 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
390 @logs[where].sync = true
392 @logs[where].puts "[#{stamp}] #{message}"
393 #debug "[#{stamp}] <#{where}> #{message}"
396 # set topic of channel +where+ to +topic+
397 def topic(where, topic)
398 sendq "TOPIC #{where} :#{topic}"
401 # message:: optional IRC quit message
402 # quit IRC, shutdown the bot
403 def quit(message=nil)
404 trap("SIGTERM", "DEFAULT")
405 trap("SIGHUP", "DEFAULT")
406 trap("SIGINT", "DEFAULT")
407 message = @lang.get("quit") if (!message || message.length < 1)
411 @channels.each_value {|v|
412 log "@ quit (#{message})", v.name
414 @socket.puts "QUIT :#{message}"
418 puts "rbot quit (#{message})"
422 # call the save method for bot's config, keywords, auth and all plugins
431 # call the rescan method for the bot's lang, keywords and all plugins
438 # channel:: channel to join
439 # key:: optional channel key if channel is +s
441 def join(channel, key=nil)
443 sendq "JOIN #{channel} :#{key}"
445 sendq "JOIN #{channel}"
450 def part(channel, message="")
451 sendq "PART #{channel} :#{message}"
454 # attempt to change bot's nick to +name+
460 def mode(channel, mode, target)
461 sendq "MODE #{channel} #{mode} #{target}"
464 # m:: message asking for help
465 # topic:: optional topic help is requested for
466 # respond to online help requests
468 topic = nil if topic == ""
471 helpstr = "help topics: core, auth, keywords"
472 helpstr += @plugins.helptopics
473 helpstr += " (help <topic> for more info)"
476 when /^core\s+(.+)$/i
477 helpstr = corehelp $1
480 when /^auth\s+(.+)$/i
481 helpstr = @auth.help $1
483 helpstr = @keywords.help
484 when /^keywords\s+(.+)$/i
485 helpstr = @keywords.help $1
487 unless(helpstr = @plugins.help(topic))
488 helpstr = "no help for topic #{topic}"
495 secs_up = Time.new - @startup_time
496 uptime = Utils.secs_to_string secs_up
497 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
503 # handle help requests for "core" topics
504 def corehelp(topic="")
507 return "quit [<message>] => quit IRC with message <message>"
509 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"
511 return "part <channel> => part channel <channel>"
513 return "hide => part all channels"
515 return "save => save current dynamic data and configuration"
517 return "rescan => reload modules and static facts"
519 return "nick <nick> => attempt to change nick to <nick>"
521 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
523 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
525 return "topic <channel> <message> => set topic of <channel> to <message>"
527 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>"
529 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>"
531 return "version => describes software version"
533 return "botsnack => reward #{@nick} for being good"
535 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
537 return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
541 # handle incoming IRC PRIVMSG +m+
546 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
548 log "* #{m.sourcenick} #{m.message}", m.target
552 log "<#{m.sourcenick}> #{m.message}", m.target
554 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
558 # pass it off to plugins that want to hear everything
559 @plugins.delegate "listen", m
561 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
562 notice m.sourcenick, "\001PING #$1\001"
563 log "@ #{m.sourcenick} pinged me"
569 when (/^join\s+(\S+)\s+(\S+)$/i)
570 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
571 when (/^join\s+(\S+)$/i)
572 join $1 if(@auth.allow?("join", m.source, m.replyto))
574 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
575 when (/^part\s+(\S+)$/i)
576 part $1 if(@auth.allow?("join", m.source, m.replyto))
577 when (/^quit(?:\s+(.*))?$/i)
578 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
580 join 0 if(@auth.allow?("join", m.source, m.replyto))
582 if(@auth.allow?("config", m.source, m.replyto))
586 when (/^nick\s+(\S+)$/i)
587 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
588 when (/^say\s+(\S+)\s+(.*)$/i)
589 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
590 when (/^action\s+(\S+)\s+(.*)$/i)
591 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
592 when (/^topic\s+(\S+)\s+(.*)$/i)
593 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
594 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
595 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
597 say m.replyto, "pong"
599 if(@auth.allow?("config", m.source, m.replyto))
604 if(auth.allow?("talk", m.source, m.replyto))
606 @channels.each_value {|c| c.quiet = true }
608 when (/^quiet in (\S+)$/i)
610 if(auth.allow?("talk", m.source, m.replyto))
612 where.gsub!(/^here$/, m.target) if m.public?
613 @channels[where].quiet = true if(@channels.has_key?(where))
616 if(auth.allow?("talk", m.source, m.replyto))
617 @channels.each_value {|c| c.quiet = false }
620 when (/^talk in (\S+)$/i)
622 if(auth.allow?("talk", m.source, m.replyto))
623 where.gsub!(/^here$/, m.target) if m.public?
624 @channels[where].quiet = false if(@channels.has_key?(where))
627 # TODO break this out into a config module
628 when (/^options get sendq_delay$/i)
629 if auth.allow?("config", m.source, m.replyto)
630 m.reply "options->sendq_delay = #{@socket.sendq_delay}"
632 when (/^options get sendq_burst$/i)
633 if auth.allow?("config", m.source, m.replyto)
634 m.reply "options->sendq_burst = #{@socket.sendq_burst}"
636 when (/^options set sendq_burst (.*)$/i)
638 if auth.allow?("config", m.source, m.replyto)
639 @socket.sendq_burst = num
640 @config['irc.sendq_burst'] = num
643 when (/^options set sendq_delay (.*)$/i)
645 if auth.allow?("config", m.source, m.replyto)
646 @socket.sendq_delay = freq
647 @config['irc.sendq_delay'] = freq
651 m.reply status if auth.allow?("status", m.source, m.replyto)
652 when (/^registry stats$/i)
653 if auth.allow?("config", m.source, m.replyto)
654 m.reply @registry.stat.inspect
656 when (/^(version)|(introduce yourself)$/i)
657 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
658 when (/^help(?:\s+(.*))?$/i)
659 say m.replyto, help($1)
660 when (/^(botsnack|ciggie)$/i)
661 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
662 say m.replyto, @lang.get("thanks") if(m.private?)
663 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
664 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
665 say m.replyto, @lang.get("hello") if(m.private?)
670 # stuff to handle when not addressed
672 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))\s+#{@nick}$/i)
673 say m.replyto, @lang.get("hello_X") % m.sourcenick
674 when (/^#{@nick}!*$/)
675 say m.replyto, @lang.get("hello_X") % m.sourcenick
682 # log a message. Internal use only.
683 def log_sent(type, where, message)
687 log "-=#{@nick}=- #{message}", where
688 elsif (where =~ /(\S*)!.*/)
689 log "[-=#{where}=-] #{message}", $1
691 log "[-=#{where}=-] #{message}"
695 log "<#{@nick}> #{message}", where
696 elsif (where =~ /^(\S*)!.*$/)
697 log "[msg(#{where})] #{message}", $1
699 log "[msg(#{where})] #{message}", where
705 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
707 log "@ Joined channel #{m.channel}", m.channel
708 puts "joined channel #{m.channel}"
710 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
711 @channels[m.channel].users[m.sourcenick] = Hash.new
712 @channels[m.channel].users[m.sourcenick]["mode"] = ""
715 @plugins.delegate("listen", m)
716 @plugins.delegate("join", m)
721 log "@ Left channel #{m.channel} (#{m.message})", m.channel
722 @channels.delete(m.channel)
723 puts "left channel #{m.channel}"
725 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
726 @channels[m.channel].users.delete(m.sourcenick)
729 # delegate to plugins
730 @plugins.delegate("listen", m)
731 @plugins.delegate("part", m)
734 # respond to being kicked from a channel
737 @channels.delete(m.channel)
738 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
739 puts "kicked from channel #{m.channel}"
741 @channels[m.channel].users.delete(m.sourcenick)
742 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
745 @plugins.delegate("listen", m)
746 @plugins.delegate("kick", m)
750 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
751 @channels[m.channel].topic = m.topic if !m.topic.nil?
752 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
753 @channels[m.channel].topic.by = m.source if !m.source.nil?
755 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
758 # delegate a privmsg to auth, keyword or plugin handlers
759 def delegate_privmsg(message)
760 [@auth, @plugins, @keywords].each {|m|
761 break if m.privmsg(message)