forked from serpis/pynik
-
Notifications
You must be signed in to change notification settings - Fork 7
/
ircbot.py
232 lines (189 loc) · 7.63 KB
/
ircbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import re
import sys
import traceback
import datetime
from copy import copy
from heapq import heappush, heappop
from autoreloader.autoreloader import AutoReloader
import plugin_handler
import error_handler
from ircclient import ircclient
# Call plugins_on_load only on first import
try:
IRCBot
except NameError:
plugin_handler.plugins_on_load()
class PriorityQueue:
def __init__(self):
self.internal_array = []
def clear(self):
self.internal_array = []
def push(self, item):
heappush(self.internal_array, item)
def pop(self):
return heappop(self.internal_array)
def empty(self):
return len(self.internal_array) == 0
def top(self):
return self.internal_array[0]
class TimedEvent:
def __init__(self, trigger_delta, recurring, target, args):
self.trigger_delta = trigger_delta
self.trigger_time = datetime.datetime.now() + trigger_delta
self.recurring = recurring
self.target = target
self.args = args
def trigger(self):
self.target(*self.args)
def reset(self):
self.trigger_time += self.trigger_delta
def __cmp__(self, other):
return cmp(self.trigger_time, other.trigger_time)
class IRCBot(AutoReloader):
def __init__(self, settings):
self.settings = settings
self.callbacks = self.get_callbacks()
self.clients = {}
self.networks = []
self.plugins = []
self.timer_heap = PriorityQueue()
self.next_timer_beat = None
self.need_reload = {}
for network in self.settings.networks:
net_settings = self.settings.networks[network]
print "Connecting to network %s at %s:%s..." % (network,
net_settings['server_address'], net_settings['server_port'])
self.clients[network] = ircclient.IRCClient(net_settings['server_address'],
net_settings['server_port'],
net_settings['nick'],
net_settings['username'],
net_settings['realname'],
network,
net_settings.setdefault('server_password'))
self.clients[network].callbacks = copy(self.callbacks)
self.networks.append(network)
def get_callbacks(self):
return { "on_connected": self.on_connected, "on_join": self.on_join,
"on_nick_change": self.on_nick_change, "on_notice": self.on_notice,
"on_part": self.on_part, "on_privmsg": self.on_privmsg, "on_quit": self.on_quit }
def is_connected(self, network=None):
if network == None:
raise DeprecationWarning("network parameter missing")
return self.clients['networks'].is_connected()
def execute_plugins(self, network, trigger, *arguments):
for plugin in plugin_handler.all_plugins():
try:
if plugin.__class__.__dict__.has_key(trigger):
# FIXME this is rather ugly, for compatiblity with pynik
if plugin.__class__.__dict__[trigger].func_code.co_argcount == len(arguments) + 2:
plugin.__class__.__dict__[trigger](plugin, self, *arguments) # Call without network
elif plugin.__class__.__dict__[trigger].func_code.co_argcount == len(arguments) + 3:
plugin.__class__.__dict__[trigger](plugin, self, *arguments, **{'network': network})
else:
raise NotImplementedError("Plugin '%s' argument count missmatch, was %s." % (
plugin, plugin.__class__.__dict__[trigger].func_code.co_argcount))
except:
error_handler.output_message("%s %s Plugin '%s' threw exception, exinfo: '%s', traceback: '%s'" % (
datetime.datetime.now().strftime("[%H:%M:%S]"), network,
plugin, sys.exc_info(), traceback.extract_tb(sys.exc_info()[2])))
if trigger != "timer_beat":
try:
self.tell(self.settings.admin_network, self.settings.admin_channel,
"%s %s Plugin '%s' threw exception, exinfo: '%s', traceback: '%s'" % (
datetime.datetime.now().strftime("[%H:%M:%S]"), network,
plugin, sys.exc_info(), traceback.extract_tb(sys.exc_info()[2])[::-1]))
except:
error_handler.output_message("%s %s Unable to send exception to admin channel, exinfo: '%s', traceback: '%s'" % (
datetime.datetime.now().strftime("[%H:%M:%S]"), network,
sys.exc_info(), traceback.extract_tb(sys.exc_info()[2])))
def on_connected(self, network):
for channel in self.settings.networks[network]['channels']:
try:
self.join(network, channel[0], channel[1])
except IndexError:
self.join(network, channel[0])
self.execute_plugins(network, "on_connected")
def on_join(self, network, nick, channel):
self.execute_plugins(network, "on_join", nick, channel)
def on_nick_change(self, network, old_nick, new_nick):
self.execute_plugins(network, "on_nick_change", old_nick, new_nick)
def on_notice(self, network, nick, target, message):
self.execute_plugins(network, "on_notice", nick, target, message)
def on_part(self, network, nick, channel, reason):
self.execute_plugins(network, "on_part", nick, channel, reason)
def on_privmsg(self, network, nick, target, message):
self.execute_plugins(network, "on_privmsg", nick, target, message)
def on_quit(self, network, nick, reason):
self.execute_plugins(network, "on_quit", nick, reason)
def on_reload(self):
# Check for new channels, if so join them
for network in self.networks:
for channel in self.settings.networks[network]['channels']:
try:
self.join(network, channel[0], channel[1])
except IndexError:
self.join(network, channel[0])
# Connect to new networks
for network in self.settings.networks:
if network not in self.networks:
net_settings = self.settings.networks[network]
print "Connecting to new network %s at %s:%s..." % (network,
net_settings['server_address'], net_settings['server_port'])
self.clients[network] = ircclient.IRCClient(net_settings['server_address'],
net_settings['server_port'],
net_settings['nick'],
net_settings['username'],
net_settings['realname'],
network)
self.clients[network].callbacks = copy(self.callbacks)
self.networks.append(network)
def reload(self):
self.need_reload['main'] = True
self.need_reload['ircbot'] = True
def reload_plugins(self):
plugin_handler.plugins_on_unload()
plugin_handler.reload_plugin_modules()
plugin_handler.plugins_on_load()
def load_plugin(self, plugin):
plugin_handler.load_plugin(plugin)
def join(self, network, channel, password=""):
return self.clients[network].join(channel, password)
def send(self, network, line=None):
if line == None:
raise DeprecationWarning("network parameter missing")
return self.clients[network].send(line)
def send_all_networks(self, line):
for client in self.clients.values():
if client.is_connected():
client.send(line)
def tell(self, network, target, message=None):
if message == None:
raise DeprecationWarning("network parameter missing")
return self.clients[network].tell(target, message)
def tick(self):
# Do reload if necassary
if self.need_reload.get('ircbot'):
reload(ircclient)
reload(plugin_handler)
self.callbacks = self.get_callbacks()
for client in self.clients.values():
client.callbacks = copy(self.callbacks)
self.need_reload['ircbot'] = False
# Call timers
now = datetime.datetime.now()
while not self.timer_heap.empty() and self.timer_heap.top().trigger_time <= now:
timer = self.timer_heap.pop()
timer.trigger()
if timer.recurring:
timer.reset()
self.timer_heap.push(timer)
for client in self.clients.values():
client.tick()
# Call timer_beat in all networks every 1 second
if not self.next_timer_beat or self.next_timer_beat < now:
self.next_timer_beat = now + datetime.timedelta(0, 1)
for network in self.networks:
self.execute_plugins(network, "timer_beat", now)
def add_timer(self, delta, recurring, target, *args):
timer = TimedEvent(delta, recurring, target, args)
self.timer_heap.push(timer)