note: if is more readale than unless here
[rbot] / data / rbot / plugins / note.rb
1 #++
2 #
3 # :title: Note plugin for rbot
4 #
5 # Author:: dmitry kim <dmitry dot kim at gmail dot com>
6 #
7 # Copyright:: (C) 200?-2009 dmitry 'jsn' kim
8 #
9 # License:: MIT license
10
11 class NotePlugin < Plugin
12
13   Note = Struct.new('Note', :time, :from, :private, :text)
14
15   Config.register Config::BooleanValue.new 'note.private_message',
16     :default => false,
17     :desc => 'Send all notes in private messages instead of channel messages.'
18
19   def initialize
20     super
21     return if @registry.length < 1
22     debug 'Checking registry for old-formatted notes...'
23     n = 0
24     @registry.dup.each_key do |key|
25       unless key == key.downcase
26         @registry[key.downcase] = @registry[key] + (@registry[key.downcase] || [])
27         @registry.delete key
28         n += 1
29       end
30     end
31     debug "#{n} entries converted and merged."
32   end
33
34   def help(plugin, topic='')
35     'note <nick> <string> => stores a note (<string>) for <nick>'
36   end
37
38   def message(m)
39     begin
40       nick = m.sourcenick.downcase
41       # Keys are case insensitive to avoid storing a message
42       # for <person> instead of <Person> or visa-versa.
43       return unless @registry.has_key? nick
44       pub = []
45       priv = []
46       @registry[nick].each do |n|
47         s = "[#{n.time.strftime('%b-%e %H:%M')}] <#{n.from}> #{n.text}"
48         if n.private or @bot.config['note.private_message']
49           priv << s
50         else
51           pub << s
52         end
53       end
54       unless pub.empty?
55         @bot.say m.replyto, "#{m.sourcenick}, you have notes! " +
56           pub.join(' ')
57       end
58       unless priv.empty?
59         @bot.say m.sourcenick, 'you have notes! ' + priv.join(' ')
60       end
61       @registry.delete nick
62     rescue Exception => e
63       m.reply e.message
64     end
65   end
66
67   def note(m, params)
68     begin
69       nick = params[:nick].downcase
70       q = @registry[nick] || Array.new
71       s = params[:string].to_s.strip
72       raise 'cowardly discarding the empty note' if s.empty?
73       q.push Note.new(Time.now, m.sourcenick, m.private?, s)
74       @registry[nick] = q
75       m.okay
76     rescue Exception => e
77       m.reply "error: #{e.message}"
78     end
79   end
80 end
81
82 NotePlugin.new.map 'note :nick *string'