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'
40 # Main bot class, which receives messages, handles them or passes them to
41 # plugins, and stores runtime data
43 # the bot's current nickname
46 # the bot's IrcAuth data
49 # the bot's BotConfig data
52 # the botclass for this bot (determines configdir among other things)
55 # used to perform actions periodically (saves configuration once per minute
62 # bot's configured addressing prefixes
63 attr_reader :addressing_prefixes
65 # channel info for channels the bot is in
68 # bot's object registry, plugins get an interface to this for persistant
69 # storage (hash interface tied to a bdb file, plugins use Accessors to store
70 # and restore objects in their own namespaces.)
73 # create a new IrcBot with botclass +botclass+
74 def initialize(botclass)
75 @botclass = botclass.gsub(/\/$/, "")
76 @startup_time = Time.new
78 Dir.mkdir("#{botclass}") if(!File.exist?("#{botclass}"))
79 Dir.mkdir("#{botclass}/logs") if(!File.exist?("#{botclass}/logs"))
81 @config = Irc::BotConfig.new(self)
82 @timer = Timer::Timer.new
83 @registry = BotRegistry.new self
84 @timer.add(@config["SAVE_EVERY"].to_i) { save }
88 @lang = Irc::Language.new(@config["LANGUAGE"])
89 @keywords = Irc::Keywords.new(self)
90 @auth = Irc::IrcAuth.new(self)
91 @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
92 @socket = Irc::IrcSocket.new(@config["SERVER"], @config["PORT"], @config["HOST"], @config["SENDQ_DELAY"], @config["SENDQ_BURST"])
93 @nick = @config["NICK"]
94 @server_password = @config["SERVER_PASSWORD"]
95 if @config["ADDRESS_PREFIX"]
96 @addressing_prefixes = @config["ADDRESS_PREFIX"].split(" ")
98 @addressing_prefixes = Array.new
101 @client = Irc::IrcClient.new
102 @client["PRIVMSG"] = proc { |data|
103 message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
106 @client["NOTICE"] = proc { |data|
107 message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
108 # pass it off to plugins that want to hear everything
109 @plugins.delegate "listen", message
111 @client["MOTD"] = proc { |data|
112 data['MOTD'].each_line { |line|
113 log "MOTD: #{line}", "server"
116 @client["NICKTAKEN"] = proc { |data|
119 @client["BADNICK"] = proc {|data|
120 puts "WARNING, bad nick (#{data['NICK']})"
122 @client["PING"] = proc {|data|
123 # (jump the queue for pongs)
124 @socket.puts "PONG #{data['PINGID']}"
126 @client["NICK"] = proc {|data|
127 sourcenick = data["SOURCENICK"]
129 m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"])
130 if(sourcenick == @nick)
133 @channels.each {|k,v|
134 if(v.users.has_key?(sourcenick))
135 log "@ #{sourcenick} is now known as #{nick}", k
136 v.users[nick] = v.users[sourcenick]
137 v.users.delete(sourcenick)
140 @plugins.delegate("listen", m)
141 @plugins.delegate("nick", m)
143 @client["QUIT"] = proc {|data|
144 source = data["SOURCE"]
145 sourcenick = data["SOURCENICK"]
146 sourceurl = data["SOURCEADDRESS"]
147 message = data["MESSAGE"]
148 m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"])
149 if(data["SOURCENICK"] =~ /#{@nick}/i)
151 @channels.each {|k,v|
152 if(v.users.has_key?(sourcenick))
153 log "@ Quit: #{sourcenick}: #{message}", k
154 v.users.delete(sourcenick)
158 @plugins.delegate("listen", m)
159 @plugins.delegate("quit", m)
161 @client["MODE"] = proc {|data|
162 source = data["SOURCE"]
163 sourcenick = data["SOURCENICK"]
164 sourceurl = data["SOURCEADDRESS"]
165 channel = data["CHANNEL"]
166 targets = data["TARGETS"]
167 modestring = data["MODESTRING"]
168 log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
170 @client["WELCOME"] = proc {|data|
171 log "joined server #{data['SOURCE']} as #{data['NICK']}", "server"
172 debug "I think my nick is #{@nick}, server thinks #{data['NICK']}"
173 if data['NICK'] && data['NICK'].length > 0
177 puts "authing with Q using #{@config["QUSER"]} #{@config["QAUTH"]}"
178 @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config["QUSER"]} #{@config["QAUTH"]}"
181 if(@config["JOIN_CHANNELS"])
182 @config["JOIN_CHANNELS"].split(", ").each {|c|
183 puts "autojoining channel #{c}"
184 if(c =~ /^(\S+)\s+(\S+)$/i)
192 @client["JOIN"] = proc {|data|
193 m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
196 @client["PART"] = proc {|data|
197 m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
200 @client["KICK"] = proc {|data|
201 m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"])
204 @client["INVITE"] = proc {|data|
205 if(data["TARGET"] =~ /^#{@nick}$/i)
206 join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"]))
209 @client["CHANGETOPIC"] = proc {|data|
210 channel = data["CHANNEL"]
211 sourcenick = data["SOURCENICK"]
212 topic = data["TOPIC"]
213 timestamp = data["UNIXTIME"] || Time.now.to_i
214 if(sourcenick == @nick)
215 log "@ I set topic \"#{topic}\"", channel
217 log "@ #{sourcenick} set topic \"#{topic}\"", channel
219 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"])
222 @plugins.delegate("topic", m)
223 @plugins.delegate("listen", m)
225 @client["TOPIC"] = @client["TOPICINFO"] = proc {|data|
226 channel = data["CHANNEL"]
227 m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"])
230 @client["NAMES"] = proc {|data|
231 channel = data["CHANNEL"]
232 users = data["USERS"]
233 unless(@channels[channel])
234 puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
237 @channels[channel].users.clear
239 @channels[channel].users[u[0]] = ["mode", u[1]]
242 @client["UNKNOWN"] = proc {|data|
243 debug "UNKNOWN: #{data['SERVERSTRING']}"
247 # connect the bot to IRC
249 trap("SIGTERM") { quit }
250 trap("SIGHUP") { quit }
251 trap("SIGINT") { quit }
255 raise "failed to connect to IRC server at #{@config['SERVER']} #{@config['PORT']}: " + e
257 @socket.puts "PASS " + @server_password if @server_password
258 @socket.puts "NICK #{@nick}\nUSER #{@config['USER']} 4 #{@config['SERVER']} :Ruby bot. (c) Tom Gilbert"
261 # begin event handling loop
271 if @socket.select socket_timeout
272 break unless reply = @socket.gets
273 @client.process reply
278 puts "connection closed: #{e}"
279 puts e.backtrace.join("\n")
286 puts "waiting to reconnect"
291 # type:: message type
292 # where:: message target
293 # message:: message text
294 # send message +message+ of type +type+ to target +where+
295 # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
296 # relevant say() or notice() methods. This one should be used for IRCd
297 # extensions you want to use in modules.
298 def sendmsg(type, where, message)
299 # limit it 440 chars + CRLF.. so we have to split long lines
300 left = 440 - type.length - where.length - 3
302 if(left >= message.length)
303 sendq("#{type} #{where} :#{message}")
304 log_sent(type, where, message)
307 line = message.slice!(0, left)
308 lastspace = line.rindex(/\s+/)
310 message = line.slice!(lastspace, line.length) + message
311 message.gsub!(/^\s+/, "")
313 sendq("#{type} #{where} :#{line}")
314 log_sent(type, where, line)
315 end while(message.length > 0)
318 def sendq(message="")
320 @socket.queue(message)
323 # send a notice message to channel/nick +where+
324 def notice(where, message)
325 message.each_line { |line|
327 next unless(line.length > 0)
328 sendmsg("NOTICE", where, line)
332 # say something (PRIVMSG) to channel/nick +where+
333 def say(where, message)
334 message.to_s.each_line { |line|
336 next unless(line.length > 0)
337 unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
338 sendmsg("PRIVMSG", where, line)
343 # perform a CTCP action with message +message+ to channel/nick +where+
344 def action(where, message)
345 sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
347 log "* #{@nick} #{message}", where
348 elsif (where =~ /^(\S*)!.*$/)
349 log "* #{@nick}[#{where}] #{message}", $1
351 log "* #{@nick}[#{where}] #{message}", where
355 # quick way to say "okay" (or equivalent) to +where+
357 say where, @lang.get("okay")
360 # log message +message+ to a file determined by +where+. +where+ can be a
361 # channel name, or a nick for private message logging
362 def log(message, where="server")
364 stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
365 unless(@logs.has_key?(where))
366 @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
367 @logs[where].sync = true
369 @logs[where].puts "[#{stamp}] #{message}"
370 #debug "[#{stamp}] <#{where}> #{message}"
373 # set topic of channel +where+ to +topic+
374 def topic(where, topic)
375 sendq "TOPIC #{where} :#{topic}"
378 # message:: optional IRC quit message
379 # quit IRC, shutdown the bot
380 def quit(message=nil)
381 trap("SIGTERM", "DEFAULT")
382 trap("SIGHUP", "DEFAULT")
383 trap("SIGINT", "DEFAULT")
384 message = @lang.get("quit") if (!message || message.length < 1)
388 @channels.each_value {|v|
389 log "@ quit (#{message})", v.name
391 @socket.puts "QUIT :#{message}"
395 puts "rbot quit (#{message})"
399 # call the save method for bot's config, keywords, auth and all plugins
408 # call the rescan method for the bot's lang, keywords and all plugins
415 # channel:: channel to join
416 # key:: optional channel key if channel is +s
418 def join(channel, key=nil)
420 sendq "JOIN #{channel} :#{key}"
422 sendq "JOIN #{channel}"
427 def part(channel, message="")
428 sendq "PART #{channel} :#{message}"
431 # attempt to change bot's nick to +name+
436 # m:: message asking for help
437 # topic:: optional topic help is requested for
438 # respond to online help requests
440 topic = nil if topic == ""
443 helpstr = "help topics: core, auth, keywords"
444 helpstr += @plugins.helptopics
445 helpstr += " (help <topic> for more info)"
448 when /^core\s+(.+)$/i
449 helpstr = corehelp $1
452 when /^auth\s+(.+)$/i
453 helpstr = @auth.help $1
455 helpstr = @keywords.help
456 when /^keywords\s+(.+)$/i
457 helpstr = @keywords.help $1
459 unless(helpstr = @plugins.help(topic))
460 helpstr = "no help for topic #{topic}"
468 # handle help requests for "core" topics
469 def corehelp(topic="")
472 return "quit [<message>] => quit IRC with message <message>"
474 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"
476 return "part <channel> => part channel <channel>"
478 return "hide => part all channels"
480 return "save => save current dynamic data and configuration"
482 return "rescan => reload modules and static facts"
484 return "nick <nick> => attempt to change nick to <nick>"
486 return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
488 return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
490 return "topic <channel> <message> => set topic of <channel> to <message>"
492 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>"
494 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>"
496 return "version => describes software version"
498 return "botsnack => reward #{@nick} for being good"
500 return "hello|hi|hey|yo [#{@nick}] => greet the bot"
502 return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
506 # handle incoming IRC PRIVMSG +m+
511 log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
513 log "* #{m.sourcenick} #{m.message}", m.target
517 log "<#{m.sourcenick}> #{m.message}", m.target
519 log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
523 # pass it off to plugins that want to hear everything
524 @plugins.delegate "listen", m
526 if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
527 notice m.sourcenick, "\001PING #$1\001"
528 log "@ #{m.sourcenick} pinged me"
534 when (/^join\s+(\S+)\s+(\S+)$/i)
535 join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
536 when (/^join\s+(\S+)$/i)
537 join $1 if(@auth.allow?("join", m.source, m.replyto))
539 part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
540 when (/^part\s+(\S+)$/i)
541 part $1 if(@auth.allow?("join", m.source, m.replyto))
542 when (/^quit(?:\s+(.*))?$/i)
543 quit $1 if(@auth.allow?("quit", m.source, m.replyto))
545 join 0 if(@auth.allow?("join", m.source, m.replyto))
547 if(@auth.allow?("config", m.source, m.replyto))
551 when (/^nick\s+(\S+)$/i)
552 nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
553 when (/^say\s+(\S+)\s+(.*)$/i)
554 say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
555 when (/^action\s+(\S+)\s+(.*)$/i)
556 action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
557 when (/^topic\s+(\S+)\s+(.*)$/i)
558 topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
560 say m.replyto, "pong"
562 if(@auth.allow?("config", m.source, m.replyto))
567 if(auth.allow?("talk", m.source, m.replyto))
568 say m.replyto, @lang.get("okay")
569 @channels.each_value {|c| c.quiet = true }
571 when (/^quiet in (\S+)$/i)
573 if(auth.allow?("talk", m.source, m.replyto))
574 say m.replyto, @lang.get("okay")
575 where.gsub!(/^here$/, m.target) if m.public?
576 @channels[where].quiet = true if(@channels.has_key?(where))
579 if(auth.allow?("talk", m.source, m.replyto))
580 @channels.each_value {|c| c.quiet = false }
583 when (/^talk in (\S+)$/i)
585 if(auth.allow?("talk", m.source, m.replyto))
586 where.gsub!(/^here$/, m.target) if m.public?
587 @channels[where].quiet = false if(@channels.has_key?(where))
590 # TODO break this out into an options module
591 when (/^options get sendq_delay$/i)
592 if auth.allow?("config", m.source, m.replyto)
593 m.reply "options->sendq_delay = #{@socket.get_sendq}"
595 when (/^options get sendq_burst$/i)
596 if auth.allow?("config", m.source, m.replyto)
597 m.reply "options->sendq_burst = #{@socket.get_maxburst}"
599 when (/^options set sendq_burst (.*)$/i)
601 if auth.allow?("config", m.source, m.replyto)
602 @socket.set_maxburst(num)
603 @config["SENDQ_BURST"] = num
606 when (/^options set sendq_delay (.*)$/i)
608 if auth.allow?("config", m.source, m.replyto)
609 @socket.set_sendq(freq)
610 @config["SENDQ_DELAY"] = freq
614 m.reply status if auth.allow?("status", m.source, m.replyto)
615 when (/^registry stats$/i)
616 if auth.allow?("config", m.source, m.replyto)
617 m.reply @registry.stat.inspect
619 when (/^(version)|(introduce yourself)$/i)
620 say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
621 when (/^help(?:\s+(.*))?$/i)
622 say m.replyto, help($1)
623 when (/^(botsnack|ciggie)$/i)
624 say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
625 say m.replyto, @lang.get("thanks") if(m.private?)
626 when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
627 say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
628 say m.replyto, @lang.get("hello") if(m.private?)
633 # stuff to handle when not addressed
635 when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))\s+#{@nick}$/i)
636 say m.replyto, @lang.get("hello_X") % m.sourcenick
637 when (/^#{@nick}!*$/)
638 say m.replyto, @lang.get("hello_X") % m.sourcenick
645 # log a message. Internal use only.
646 def log_sent(type, where, message)
650 log "-=#{@nick}=- #{message}", where
651 elsif (where =~ /(\S*)!.*/)
652 log "[-=#{where}=-] #{message}", $1
654 log "[-=#{where}=-] #{message}"
658 log "<#{@nick}> #{message}", where
659 elsif (where =~ /^(\S*)!.*$/)
660 log "[msg(#{where})] #{message}", $1
662 log "[msg(#{where})] #{message}", where
668 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
670 log "@ Joined channel #{m.channel}", m.channel
671 puts "joined channel #{m.channel}"
673 log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
674 @channels[m.channel].users[m.sourcenick] = Hash.new
675 @channels[m.channel].users[m.sourcenick]["mode"] = ""
678 @plugins.delegate("listen", m)
679 @plugins.delegate("join", m)
684 log "@ Left channel #{m.channel} (#{m.message})", m.channel
685 @channels.delete(m.channel)
686 puts "left channel #{m.channel}"
688 log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
689 @channels[m.channel].users.delete(m.sourcenick)
692 # delegate to plugins
693 @plugins.delegate("listen", m)
694 @plugins.delegate("part", m)
697 # respond to being kicked from a channel
700 @channels.delete(m.channel)
701 log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
702 puts "kicked from channel #{m.channel}"
704 @channels[m.channel].users.delete(m.sourcenick)
705 log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
708 @plugins.delegate("listen", m)
709 @plugins.delegate("kick", m)
713 @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
714 @channels[m.channel].topic = m.topic if !m.topic.nil?
715 @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
716 @channels[m.channel].topic.by = m.source if !m.source.nil?
718 puts @channels[m.channel].topic
722 secs_up = Time.new - @startup_time
723 uptime = Utils.secs_to_string secs_up
724 return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
727 # delegate a privmsg to auth, keyword or plugin handlers
728 def delegate_privmsg(message)
729 [@auth, @plugins, @keywords].each {|m|
730 break if m.privmsg(message)