This repository has been archived by the owner on Dec 7, 2023. It is now read-only.
forked from sbp/phenny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
executable file
·255 lines (212 loc) · 9.17 KB
/
bot.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python
"""
bot.py - Phenny IRC Bot
Copyright 2008, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.
http://inamidst.com/phenny/
"""
import sys
import os
import re
import threading
import imp
import irc
home = os.getcwd()
def decode(msg_bytes):
try:
text = msg_bytes.decode('utf-8')
except UnicodeDecodeError:
try:
text = msg_bytes.decode('iso-8859-1')
except UnicodeDecodeError:
text = msg_bytes.decode('cp1252')
return text
class Phenny(irc.Bot):
def __init__(self, config):
args = (config.nick, config.name, config.channels, config.password)
irc.Bot.__init__(self, *args)
self.config = config
self.doc = {}
self.stats = {}
self.setup()
def setup(self):
self.variables = {}
filenames = []
if not hasattr(self.config, 'enable'):
for fn in os.listdir(os.path.join(home, 'modules')):
if fn.endswith('.py') and not fn.startswith('_'):
filenames.append(os.path.join(home, 'modules', fn))
else:
for fn in self.config.enable:
filenames.append(os.path.join(home, 'modules', fn + '.py'))
if hasattr(self.config, 'extra'):
for fn in self.config.extra:
if os.path.isfile(fn):
filenames.append(fn)
elif os.path.isdir(fn):
for n in os.listdir(fn):
if n.endswith('.py') and not n.startswith('_'):
filenames.append(os.path.join(fn, n))
modules = []
excluded_modules = getattr(self.config, 'exclude', [])
filenames = [m for m in filenames if m not in excluded_modules]
for filename in filenames:
name = os.path.basename(filename)[:-3]
try:
module = imp.load_source(name, filename)
except Exception, e:
print >> sys.stderr, "Error loading %s: %s (in bot.py)" % (
name, e)
else:
if hasattr(module, 'setup'):
module.setup(self)
self.register(vars(module))
modules.append(name)
if modules:
print >> sys.stderr, 'Registered modules:', ', '.join(modules)
else:
print >> sys.stderr, "Warning: Couldn't find any modules"
self.bind_commands()
def register(self, variables):
# This is used by reload.py, hence it being methodised
for name, obj in variables.iteritems():
if hasattr(obj, 'commands') or hasattr(obj, 'rule'):
self.variables[name] = obj
def bind_commands(self):
self.commands = {'high': {}, 'medium': {}, 'low': {}}
def bind(self, priority, regexp, func):
print priority, regexp.pattern.encode('utf-8'), func
# register documentation
if not hasattr(func, 'name'):
func.name = func.__name__
if func.__doc__:
if hasattr(func, 'example'):
example = func.example
example = example.replace('$nickname', self.nick)
else:
example = None
self.doc[func.name] = (func.__doc__, example)
self.commands[priority].setdefault(regexp, []).append(func)
def sub(pattern, self=self):
# These replacements have significant order
pattern = pattern.replace('$nickname', re.escape(self.nick))
return pattern.replace('$nick', r'%s[,: ]+' % re.escape(self.nick))
for name, func in self.variables.iteritems():
if not hasattr(func, 'priority'):
func.priority = 'medium'
if not hasattr(func, 'thread'):
func.thread = True
if not hasattr(func, 'event'):
func.event = 'PRIVMSG'
else:
func.event = func.event.upper()
if hasattr(func, 'rule'):
if isinstance(func.rule, str):
pattern = sub(func.rule)
regexp = re.compile(pattern)
bind(self, func.priority, regexp, func)
if isinstance(func.rule, tuple):
# 1) e.g. ('$nick', '(.*)')
if len(func.rule) == 2 and isinstance(func.rule[0], str):
prefix, pattern = func.rule
prefix = sub(prefix)
regexp = re.compile(prefix + pattern)
bind(self, func.priority, regexp, func)
# 2) e.g. (['p', 'q'], '(.*)')
elif len(func.rule) == 2 and isinstance(func.rule[0], list):
prefix = self.config.prefix
commands, pattern = func.rule
for command in commands:
command = r'(%s)\b(?: +(?:%s))?' % (
command, pattern)
regexp = re.compile(prefix + command)
bind(self, func.priority, regexp, func)
# 3) e.g. ('$nick', ['p', 'q'], '(.*)')
elif len(func.rule) == 3:
prefix, commands, pattern = func.rule
prefix = sub(prefix)
for command in commands:
command = r'(%s) +' % command
regexp = re.compile(prefix + command + pattern)
bind(self, func.priority, regexp, func)
if hasattr(func, 'commands'):
for command in func.commands:
template = r'^%s(%s)(?: +(.*))?$'
pattern = template % (self.config.prefix, command)
regexp = re.compile(pattern)
bind(self, func.priority, regexp, func)
def wrapped(self, origin, text, match):
class PhennyWrapper(object):
def __init__(self, phenny):
self.bot = phenny
def __getattr__(self, attr):
sender = origin.sender or text
if attr == 'reply':
return (lambda msg:
self.bot.msg(sender, origin.nick + ': ' + msg))
elif attr == 'say':
return lambda msg: self.bot.msg(sender, msg)
return getattr(self.bot, attr)
return PhennyWrapper(self)
def input_msg(self, origin, text, msg_bytes, match, event, args):
class CommandInput(unicode):
def __new__(cls, text, origin, msg_bytes, match, event, args):
s = unicode.__new__(cls, text)
s.sender = origin.sender
s.nick = origin.nick
s.event = event
s.msg_bytes = msg_bytes
s.match = match
s.group = match.group
s.groups = match.groups
s.args = args
s.admin = origin.nick in self.config.admins
s.owner = origin.nick == self.config.owner
return s
return CommandInput(text, origin, msg_bytes, match, event, args)
def call(self, func, origin, phenny, input_msg):
try:
func(phenny, input_msg)
except Exception, e:
self.error(origin)
def limit(self, origin, func):
if origin.sender and origin.sender.startswith('#'):
if hasattr(self.config, 'limit'):
limits = self.config.limit.get(origin.sender)
if limits and (func.__module__ not in limits):
return True
return False
def dispatch(self, origin, args):
msg_bytes, event, args = args[0], args[1], args[2:]
text = decode(msg_bytes)
last_cmd = False
for priority in ('high', 'medium', 'low'):
items = self.commands[priority].items()
for regexp, funcs in items:
for func in funcs:
if last_cmd:
break
if event != func.event:
continue
match = regexp.match(text)
if not match:
continue
if self.limit(origin, func):
continue
phenny = self.wrapped(origin, text, match)
input_msg = self.input_msg(origin, text, msg_bytes, match, event, args)
if func.thread:
targs = (func, origin, phenny, input_msg)
t = threading.Thread(target=self.call, args=targs)
t.start()
else:
self.call(func, origin, phenny, input_msg)
if hasattr(func, "last_cmd") and func.last_cmd:
last_cmd = True
for source in [origin.sender, origin.nick]:
try:
self.stats[(func.name, source)] += 1
except KeyError:
self.stats[(func.name, source)] = 1
if __name__ == '__main__':
print __doc__