]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/message.rb
5d6ea60f28e10c89d07e42163407c92e3bd7845e
[user/henk/code/ruby/rbot.git] / 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       if target && target == @bot.myself
199         @address = true
200       end
201
202     end
203
204     # Access the nick of the source
205     #
206     def sourcenick
207       @source.nick rescue @source.to_s
208     end
209
210     # Access the user@host of the source
211     #
212     def sourceaddress
213       "#{@source.user}@#{@source.host}" rescue @source.to_s
214     end
215
216     # Access the botuser corresponding to the source, if any
217     #
218     def botuser
219       source.botuser rescue @bot.auth.everyone
220     end
221
222
223     # Was the message from an identified user?
224     def identified?
225       return @identified
226     end
227
228     # returns true if the message was addressed to the bot.
229     # This includes any private message to the bot, or any public message
230     # which looks like it's addressed to the bot, e.g. "bot: foo", "bot, foo",
231     # a kick message when bot was kicked etc.
232     def address?
233       return @address
234     end
235
236     # strip mIRC colour escapes from a string
237     def BasicUserMessage.stripcolour(string)
238       return "" unless string
239       ret = string.gsub(ColorRx, "")
240       #ret.tr!("\x00-\x1f", "")
241       ret
242     end
243
244     def BasicUserMessage.strip_initial_formatting(string)
245       return "" unless string
246       ret = string.gsub(/^#{FormattingRx}|#{FormattingRx}$/,"")
247     end
248
249     def BasicUserMessage.strip_formatting(string)
250       string.gsub(FormattingRx,"")
251     end
252
253   end
254
255   # class for handling welcome messages from the server
256   class WelcomeMessage < BasicUserMessage
257   end
258
259   # class for handling MOTD from the server. Yes, MotdMessage
260   # is somewhat redundant, but it fits with the naming scheme
261   class MotdMessage < BasicUserMessage
262   end
263
264   # class for handling IRC user messages. Includes some utilities for handling
265   # the message, for example in plugins.
266   # The +message+ member will have any bot addressing "^bot: " removed
267   # (address? will return true in this case)
268   class UserMessage < BasicUserMessage
269
270     def inspect
271       fields = ' plugin=' << plugin.inspect
272       fields << ' params=' << params.inspect
273       fields << ' channel=' << channel.to_s if channel
274       fields << ' (reply to ' << replyto.to_s << ')'
275       if self.private?
276         fields << ' (private)'
277       else
278         fields << ' (public)'
279       end
280       if self.action?
281         fields << ' (action)'
282       elsif ctcp
283         fields << ' (CTCP ' << ctcp << ')'
284       end
285       super(fields)
286     end
287
288     # for plugin messages, the name of the plugin invoked by the message
289     attr_reader :plugin
290
291     # for plugin messages, the rest of the message, with the plugin name
292     # removed
293     attr_reader :params
294
295     # convenience member. Who to reply to (i.e. would be sourcenick for a
296     # privately addressed message, or target (the channel) for a publicly
297     # addressed message
298     attr_reader :replyto
299
300     # channel the message was in, nil for privately addressed messages
301     attr_reader :channel
302
303     # for PRIVMSGs, false unless the message was a CTCP command,
304     # in which case it evaluates to the CTCP command itself
305     # (TIME, PING, VERSION, etc). The CTCP command parameters
306     # are then stored in the message.
307     attr_reader :ctcp
308
309     # for PRIVMSGs, true if the message was a CTCP ACTION (CTCP stuff
310     # will be stripped from the message)
311     attr_reader :action
312
313     # instantiate a new UserMessage
314     # bot::      associated bot class
315     # source::   hostmask of the message source
316     # target::   nick/channel message is destined for
317     # message::  message part
318     def initialize(bot, server, source, target, message)
319       super(bot, server, source, target, message)
320       @target = target
321       @private = false
322       @plugin = nil
323       @ctcp = false
324       @action = false
325
326       if target == @bot.myself
327         @private = true
328         @address = true
329         @channel = nil
330         @replyto = source
331       else
332         @replyto = @target
333         @channel = @target
334       end
335
336       # check for option extra addressing prefixes, e.g "|search foo", or
337       # "!version" - first match wins
338       bot.config['core.address_prefix'].each {|mprefix|
339         if @message.gsub!(/^#{Regexp.escape(mprefix)}\s*/, "")
340           @address = true
341           break
342         end
343       }
344
345       # even if they used above prefixes, we allow for silly people who
346       # combine all possible types, e.g. "|rbot: hello", or
347       # "/msg rbot rbot: hello", etc
348       if @message.gsub!(/^\s*#{Regexp.escape(bot.nick)}\s*([:;,>]|\s)\s*/i, "")
349         @address = true
350       end
351
352       if(@message =~ /^\001(\S+)(\s(.+))?\001/)
353         @ctcp = $1
354         # FIXME need to support quoting of NULL and CR/LF, see
355         # http://www.irchelp.org/irchelp/rfc/ctcpspec.html
356         @message = $3 || String.new
357         @action = @ctcp == 'ACTION'
358         debug "Received CTCP command #{@ctcp} with options #{@message} (action? #{@action})"
359         @logmessage = @message.dup
360         @plainmessage = BasicUserMessage.strip_formatting(@message)
361         @message = BasicUserMessage.strip_initial_formatting(@message)
362       end
363
364       # free splitting for plugins
365       @params = @message.dup
366       # Created messges (such as by fake_message) can contain multiple lines
367       if @params.gsub!(/\A\s*(\S+)[\s$]*/m, "")
368         @plugin = $1.downcase
369         @params = nil unless @params.length > 0
370       end
371     end
372
373     # returns true for private messages, e.g. "/msg bot hello"
374     def private?
375       return @private
376     end
377
378     # returns true if the message was in a channel
379     def public?
380       return !@private
381     end
382
383     def action?
384       return @action
385     end
386
387     # convenience method to reply to a message, useful in plugins. It's the
388     # same as doing:
389     # <tt>@bot.say m.replyto, string</tt>
390     # So if the message is private, it will reply to the user. If it was
391     # in a channel, it will reply in the channel.
392     def plainreply(string, options={})
393       @bot.say @replyto, string, options
394       @replied = true
395     end
396
397     # Same as reply, but when replying in public it adds the nick of the user
398     # the bot is replying to
399     def nickreply(string, options={})
400       extra = self.public? ? "#{@source}#{@bot.config['core.nick_postfix']} " : ""
401       @bot.say @replyto, extra + string, options
402       @replied = true
403     end
404
405     # the default reply style is to nickreply unless the reply already contains
406     # the nick or core.reply_with_nick is set to false
407     #
408     def reply(string, options={})
409       if @bot.config['core.reply_with_nick'] and not string =~ /(?:^|\W)#{Regexp.escape(@source.to_s)}(?:$|\W)/
410         return nickreply(string, options)
411       end
412       plainreply(string, options)
413     end
414
415     # convenience method to reply to a message with an action. It's the
416     # same as doing:
417     # <tt>@bot.action m.replyto, string</tt>
418     # So if the message is private, it will reply to the user. If it was
419     # in a channel, it will reply in the channel.
420     def act(string, options={})
421       @bot.action @replyto, string, options
422       @replied = true
423     end
424
425     # send a CTCP response, i.e. a private NOTICE to the sender
426     # with the same CTCP command and the reply as a parameter
427     def ctcp_reply(string, options={})
428       @bot.ctcp_notice @source, @ctcp, string, options
429     end
430
431     # convenience method to reply "okay" in the current language to the
432     # message
433     def plainokay
434       self.plainreply @bot.lang.get("okay")
435     end
436
437     # Like the above, but append the username
438     def nickokay
439       str = @bot.lang.get("okay").dup
440       if self.public?
441         # remove final punctuation
442         str.gsub!(/[!,.]$/,"")
443         str += ", #{@source}"
444       end
445       self.plainreply str
446     end
447
448     # the default okay style is the same as the default reply style
449     #
450     def okay
451       if @bot.config['core.reply_with_nick']
452         return nickokay
453       end
454       plainokay
455     end
456
457     # send a NOTICE to the message source
458     #
459     def notify(msg,opts={})
460       @bot.notice(sourcenick, msg, opts)
461     end
462
463   end
464
465   # class to manage IRC PRIVMSGs
466   class PrivMessage < UserMessage
467     def initialize(bot, server, source, target, message, opts={})
468       @msg_wants_id = opts[:handle_id]
469       super(bot, server, source, target, message)
470     end
471   end
472
473   # class to manage IRC NOTICEs
474   class NoticeMessage < UserMessage
475     def initialize(bot, server, source, target, message, opts={})
476       @msg_wants_id = opts[:handle_id]
477       super(bot, server, source, target, message)
478     end
479   end
480
481   # class to manage IRC KICKs
482   # +address?+ can be used as a shortcut to see if the bot was kicked,
483   # basically, +target+ was kicked from +channel+ by +source+ with +message+
484   class KickMessage < BasicUserMessage
485     # channel user was kicked from
486     attr_reader :channel
487
488     def inspect
489       fields = ' channel=' << channel.to_s
490       super(fields)
491     end
492
493     def initialize(bot, server, source, target, channel, message="")
494       super(bot, server, source, target, message)
495       @channel = channel
496     end
497   end
498
499   # class to manage IRC INVITEs
500   # +address?+ can be used as a shortcut to see if the bot was invited,
501   # which should be true except for server bugs
502   class InviteMessage < BasicUserMessage
503     # channel user was invited to
504     attr_reader :channel
505
506     def inspect
507       fields = ' channel=' << channel.to_s
508       super(fields)
509     end
510
511     def initialize(bot, server, source, target, channel, message="")
512       super(bot, server, source, target, message)
513       @channel = channel
514     end
515   end
516
517   # class to pass IRC Nick changes in. @message contains the old nickame,
518   # @sourcenick contains the new one.
519   class NickMessage < BasicUserMessage
520     attr_accessor :is_on
521     def initialize(bot, server, source, oldnick, newnick)
522       super(bot, server, source, oldnick, newnick)
523       @is_on = []
524     end
525
526     def oldnick
527       return @target
528     end
529
530     def newnick
531       return @message
532     end
533
534     def inspect
535       fields = ' old=' << oldnick
536       fields << ' new=' << newnick
537       super(fields)
538     end
539   end
540
541   # class to manage mode changes
542   class ModeChangeMessage < BasicUserMessage
543     attr_accessor :modes
544     def initialize(bot, server, source, target, message="")
545       super(bot, server, source, target, message)
546       @address = (source == @bot.myself)
547       @modes = []
548     end
549
550     def inspect
551       fields = ' modes=' << modes.inspect
552       super(fields)
553     end
554   end
555
556   # class to manage NAME replies
557   class NamesMessage < BasicUserMessage
558     attr_accessor :users
559     def initialize(bot, server, source, target, message="")
560       super(bot, server, source, target, message)
561       @users = []
562     end
563
564     def inspect
565       fields = ' users=' << users.inspect
566       super(fields)
567     end
568   end
569
570   class QuitMessage < BasicUserMessage
571     attr_accessor :was_on
572     def initialize(bot, server, source, target, message="")
573       super(bot, server, source, target, message)
574       @was_on = []
575     end
576   end
577
578   class TopicMessage < BasicUserMessage
579     # channel topic
580     attr_reader :topic
581     # topic set at (unixtime)
582     attr_reader :timestamp
583     # topic set on channel
584     attr_reader :channel
585
586     # :info if topic info, :set if topic set
587     attr_accessor :info_or_set
588     def initialize(bot, server, source, channel, topic=ChannelTopic.new)
589       super(bot, server, source, channel, topic.text)
590       @topic = topic
591       @timestamp = topic.set_on
592       @channel = channel
593       @info_or_set = nil
594     end
595
596     def inspect
597       fields = ' topic=' << topic
598       fields << ' (set on ' << timestamp << ')'
599       super(fields)
600     end
601   end
602
603   # class to manage channel joins
604   class JoinMessage < BasicUserMessage
605     # channel joined
606     attr_reader :channel
607
608     def inspect
609       fields = ' channel=' << channel.to_s
610       super(fields)
611     end
612
613     def initialize(bot, server, source, channel, message="")
614       super(bot, server, source, channel, message)
615       @channel = channel
616       # in this case sourcenick is the nick that could be the bot
617       @address = (source == @bot.myself)
618     end
619   end
620
621   # class to manage channel parts
622   # same as a join, but can have a message too
623   class PartMessage < JoinMessage
624   end
625
626   class UnknownMessage < BasicUserMessage
627   end
628 end