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.
24 require 'rbot/rfc2812'
25 require 'rbot/keywords'
27 require 'rbot/ircsocket'
30 require 'rbot/plugins'
31 require 'rbot/channel'
33 require 'rbot/message'
34 require 'rbot/language'
36 require 'rbot/registry'
37 require 'rbot/httputil'
41 # Main bot class, which receives messages, handles them or passes them to
42 # plugins, and stores runtime data
44 # the bot's current nickname
47 # the bot's IrcAuth data
50 # the bot's BotConfig data
53 # the botclass for this bot (determines configdir among other things)
56 # used to perform actions periodically (saves configuration once per minute
63 # bot's configured addressing prefixes
64 attr_reader :addressing_prefixes
66 # channel info for channels the bot is in
69 # bot's object registry, plugins get an interface to this for persistant
70 # storage (hash interface tied to a bdb file, plugins use Accessors to store
71 # and restore objects in their own namespaces.)
74 # bot's httputil help object, for fetching resources via http. Sets up
75 # proxies etc as defined by the bot configuration/environment
78 # create a new IrcBot with botclass +botclass+
79 def initialize(botclass)
80 @botclass = botclass.gsub(/\/$/, "")
81 @startup_time = Time.new
83 Dir.mkdir("#{botclass}") if(!File.exist?("#{botclass}"))
84 Dir.mkdir("#{botclass}/logs") if(!File.exist?("#{botclass}/logs"))
86 @config = Irc::BotConfig.new(self)
87 @timer = Timer::Timer.new
88 @registry = BotRegistry.new self
89 @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
93 @httputil = Irc::HttpUtil.new(self)
94 @lang = Irc::Language.new(@config['core.language'])
95 @keywords = Irc::Keywords.new(self)
96 @auth = Irc::IrcAuth.new(self)
97 @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
99 @socket = Irc::IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
100 @nick = @config['irc.nick']
101 if @config['core.address_prefix']
102 @addressing_prefixes = @config['core.address_prefix'].split(" ")
104 @addressing_prefixes = Array.new
107 @client = Irc::IrcClient.new
108 @client["PRIVMSG"] = proc { |data|
109 message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
112 @client["NOTICE"] = proc { |data|
113 message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
114 # pass it off to plugins that want to hear everything
115 @plugins.delegate "listen", message
117 @client["MOTD"] = proc { |data|
118 data['MOTD'].each_line { |line|
119 log "MOTD: #{line}", "server"
122 @client["NICKTAKEN"] = proc { |data|
125 @client["BADNICK"] = proc {|data|
126 puts "WARNING, bad nick (#{data['NICK']})"
128 @client["PING"] = proc {|data|
129 # (jump the queue for pongs)
130 @socket.puts "PONG #{data['PINGID']}"
132 @client["NICK"] = proc {|data|
133 sourcenick = data["SOURCENICK"]
135 m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"])
136 if(sourcenick == @nick)
139 @channels.each {|k,v|
140 if(v.users.has_key?(sourcenick))
141 log "@ #{sourcenick} is now known as #{nick}", k
142 v.users[nick] = v.users[sourcenick]
143 v.users.delete(sourcenick)
146 @plugins.delegate("listen", m)
147 @plugins.delegate("nick", m)
149 @client["QUIT"] = proc {|data|
150 source = data["SOURCE"]
151 sourcenick = data["SOURCENICK"]
152 sourceurl = data["SOURCEADDRESS"]
153 message = data["MESSAGE"]
154 m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"])
155 if(data["SOURCENICK"] =~ /#{@nick}/i)
157 @channels.each {|k,v|
158 if(v.users.has_key?(sourcenick))
159 log "@ Quit: #{sourcenick}: #{message}", k
160 v.users.delete(sourcenick)
164 @plugins.delegate("listen", m)
165 @plugins.delegate("quit", m)
167 @client["MODE"] = proc {|data|
168 source = data["SOURCE"]
169 sourcenick = data["SOURCENICK"]
170 sourceurl = data["SOURCEADDRESS"]
171 channel = data["CHANNEL"]
172 targets = data["TARGETS"]
173 modestring = data["MODESTRING"]
174 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
176 @client["WELCOME"] = proc {|data|
177 log "joined server #{data['SOURCE']} as #{data['NICK']}", "server"
178 debug "I think my nick is #{@nick}, server thinks #{data['NICK']}"
179 if data['NICK'] && data['NICK'].length > 0
182 if(@config['irc.quser'])
183 puts "authing with Q using #{@config['quakenet.user']} #{@config['quakenet.auth']}"
184 @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config['quakenet.user']} #{@config['quakenet.auth']}"
187 if(@config['irc.join_channels'])
188 @config['irc.join_channels'].split(", ").each {|c|
189 puts "autojoining channel #{c}"
190 if(c =~ /^(\S+)\s+(\S+)$/i)
198 @client["JOIN"] = proc {|data|
199 m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
202 @client["PART"] = proc {|data|
203 m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
206 @client["KICK"] = proc {|data|
207 m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"])
210 @client["INVITE"] = proc {|data|
211 if(data["TARGET"] =~ /^#{@nick}$/i)
212 join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"]))
215 @client["CHANGETOPIC"] = proc {|data|
216 channel = data["CHANNEL"]
217 sourcenick = data["SOURCENICK"]
218 topic = data["TOPIC"]
219 timestamp = data["UNIXTIME"] || Time.now.to_i
220 if(sourcenick == @nick)
221 log "@ I set topic \"#{topic}\"", channel
223 log "@ #{sourcenick} set topic \"#{topic}\"", channel
225 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"])
228 @plugins.delegate("listen", m)
229 @plugins.delegate("topic", m)
231 @client["TOPIC"] = @client["TOPICINFO"] = proc {|data|
232 channel = data["CHANNEL"]
233 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"])
236 @client["NAMES"] = proc {|data|
237 channel = data["CHANNEL"]
238 users = data["USERS"]
239 unless(@channels[channel])
240 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
243 @channels[channel].users.clear
245 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
248 @client["UNKNOWN"] = proc {|data|
249 debug "UNKNOWN: #{data['SERVERSTRING']}"
253 # connect the bot to IRC
255 trap("SIGTERM") { quit }
256 trap("SIGHUP") { quit }
257 trap("SIGINT") { quit }
261 raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
263 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
264 @socket.puts "NICK #{@nick}\nUSER #{@config['server.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
267 # begin event handling loop
277 if @socket.select socket_timeout
278 break unless reply = @socket.gets
279 @client.process reply
284 puts "connection closed: #{e}"
285 puts e.backtrace.join("\n")
292 puts "waiting to reconnect"
297 # type:: message type
298 # where:: message target
299 # message:: message text
300 # send message +message+ of type +type+ to target +where+
301 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
302 # relevant say() or notice() methods. This one should be used for IRCd
303 # extensions you want to use in modules.
304 def sendmsg(type, where, message)
305 # limit it 440 chars + CRLF.. so we have to split long lines
306 left = 440 - type.length - where.length - 3
308 if(left >= message.length)
309 sendq("#{type} #{where} :#{message}")
310 log_sent(type, where, message)
313 line = message.slice!(0, left)
314 lastspace = line.rindex(/\s+/)
316 message = line.slice!(lastspace, line.length) + message
317 message.gsub!(/^\s+/, "")
319 sendq("#{type} #{where} :#{line}")
320 log_sent(type, where, line)
321 end while(message.length > 0)
324 def sendq(message="")
326 @socket.queue(message)
329 # send a notice message to channel/nick +where+
330 def notice(where, message)
331 message.each_line { |line|
333 next unless(line.length > 0)
334 sendmsg("NOTICE", where, line)
338 # say something (PRIVMSG) to channel/nick +where+
339 def say(where, message)
340 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
342 next unless(line.length > 0)
343 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
344 sendmsg("PRIVMSG", where, line)
349 # perform a CTCP action with message +message+ to channel/nick +where+
350 def action(where, message)
351 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
353 log "* #{@nick} #{message}", where
354 elsif (where =~ /^(\S*)!.*$/)
355 log "* #{@nick}[#{where}] #{message}", $1
357 log "* #{@nick}[#{where}] #{message}", where
361 # quick way to say "okay" (or equivalent) to +where+
363 say where, @lang.get("okay")
366 # log message +message+ to a file determined by +where+. +where+ can be a
367 # channel name, or a nick for private message logging
368 def log(message, where="server")
370 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
371 unless(@logs.has_key?(where))
372 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
373 @logs[where].sync = true
375 @logs[where].puts "[#{stamp}] #{message}"
376 #debug "[#{stamp}] <#{where}> #{message}"
379 # set topic of channel +where+ to +topic+
380 def topic(where, topic)
381 sendq "TOPIC #{where} :#{topic}"
384 # message:: optional IRC quit message
385 # quit IRC, shutdown the bot
386 def quit(message=nil)
387 trap("SIGTERM", "DEFAULT")
388 trap("SIGHUP", "DEFAULT")
389 trap("SIGINT", "DEFAULT")
390 message = @lang.get("quit") if (!message || message.length < 1)
394 @channels.each_value {|v|
395 log "@ quit (#{message})", v.name
397 @socket.puts "QUIT :#{message}"
401 puts "rbot quit (#{message})"
405 # call the save method for bot's config, keywords, auth and all plugins
414 # call the rescan method for the bot's lang, keywords and all plugins
421 # channel:: channel to join
422 # key:: optional channel key if channel is +s
424 def join(channel, key=nil)
426 sendq "JOIN #{channel} :#{key}"
428 sendq "JOIN #{channel}"
433 def part(channel, message="")
434 sendq "PART #{channel} :#{message}"
437 # attempt to change bot's nick to +name+
443 def mode(channel, mode, target)
444 sendq "MODE #{channel} #{mode} #{target}"
447 # m:: message asking for help
448 # topic:: optional topic help is requested for
449 # respond to online help requests
451 topic = nil if topic == ""
454 helpstr = "help topics: core, auth, keywords"
455 helpstr += @plugins.helptopics
456 helpstr += " (help <topic> for more info)"
459 when /^core\s+(.+)$/i
460 helpstr = corehelp $1
463 when /^auth\s+(.+)$/i
464 helpstr = @auth.help $1
466 helpstr = @keywords.help
467 when /^keywords\s+(.+)$/i
468 helpstr = @keywords.help $1
470 unless(helpstr = @plugins.help(topic))
471 helpstr = "no help for topic #{topic}"
478 secs_up = Time.new - @startup_time
479 uptime = Utils.secs_to_string secs_up
480 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
486 # handle help requests for "core" topics
487 def corehelp(topic="")
490 return "quit [<message>] => quit IRC with message <message>"
492 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"
494 return "part <channel> => part channel <channel>"
496 return "hide => part all channels"
498 return "save => save current dynamic data and configuration"
500 return "rescan => reload modules and static facts"
502 return "nick <nick> => attempt to change nick to <nick>"
504 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
506 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
508 return "topic <channel> <message> => set topic of <channel> to <message>"
510 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>"
512 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>"
514 return "version => describes software version"
516 return "botsnack => reward #{@nick} for being good"
518 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
520 return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
524 # handle incoming IRC PRIVMSG +m+
529 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
531 log "* #{m.sourcenick} #{m.message}", m.target
535 log "<#{m.sourcenick}> #{m.message}", m.target
537 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
541 # pass it off to plugins that want to hear everything
542 @plugins.delegate "listen", m
544 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
545 notice m.sourcenick, "\001PING #$1\001"
546 log "@ #{m.sourcenick} pinged me"
552 when (/^join\s+(\S+)\s+(\S+)$/i)
553 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
554 when (/^join\s+(\S+)$/i)
555 join $1 if(@auth.allow?("join", m.source, m.replyto))
557 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
558 when (/^part\s+(\S+)$/i)
559 part $1 if(@auth.allow?("join", m.source, m.replyto))
560 when (/^quit(?:\s+(.*))?$/i)
561 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
563 join 0 if(@auth.allow?("join", m.source, m.replyto))
565 if(@auth.allow?("config", m.source, m.replyto))
569 when (/^nick\s+(\S+)$/i)
570 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
571 when (/^say\s+(\S+)\s+(.*)$/i)
572 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
573 when (/^action\s+(\S+)\s+(.*)$/i)
574 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
575 when (/^topic\s+(\S+)\s+(.*)$/i)
576 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
577 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
578 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
580 say m.replyto, "pong"
582 if(@auth.allow?("config", m.source, m.replyto))
587 if(auth.allow?("talk", m.source, m.replyto))
589 @channels.each_value {|c| c.quiet = true }
591 when (/^quiet in (\S+)$/i)
593 if(auth.allow?("talk", m.source, m.replyto))
595 where.gsub!(/^here$/, m.target) if m.public?
596 @channels[where].quiet = true if(@channels.has_key?(where))
599 if(auth.allow?("talk", m.source, m.replyto))
600 @channels.each_value {|c| c.quiet = false }
603 when (/^talk in (\S+)$/i)
605 if(auth.allow?("talk", m.source, m.replyto))
606 where.gsub!(/^here$/, m.target) if m.public?
607 @channels[where].quiet = false if(@channels.has_key?(where))
610 # TODO break this out into a config module
611 when (/^options get sendq_delay$/i)
612 if auth.allow?("config", m.source, m.replyto)
613 m.reply "options->sendq_delay = #{@socket.sendq_delay}"
615 when (/^options get sendq_burst$/i)
616 if auth.allow?("config", m.source, m.replyto)
617 m.reply "options->sendq_burst = #{@socket.sendq_burst}"
619 when (/^options set sendq_burst (.*)$/i)
621 if auth.allow?("config", m.source, m.replyto)
622 @socket.sendq_burst = num
623 @config['irc.sendq_burst'] = num
626 when (/^options set sendq_delay (.*)$/i)
628 if auth.allow?("config", m.source, m.replyto)
629 @socket.sendq_delay = freq
630 @config['irc.sendq_delay'] = freq
634 m.reply status if auth.allow?("status", m.source, m.replyto)
635 when (/^registry stats$/i)
636 if auth.allow?("config", m.source, m.replyto)
637 m.reply @registry.stat.inspect
639 when (/^(version)|(introduce yourself)$/i)
640 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
641 when (/^help(?:\s+(.*))?$/i)
642 say m.replyto, help($1)
643 when (/^(botsnack|ciggie)$/i)
644 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
645 say m.replyto, @lang.get("thanks") if(m.private?)
646 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
647 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
648 say m.replyto, @lang.get("hello") if(m.private?)
653 # stuff to handle when not addressed
655 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))\s+#{@nick}$/i)
656 say m.replyto, @lang.get("hello_X") % m.sourcenick
657 when (/^#{@nick}!*$/)
658 say m.replyto, @lang.get("hello_X") % m.sourcenick
665 # log a message. Internal use only.
666 def log_sent(type, where, message)
670 log "-=#{@nick}=- #{message}", where
671 elsif (where =~ /(\S*)!.*/)
672 log "[-=#{where}=-] #{message}", $1
674 log "[-=#{where}=-] #{message}"
678 log "<#{@nick}> #{message}", where
679 elsif (where =~ /^(\S*)!.*$/)
680 log "[msg(#{where})] #{message}", $1
682 log "[msg(#{where})] #{message}", where
688 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
690 log "@ Joined channel #{m.channel}", m.channel
691 puts "joined channel #{m.channel}"
693 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
694 @channels[m.channel].users[m.sourcenick] = Hash.new
695 @channels[m.channel].users[m.sourcenick]["mode"] = ""
698 @plugins.delegate("listen", m)
699 @plugins.delegate("join", m)
704 log "@ Left channel #{m.channel} (#{m.message})", m.channel
705 @channels.delete(m.channel)
706 puts "left channel #{m.channel}"
708 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
709 @channels[m.channel].users.delete(m.sourcenick)
712 # delegate to plugins
713 @plugins.delegate("listen", m)
714 @plugins.delegate("part", m)
717 # respond to being kicked from a channel
720 @channels.delete(m.channel)
721 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
722 puts "kicked from channel #{m.channel}"
724 @channels[m.channel].users.delete(m.sourcenick)
725 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
728 @plugins.delegate("listen", m)
729 @plugins.delegate("kick", m)
733 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
734 @channels[m.channel].topic = m.topic if !m.topic.nil?
735 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
736 @channels[m.channel].topic.by = m.source if !m.source.nil?
738 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
741 # delegate a privmsg to auth, keyword or plugin handlers
742 def delegate_privmsg(message)
743 [@auth, @plugins, @keywords].each {|m|
744 break if m.privmsg(message)