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 "data directory '#{Config::DATADIR}' not found, did you 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") unless File.exist?("#{botclass}/logs")
102 @startup_time = Time.new
103 @config = Irc::BotConfig.new(self)
104 @timer = Timer::Timer.new(1.0) # only need per-second granularity
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)
115 Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
116 @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
118 @socket = Irc::IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
119 @nick = @config['irc.nick']
120 if @config['core.address_prefix']
121 @addressing_prefixes = @config['core.address_prefix'].split(" ")
123 @addressing_prefixes = Array.new
126 @client = Irc::IrcClient.new
127 @client["PRIVMSG"] = proc { |data|
128 message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
131 @client["NOTICE"] = proc { |data|
132 message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
133 # pass it off to plugins that want to hear everything
134 @plugins.delegate "listen", message
136 @client["MOTD"] = proc { |data|
137 data['MOTD'].each_line { |line|
138 log "MOTD: #{line}", "server"
141 @client["NICKTAKEN"] = proc { |data|
144 @client["BADNICK"] = proc {|data|
145 puts "WARNING, bad nick (#{data['NICK']})"
147 @client["PING"] = proc {|data|
148 # (jump the queue for pongs)
149 @socket.puts "PONG #{data['PINGID']}"
151 @client["NICK"] = proc {|data|
152 sourcenick = data["SOURCENICK"]
154 m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"])
155 if(sourcenick == @nick)
158 @channels.each {|k,v|
159 if(v.users.has_key?(sourcenick))
160 log "@ #{sourcenick} is now known as #{nick}", k
161 v.users[nick] = v.users[sourcenick]
162 v.users.delete(sourcenick)
165 @plugins.delegate("listen", m)
166 @plugins.delegate("nick", m)
168 @client["QUIT"] = proc {|data|
169 source = data["SOURCE"]
170 sourcenick = data["SOURCENICK"]
171 sourceurl = data["SOURCEADDRESS"]
172 message = data["MESSAGE"]
173 m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"])
174 if(data["SOURCENICK"] =~ /#{@nick}/i)
176 @channels.each {|k,v|
177 if(v.users.has_key?(sourcenick))
178 log "@ Quit: #{sourcenick}: #{message}", k
179 v.users.delete(sourcenick)
183 @plugins.delegate("listen", m)
184 @plugins.delegate("quit", m)
186 @client["MODE"] = proc {|data|
187 source = data["SOURCE"]
188 sourcenick = data["SOURCENICK"]
189 sourceurl = data["SOURCEADDRESS"]
190 channel = data["CHANNEL"]
191 targets = data["TARGETS"]
192 modestring = data["MODESTRING"]
193 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
195 @client["WELCOME"] = proc {|data|
196 log "joined server #{data['SOURCE']} as #{data['NICK']}", "server"
197 debug "I think my nick is #{@nick}, server thinks #{data['NICK']}"
198 if data['NICK'] && data['NICK'].length > 0
201 if(@config['irc.quser'])
202 puts "authing with Q using #{@config['quakenet.user']} #{@config['quakenet.auth']}"
203 @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config['quakenet.user']} #{@config['quakenet.auth']}"
206 if(@config['irc.join_channels'])
207 @config['irc.join_channels'].split(", ").each {|c|
208 debug "autojoining channel #{c}"
209 if(c =~ /^(\S+)\s+(\S+)$/i)
217 @client["JOIN"] = proc {|data|
218 m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
221 @client["PART"] = proc {|data|
222 m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
225 @client["KICK"] = proc {|data|
226 m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"])
229 @client["INVITE"] = proc {|data|
230 if(data["TARGET"] =~ /^#{@nick}$/i)
231 join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"]))
234 @client["CHANGETOPIC"] = proc {|data|
235 channel = data["CHANNEL"]
236 sourcenick = data["SOURCENICK"]
237 topic = data["TOPIC"]
238 timestamp = data["UNIXTIME"] || Time.now.to_i
239 if(sourcenick == @nick)
240 log "@ I set topic \"#{topic}\"", channel
242 log "@ #{sourcenick} set topic \"#{topic}\"", channel
244 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"])
247 @plugins.delegate("listen", m)
248 @plugins.delegate("topic", m)
250 @client["TOPIC"] = @client["TOPICINFO"] = proc {|data|
251 channel = data["CHANNEL"]
252 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"])
255 @client["NAMES"] = proc {|data|
256 channel = data["CHANNEL"]
257 users = data["USERS"]
258 unless(@channels[channel])
259 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
262 @channels[channel].users.clear
264 @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
267 @client["UNKNOWN"] = proc {|data|
268 debug "UNKNOWN: #{data['SERVERSTRING']}"
272 # connect the bot to IRC
274 trap("SIGTERM") { quit }
275 trap("SIGHUP") { quit }
276 trap("SIGINT") { quit }
280 raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
282 @socket.puts "PASS " + @config['server.password'] if @config['server.password']
283 @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
286 # begin event handling loop
295 break unless reply = @socket.gets
296 @client.process reply
300 puts "connection closed: #{e}"
301 puts e.backtrace.join("\n")
308 puts "waiting to reconnect"
309 sleep @config['server.reconnect_wait']
313 # type:: message type
314 # where:: message target
315 # message:: message text
316 # send message +message+ of type +type+ to target +where+
317 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
318 # relevant say() or notice() methods. This one should be used for IRCd
319 # extensions you want to use in modules.
320 def sendmsg(type, where, message)
321 # limit it 440 chars + CRLF.. so we have to split long lines
322 left = 440 - type.length - where.length - 3
324 if(left >= message.length)
325 sendq("#{type} #{where} :#{message}")
326 log_sent(type, where, message)
329 line = message.slice!(0, left)
330 lastspace = line.rindex(/\s+/)
332 message = line.slice!(lastspace, line.length) + message
333 message.gsub!(/^\s+/, "")
335 sendq("#{type} #{where} :#{line}")
336 log_sent(type, where, line)
337 end while(message.length > 0)
340 def sendq(message="")
342 @socket.queue(message)
345 # send a notice message to channel/nick +where+
346 def notice(where, message)
347 message.each_line { |line|
349 next unless(line.length > 0)
350 sendmsg("NOTICE", where, line)
354 # say something (PRIVMSG) to channel/nick +where+
355 def say(where, message)
356 message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
358 next unless(line.length > 0)
359 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
360 sendmsg("PRIVMSG", where, line)
365 # perform a CTCP action with message +message+ to channel/nick +where+
366 def action(where, message)
367 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
369 log "* #{@nick} #{message}", where
370 elsif (where =~ /^(\S*)!.*$/)
371 log "* #{@nick}[#{where}] #{message}", $1
373 log "* #{@nick}[#{where}] #{message}", where
377 # quick way to say "okay" (or equivalent) to +where+
379 say where, @lang.get("okay")
382 # log message +message+ to a file determined by +where+. +where+ can be a
383 # channel name, or a nick for private message logging
384 def log(message, where="server")
386 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
387 unless(@logs.has_key?(where))
388 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
389 @logs[where].sync = true
391 @logs[where].puts "[#{stamp}] #{message}"
392 #debug "[#{stamp}] <#{where}> #{message}"
395 # set topic of channel +where+ to +topic+
396 def topic(where, topic)
397 sendq "TOPIC #{where} :#{topic}"
400 # message:: optional IRC quit message
401 # quit IRC, shutdown the bot
402 def quit(message=nil)
403 trap("SIGTERM", "DEFAULT")
404 trap("SIGHUP", "DEFAULT")
405 trap("SIGINT", "DEFAULT")
406 message = @lang.get("quit") if (!message || message.length < 1)
410 @channels.each_value {|v|
411 log "@ quit (#{message})", v.name
413 @socket.puts "QUIT :#{message}"
417 puts "rbot quit (#{message})"
421 # call the save method for bot's config, keywords, auth and all plugins
430 # call the rescan method for the bot's lang, keywords and all plugins
437 # channel:: channel to join
438 # key:: optional channel key if channel is +s
440 def join(channel, key=nil)
442 sendq "JOIN #{channel} :#{key}"
444 sendq "JOIN #{channel}"
449 def part(channel, message="")
450 sendq "PART #{channel} :#{message}"
453 # attempt to change bot's nick to +name+
459 def mode(channel, mode, target)
460 sendq "MODE #{channel} #{mode} #{target}"
463 # m:: message asking for help
464 # topic:: optional topic help is requested for
465 # respond to online help requests
467 topic = nil if topic == ""
470 helpstr = "help topics: core, auth, keywords"
471 helpstr += @plugins.helptopics
472 helpstr += " (help <topic> for more info)"
475 when /^core\s+(.+)$/i
476 helpstr = corehelp $1
479 when /^auth\s+(.+)$/i
480 helpstr = @auth.help $1
482 helpstr = @keywords.help
483 when /^keywords\s+(.+)$/i
484 helpstr = @keywords.help $1
486 unless(helpstr = @plugins.help(topic))
487 helpstr = "no help for topic #{topic}"
494 secs_up = Time.new - @startup_time
495 uptime = Utils.secs_to_string secs_up
496 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
502 # handle help requests for "core" topics
503 def corehelp(topic="")
506 return "quit [<message>] => quit IRC with message <message>"
508 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"
510 return "part <channel> => part channel <channel>"
512 return "hide => part all channels"
514 return "save => save current dynamic data and configuration"
516 return "rescan => reload modules and static facts"
518 return "nick <nick> => attempt to change nick to <nick>"
520 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
522 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
524 return "topic <channel> <message> => set topic of <channel> to <message>"
526 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>"
528 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>"
530 return "version => describes software version"
532 return "botsnack => reward #{@nick} for being good"
534 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
536 return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
540 # handle incoming IRC PRIVMSG +m+
545 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
547 log "* #{m.sourcenick} #{m.message}", m.target
551 log "<#{m.sourcenick}> #{m.message}", m.target
553 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
557 # pass it off to plugins that want to hear everything
558 @plugins.delegate "listen", m
560 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
561 notice m.sourcenick, "\001PING #$1\001"
562 log "@ #{m.sourcenick} pinged me"
568 when (/^join\s+(\S+)\s+(\S+)$/i)
569 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
570 when (/^join\s+(\S+)$/i)
571 join $1 if(@auth.allow?("join", m.source, m.replyto))
573 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
574 when (/^part\s+(\S+)$/i)
575 part $1 if(@auth.allow?("join", m.source, m.replyto))
576 when (/^quit(?:\s+(.*))?$/i)
577 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
579 join 0 if(@auth.allow?("join", m.source, m.replyto))
581 if(@auth.allow?("config", m.source, m.replyto))
585 when (/^nick\s+(\S+)$/i)
586 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
587 when (/^say\s+(\S+)\s+(.*)$/i)
588 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
589 when (/^action\s+(\S+)\s+(.*)$/i)
590 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
591 when (/^topic\s+(\S+)\s+(.*)$/i)
592 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
593 when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
594 mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
596 say m.replyto, "pong"
598 if(@auth.allow?("config", m.source, m.replyto))
603 if(auth.allow?("talk", m.source, m.replyto))
605 @channels.each_value {|c| c.quiet = true }
607 when (/^quiet in (\S+)$/i)
609 if(auth.allow?("talk", m.source, m.replyto))
611 where.gsub!(/^here$/, m.target) if m.public?
612 @channels[where].quiet = true if(@channels.has_key?(where))
615 if(auth.allow?("talk", m.source, m.replyto))
616 @channels.each_value {|c| c.quiet = false }
619 when (/^talk in (\S+)$/i)
621 if(auth.allow?("talk", m.source, m.replyto))
622 where.gsub!(/^here$/, m.target) if m.public?
623 @channels[where].quiet = false if(@channels.has_key?(where))
626 # TODO break this out into a config module
627 when (/^options get sendq_delay$/i)
628 if auth.allow?("config", m.source, m.replyto)
629 m.reply "options->sendq_delay = #{@socket.sendq_delay}"
631 when (/^options get sendq_burst$/i)
632 if auth.allow?("config", m.source, m.replyto)
633 m.reply "options->sendq_burst = #{@socket.sendq_burst}"
635 when (/^options set sendq_burst (.*)$/i)
637 if auth.allow?("config", m.source, m.replyto)
638 @socket.sendq_burst = num
639 @config['irc.sendq_burst'] = num
642 when (/^options set sendq_delay (.*)$/i)
644 if auth.allow?("config", m.source, m.replyto)
645 @socket.sendq_delay = freq
646 @config['irc.sendq_delay'] = freq
650 m.reply status if auth.allow?("status", m.source, m.replyto)
651 when (/^registry stats$/i)
652 if auth.allow?("config", m.source, m.replyto)
653 m.reply @registry.stat.inspect
655 when (/^(version)|(introduce yourself)$/i)
656 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
657 when (/^help(?:\s+(.*))?$/i)
658 say m.replyto, help($1)
659 when (/^(botsnack|ciggie)$/i)
660 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
661 say m.replyto, @lang.get("thanks") if(m.private?)
662 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
663 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
664 say m.replyto, @lang.get("hello") if(m.private?)
669 # stuff to handle when not addressed
671 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))\s+#{@nick}$/i)
672 say m.replyto, @lang.get("hello_X") % m.sourcenick
673 when (/^#{@nick}!*$/)
674 say m.replyto, @lang.get("hello_X") % m.sourcenick
681 # log a message. Internal use only.
682 def log_sent(type, where, message)
686 log "-=#{@nick}=- #{message}", where
687 elsif (where =~ /(\S*)!.*/)
688 log "[-=#{where}=-] #{message}", $1
690 log "[-=#{where}=-] #{message}"
694 log "<#{@nick}> #{message}", where
695 elsif (where =~ /^(\S*)!.*$/)
696 log "[msg(#{where})] #{message}", $1
698 log "[msg(#{where})] #{message}", where
704 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
706 log "@ Joined channel #{m.channel}", m.channel
707 puts "joined channel #{m.channel}"
709 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
710 @channels[m.channel].users[m.sourcenick] = Hash.new
711 @channels[m.channel].users[m.sourcenick]["mode"] = ""
714 @plugins.delegate("listen", m)
715 @plugins.delegate("join", m)
720 log "@ Left channel #{m.channel} (#{m.message})", m.channel
721 @channels.delete(m.channel)
722 puts "left channel #{m.channel}"
724 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
725 @channels[m.channel].users.delete(m.sourcenick)
728 # delegate to plugins
729 @plugins.delegate("listen", m)
730 @plugins.delegate("part", m)
733 # respond to being kicked from a channel
736 @channels.delete(m.channel)
737 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
738 puts "kicked from channel #{m.channel}"
740 @channels[m.channel].users.delete(m.sourcenick)
741 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
744 @plugins.delegate("listen", m)
745 @plugins.delegate("kick", m)
749 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
750 @channels[m.channel].topic = m.topic if !m.topic.nil?
751 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
752 @channels[m.channel].topic.by = m.source if !m.source.nil?
754 debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
757 # delegate a privmsg to auth, keyword or plugin handlers
758 def delegate_privmsg(message)
759 [@auth, @plugins, @keywords].each {|m|
760 break if m.privmsg(message)