nickrecover plugin: work more than once per session
[rbot] / data / rbot / plugins / nickrecover.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Nick recovery
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 #
8 # Copyright:: (C) 2008 Giuseppe Bilotta
9 #
10 # This plugin tries to automatically recover the bot's wanted nick
11 # in case it couldn't be achieved.
12
13 class NickRecoverPlugin < Plugin
14   
15   Config.register Config::IntegerValue.new('irc.nick_retry',
16     :default => 60, :valiedate => Proc.new { |v| v >= 0 },
17     :on_change => Proc.new do |bot, v|
18       if v > 0
19         bot.plugin['nickrecover'].start_recovery(v)
20       else
21         bot.plugin['nickrecover'].stop_recovery
22       end
23     end, :requires_restart => false,
24     :desc => _("Time in seconds to wait between attempts to recover the nick. set to 0 to disable nick recovery."))
25
26   def help(plugin,topic="")
27     [
28       _("the nickrecover plugin takes care of recovering the bot nick by trying to change nick until it succeeds."),
29       _("the plugin waits irc.nick_retry seconds between attempts."),
30       _("set irc.nick_retry to 0 to disable it.")
31     ].join(' ')
32   end
33
34   def enabled?
35     @bot.config['irc.nick_retry'] > 0
36   end
37
38   def poll_time
39     @bot.config['irc.nick_retry']
40   end
41
42   def wanted_nick
43     @bot.wanted_nick
44   end
45
46   def has_nick?
47     @bot.nick.downcase == wanted_nick.downcase
48   end
49
50   def recover
51     @bot.nickchg wanted_nick
52   end
53
54   def stop_recovery
55     begin
56       @bot.timer.remove(@recovery) if @recovery
57     ensure
58       @recovery = nil
59     end
60   end
61
62   def start_recovery(time=self.poll_time)
63     if @recovery
64       begin
65         @bot.timer.reschedule(@recovery, poll_time)
66         return
67       rescue
68         @recovery=nil
69       end
70     end
71     @recovery = @bot.timer.add(time) do
72       has_nick? ? stop_recovery : recover
73     end
74   end
75
76   def initialize
77     super
78     @recovery = nil
79   end
80
81   def connect
82     if enabled?
83       start_recovery unless has_nick?
84     end
85   end
86
87   def nick(m)
88     return unless m.address?
89     # if recovery is enabled and the nick is not the wanted nick,
90     # launch the recovery process. Stop it otherwise
91     if enabled? and m.newnick.downcase != wanted_nick.downcase
92       start_recovery
93     else
94       stop_recovery
95     end
96   end
97
98   def cleanup
99     stop_recovery
100   end
101
102 end
103
104 plugin = NickRecoverPlugin.new
105