message.rb: fix message addressing logic
[rbot] / lib / rbot / message.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: IRC message datastructures
5
6 module Irc
7
8
9   class Bot
10     module Config
11       Config.register ArrayValue.new('core.address_prefix',
12         :default => [], :wizard => true,
13         :desc => "what non nick-matching prefixes should the bot respond to as if addressed (e.g !, so that '!foo' is treated like 'rbot: foo')"
14       )
15
16       Config.register BooleanValue.new('core.reply_with_nick',
17         :default => false, :wizard => true,
18         :desc => "if true, the bot will prepend the nick to what he has to say when replying (e.g. 'markey: you can't do that!')"
19       )
20
21       Config.register StringValue.new('core.nick_postfix',
22         :default => ':', :wizard => true,
23         :desc => "when replying with nick put this character after the nick of the user the bot is replying to"
24       )
25     end
26   end
27
28
29   # Define standard IRC attriubtes (not so standard actually,
30   # but the closest thing we have ...)
31   Bold = "\002"
32   Underline = "\037"
33   Reverse = "\026"
34   Italic = "\011"
35   NormalText = "\017"
36   AttributeRx = /#{Bold}|#{Underline}|#{Reverse}|#{Italic}|#{NormalText}/
37
38   # Color is prefixed by \003 and followed by optional
39   # foreground and background specifications, two-digits-max
40   # numbers separated by a comma. One of the two parts
41   # must be present.
42   Color = "\003"
43   ColorRx = /#{Color}\d?\d?(?:,\d\d?)?/
44
45   FormattingRx = /#{AttributeRx}|#{ColorRx}/
46
47   # Standard color codes
48   ColorCode = {
49     :black      => 1,
50     :blue       => 2,
51     :navyblue   => 2,
52     :navy_blue  => 2,
53     :green      => 3,
54     :red        => 4,
55     :brown      => 5,
56     :purple     => 6,
57     :olive      => 7,
58     :yellow     => 8,
59     :limegreen  => 9,
60     :lime_green => 9,
61     :teal       => 10,
62     :aqualight  => 11,
63     :aqua_light => 11,
64     :royal_blue => 12,
65     :hotpink    => 13,
66     :hot_pink   => 13,
67     :darkgray   => 14,
68     :dark_gray  => 14,
69     :lightgray  => 15,
70     :light_gray => 15,
71     :white      => 16
72   }
73
74   # Convert a String or Symbol into a color number
75   def Irc.find_color(data)
76     "%02d" % if Integer === data
77       data
78     else
79       f = if String === data
80             data.intern
81           else
82             data
83           end
84       if ColorCode.key?(f)
85         ColorCode[f] 
86       else
87         0
88       end
89     end
90   end
91
92   # Insert the full color code for a given
93   # foreground/background combination.
94   def Irc.color(fg=nil,bg=nil)
95     str = Color.dup
96     if fg
97      str << Irc.find_color(fg)
98     end
99     if bg
100       str << "," << Irc.find_color(bg)
101     end
102     return str
103   end
104
105   # base user message class, all user messages derive from this
106   # (a user message is defined as having a source hostmask, a target
107   # nick/channel and a message part)
108   class BasicUserMessage
109
110     # associated bot
111     attr_reader :bot
112
113     # associated server
114     attr_reader :server
115
116     # when the message was received
117     attr_reader :time
118
119     # User that originated the message
120     attr_reader :source
121
122     # User/Channel message was sent to
123     attr_reader :target
124
125     # contents of the message (stripped of initial/final format codes)
126     attr_accessor :message
127
128     # contents of the message (for logging purposes)
129     attr_accessor :logmessage
130
131     # contents of the message (stripped of all formatting)
132     attr_accessor :plainmessage
133
134     # has the message been replied to/handled by a plugin?
135     attr_accessor :replied
136     alias :replied? :replied
137
138     # should the message be ignored?
139     attr_accessor :ignored
140     alias :ignored? :ignored
141
142     # set this to true if the method that delegates the message is run in a thread
143     attr_accessor :in_thread
144     alias :in_thread? :in_thread
145
146     def inspect(fields=nil)
147       ret = self.__to_s__[0..-2]
148       ret << ' bot=' << @bot.__to_s__
149       ret << ' server=' << server.to_s
150       ret << ' time=' << time.to_s
151       ret << ' source=' << source.to_s
152       ret << ' target=' << target.to_s
153       ret << ' message=' << message.inspect
154       ret << ' logmessage=' << logmessage.inspect
155       ret << ' plainmessage=' << plainmessage.inspect
156       ret << fields if fields
157       ret << ' (identified)' if identified?
158       ret << ' (addressed to me)' if address?
159       ret << ' (replied)' if replied?
160       ret << ' (ignored)' if ignored?
161       ret << ' (in thread)' if in_thread?
162       ret << '>'
163     end
164
165     # instantiate a new Message
166     # bot::      associated bot class
167     # server::   Server where the message took place
168     # source::   User that sent the message
169     # target::   User/Channel is destined for
170     # message::  actual message
171     def initialize(bot, server, source, target, message)
172       @msg_wants_id = false unless defined? @msg_wants_id
173
174       @time = Time.now
175       @bot = bot
176       @source = source
177       @address = false
178       @target = target
179       @message = message || ""
180       @replied = false
181       @server = server
182       @ignored = false
183       @in_thread = false
184
185       @identified = false
186       if @msg_wants_id && @server.capabilities[:"identify-msg"]
187         if @message =~ /^([-+])(.*)/
188           @identified = ($1=="+")
189           @message = $2
190         else
191           warning "Message does not have identification"
192         end
193       end
194       @logmessage = @message.dup
195       @plainmessage = BasicUserMessage.strip_formatting(@message)
196       @message = BasicUserMessage.strip_initial_formatting(@message)
197
198       @address = true if source == @bot.myself
199
200     end
201
202     # Access the nick of the source
203     #
204     def sourcenick
205       @source.nick rescue @source.to_s
206     end
207
208     # Access the user@host of the source
209     #
210     def sourceaddress
211       "#{@source.user}@#{@source.host}" rescue @source.to_s
212     end
213
214     # Access the botuser corresponding to the source, if any
215     #
216     def botuser
217       source.botuser rescue @bot.auth.everyone
218     end
219
220
221     # Was the message from an identified user?
222     def identified?
223       return @identified
224     end
225
226     # returns true if the message was addressed to the bot.
227     # This includes any private message to the bot, or any public message
228     # which looks like it's addressed to the bot, e.g. "bot: foo", "bot, foo",
229     # a kick message when bot was kicked etc.
230     def address?
231       return @address
232     end
233
234     # strip mIRC colour escapes from a string
235     def BasicUserMessage.stripcolour(string)
236       return "" unless string
237       ret = string.gsub(ColorRx, "")
238       #ret.tr!("\x00-\x1f", "")
239       ret
240     end
241
242     def BasicUserMessage.strip_initial_formatting(string)
243       return "" unless string
244       ret = string.gsub(/^#{FormattingRx}|#{FormattingRx}$/,"")
245     end
246
247     def BasicUserMessage.strip_formatting(string)
248       string.gsub(FormattingRx,"")
249     end
250
251   end
252
253   # class for handling welcome messages from the server
254   class WelcomeMessage < BasicUserMessage
255   end
256
257   # class for handling MOTD from the server. Yes, MotdMessage
258   # is somewhat redundant, but it fits with the naming scheme
259   class MotdMessage < BasicUserMessage
260   end
261
262   # class for handling IRC user messages. Includes some utilities for handling
263   # the message, for example in plugins.
264   # The +message+ member will have any bot addressing "^bot: " removed
265   # (address? will return true in this case)
266   class UserMessage < BasicUserMessage
267
268     def inspect
269       fields = ' plugin=' << plugin.inspect
270       fields << ' params=' << params.inspect
271       fields << ' channel=' << channel.to_s if channel
272       fields << ' (reply to ' << replyto.to_s << ')'
273       if self.private?
274         fields << ' (private)'
275       else
276         fields << ' (public)'
277       end
278       if self.action?
279         fields << ' (action)'
280       elsif ctcp
281         fields << ' (CTCP ' << ctcp << ')'
282       end
283       super(fields)
284     end
285
286     # for plugin messages, the name of the plugin invoked by the message
287     attr_reader :plugin
288
289     # for plugin messages, the rest of the message, with the plugin name
290     # removed
291     attr_reader :params
292
293     # convenience member. Who to reply to (i.e. would be sourcenick for a
294     # privately addressed message, or target (the channel) for a publicly
295     # addressed message
296     attr_reader :replyto
297
298     # channel the message was in, nil for privately addressed messages
299     attr_reader :channel
300
301     # for PRIVMSGs, false unless the message was a CTCP command,
302     # in which case it evaluates to the CTCP command itself
303     # (TIME, PING, VERSION, etc). The CTCP command parameters
304     # are then stored in the message.
305     attr_reader :ctcp
306
307     # for PRIVMSGs, true if the message was a CTCP ACTION (CTCP stuff
308     # will be stripped from the message)
309     attr_reader :action
310
311     # instantiate a new UserMessage
312     # bot::      associated bot class
313     # source::   hostmask of the message source
314     # target::   nick/channel message is destined for
315     # message::  message part
316     def initialize(bot, server, source, target, message)
317       super(bot, server, source, target, message)
318       @target = target
319       @private = false
320       @plugin = nil
321       @ctcp = false
322       @action = false
323
324       if @address = (target == @bot.myself)
325         @private = true
326         @channel = nil
327         @replyto = source
328       else
329         @replyto = @target
330         @channel = @target
331       end
332
333       # check for option extra addressing prefixes, e.g "|search foo", or
334       # "!version" - first match wins
335       bot.config['core.address_prefix'].each {|mprefix|
336         if @message.gsub!(/^#{Regexp.escape(mprefix)}\s*/, "")
337           @address = true
338           break
339         end
340       }
341
342       # even if they used above prefixes, we allow for silly people who
343       # combine all possible types, e.g. "|rbot: hello", or
344       # "/msg rbot rbot: hello", etc
345       if @message.gsub!(/^\s*#{Regexp.escape(bot.nick)}\s*([:;,>]|\s)\s*/i, "")
346         @address = true
347       end
348
349       if(@message =~ /^\001(\S+)(\s(.+))?\001/)
350         @ctcp = $1
351         # FIXME need to support quoting of NULL and CR/LF, see
352         # http://www.irchelp.org/irchelp/rfc/ctcpspec.html
353         @message = $3 || String.new
354         @action = @ctcp == 'ACTION'
355         debug "Received CTCP command #{@ctcp} with options #{@message} (action? #{@action})"
356         @logmessage = @message.dup
357         @plainmessage = BasicUserMessage.strip_formatting(@message)
358         @message = BasicUserMessage.strip_initial_formatting(@message)
359       end
360
361       # free splitting for plugins
362       @params = @message.dup
363       # Created messges (such as by fake_message) can contain multiple lines
364       if @params.gsub!(/\A\s*(\S+)[\s$]*/m, "")
365         @plugin = $1.downcase
366         @params = nil unless @params.length > 0
367       end
368     end
369
370     # returns true for private messages, e.g. "/msg bot hello"
371     def private?
372       return @private
373     end
374
375     # returns true if the message was in a channel
376     def public?
377       return !@private
378     end
379
380     def action?
381       return @action
382     end
383
384     # convenience method to reply to a message, useful in plugins. It's the
385     # same as doing:
386     # <tt>@bot.say m.replyto, string</tt>
387     # So if the message is private, it will reply to the user. If it was
388     # in a channel, it will reply in the channel.
389     def plainreply(string, options={})
390       @bot.say @replyto, string, options
391       @replied = true
392     end
393
394     # Same as reply, but when replying in public it adds the nick of the user
395     # the bot is replying to
396     def nickreply(string, options={})
397       extra = self.public? ? "#{@source}#{@bot.config['core.nick_postfix']} " : ""
398       @bot.say @replyto, extra + string, options
399       @replied = true
400     end
401
402     # the default reply style is to nickreply unless the reply already contains
403     # the nick or core.reply_with_nick is set to false
404     #
405     def reply(string, options={})
406       if @bot.config['core.reply_with_nick'] and not string =~ /(?:^|\W)#{Regexp.escape(@source.to_s)}(?:$|\W)/
407         return nickreply(string, options)
408       end
409       plainreply(string, options)
410     end
411
412     # convenience method to reply to a message with an action. It's the
413     # same as doing:
414     # <tt>@bot.action m.replyto, string</tt>
415     # So if the message is private, it will reply to the user. If it was
416     # in a channel, it will reply in the channel.
417     def act(string, options={})
418       @bot.action @replyto, string, options
419       @replied = true
420     end
421
422     # send a CTCP response, i.e. a private NOTICE to the sender
423     # with the same CTCP command and the reply as a parameter
424     def ctcp_reply(string, options={})
425       @bot.ctcp_notice @source, @ctcp, string, options
426     end
427
428     # convenience method to reply "okay" in the current language to the
429     # message
430     def plainokay
431       self.plainreply @bot.lang.get("okay")
432     end
433
434     # Like the above, but append the username
435     def nickokay
436       str = @bot.lang.get("okay").dup
437       if self.public?
438         # remove final punctuation
439         str.gsub!(/[!,.]$/,"")
440         str += ", #{@source}"
441       end
442       self.plainreply str
443     end
444
445     # the default okay style is the same as the default reply style
446     #
447     def okay
448       if @bot.config['core.reply_with_nick']
449         return nickokay
450       end
451       plainokay
452     end
453
454     # send a NOTICE to the message source
455     #
456     def notify(msg,opts={})
457       @bot.notice(sourcenick, msg, opts)
458     end
459
460   end
461
462   # class to manage IRC PRIVMSGs
463   class PrivMessage < UserMessage
464     def initialize(bot, server, source, target, message, opts={})
465       @msg_wants_id = opts[:handle_id]
466       super(bot, server, source, target, message)
467     end
468   end
469
470   # class to manage IRC NOTICEs
471   class NoticeMessage < UserMessage
472     def initialize(bot, server, source, target, message, opts={})
473       @msg_wants_id = opts[:handle_id]
474       super(bot, server, source, target, message)
475     end
476   end
477
478   # class to manage IRC KICKs
479   # +address?+ can be used as a shortcut to see if the bot was kicked,
480   # basically, +target+ was kicked from +channel+ by +source+ with +message+
481   class KickMessage < BasicUserMessage
482     # channel user was kicked from
483     attr_reader :channel
484
485     def inspect
486       fields = ' channel=' << channel.to_s
487       super(fields)
488     end
489
490     def initialize(bot, server, source, target, channel, message="")
491       super(bot, server, source, target, message)
492       @channel = channel
493     end
494   end
495
496   # class to manage IRC INVITEs
497   # +address?+ can be used as a shortcut to see if the bot was invited,
498   # which should be true except for server bugs
499   class InviteMessage < BasicUserMessage
500     # channel user was invited to
501     attr_reader :channel
502
503     def inspect
504       fields = ' channel=' << channel.to_s
505       super(fields)
506     end
507
508     def initialize(bot, server, source, target, channel, message="")
509       super(bot, server, source, target, message)
510       @channel = channel
511     end
512   end
513
514   # class to pass IRC Nick changes in. @message contains the old nickame,
515   # @sourcenick contains the new one.
516   class NickMessage < BasicUserMessage
517     attr_accessor :is_on
518     def initialize(bot, server, source, oldnick, newnick)
519       super(bot, server, source, oldnick, newnick)
520       @is_on = []
521     end
522
523     def oldnick
524       return @target
525     end
526
527     def newnick
528       return @message
529     end
530
531     def inspect
532       fields = ' old=' << oldnick
533       fields << ' new=' << newnick
534       super(fields)
535     end
536   end
537
538   # class to manage mode changes
539   class ModeChangeMessage < BasicUserMessage
540     attr_accessor :modes
541     def initialize(bot, server, source, target, message="")
542       super(bot, server, source, target, message)
543       @modes = []
544     end
545
546     def inspect
547       fields = ' modes=' << modes.inspect
548       super(fields)
549     end
550   end
551
552   # class to manage WHOIS replies
553   class WhoisMessage < BasicUserMessage
554     attr_reader :whois
555     def initialize(bot, server, source, target, whois)
556       super(bot, server, source, target, "")
557       @whois = whois
558     end
559
560     def inspect
561       fields = ' whois=' << whois.inspect
562       super(fields)
563     end
564   end
565
566   # class to manage NAME replies
567   class NamesMessage < BasicUserMessage
568     attr_accessor :users
569     def initialize(bot, server, source, target, message="")
570       super(bot, server, source, target, message)
571       @users = []
572     end
573
574     def inspect
575       fields = ' users=' << users.inspect
576       super(fields)
577     end
578   end
579
580   class QuitMessage < BasicUserMessage
581     attr_accessor :was_on
582     def initialize(bot, server, source, target, message="")
583       super(bot, server, source, target, message)
584       @was_on = []
585     end
586   end
587
588   class TopicMessage < BasicUserMessage
589     # channel topic
590     attr_reader :topic
591     # topic set at (unixtime)
592     attr_reader :timestamp
593     # topic set on channel
594     attr_reader :channel
595
596     # :info if topic info, :set if topic set
597     attr_accessor :info_or_set
598     def initialize(bot, server, source, channel, topic=ChannelTopic.new)
599       super(bot, server, source, channel, topic.text)
600       @topic = topic
601       @timestamp = topic.set_on
602       @channel = channel
603       @info_or_set = nil
604     end
605
606     def inspect
607       fields = ' topic=' << topic
608       fields << ' (set on ' << timestamp << ')'
609       super(fields)
610     end
611   end
612
613   # class to manage channel joins
614   class JoinMessage < BasicUserMessage
615     # channel joined
616     attr_reader :channel
617
618     def inspect
619       fields = ' channel=' << channel.to_s
620       super(fields)
621     end
622
623     def initialize(bot, server, source, channel, message="")
624       super(bot, server, source, channel, message)
625       @channel = channel
626       # in this case sourcenick is the nick that could be the bot
627     end
628   end
629
630   # class to manage channel parts
631   # same as a join, but can have a message too
632   class PartMessage < JoinMessage
633   end
634
635   class UnknownMessage < BasicUserMessage
636   end
637 end