note: skip merging nil keys
[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   def initialize
16     super
17     return if @registry.length < 1
18     debug 'Checking registry for old-formatted notes...'
19     n = 0
20     @registry.dup.each_key do |key|
21       unless key == key.downcase
22         @registry[key.downcase] = @registry[key] + (@registry[key.downcase] || [])
23         @registry.delete key
24         n += 1
25       end
26     end
27     debug "#{n} entries converted and merged."
28   end
29
30   def help(plugin, topic='')
31     'note <nick> <string> => stores a note (<string>) for <nick>'
32   end
33
34   def message(m)
35     begin
36       nick = m.sourcenick.downcase
37       # Keys are case insensitive to avoid storing a message
38       # for <person> instead of <Person> or visa-versa.
39       return unless @registry.has_key? nick
40       pub = []
41       priv = []
42       @registry[nick].each do |n|
43         s = "[#{n.time.strftime('%H:%M')}] <#{n.from}> #{n.text}"
44         (n.private ? priv : pub).push s
45       end
46       if !pub.empty?
47         @bot.say m.replyto, "#{m.sourcenick}, you have notes! " +
48           pub.join(' ')
49       end
50
51       if !priv.empty?
52         @bot.say m.sourcenick, 'you have notes! ' + priv.join(' ')
53       end
54       @registry.delete nick
55     rescue Exception => e
56       m.reply e.message
57     end
58   end
59
60   def note(m, params)
61     begin
62       nick = params[:nick].downcase
63       q = @registry[nick] || Array.new
64       s = params[:string].to_s.strip
65       raise 'cowardly discarding the empty note' if s.empty?
66       q.push Note.new(Time.now, m.sourcenick, m.private?, s)
67       @registry[nick] = q
68       m.okay
69     rescue Exception => e
70       m.reply "error: #{e.message}"
71     end
72   end
73 end
74
75 NotePlugin.new.map 'note :nick *string'