Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Mar 20, 2019. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpython_dispatch.py
More file actions
Latest commit
95 lines (83 loc) · 3.25 KB
/
Copy pathpython_dispatch.py
File metadata and controls
95 lines (83 loc) · 3.25 KB
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
importimp
importos
importsys
importinspect
importjson
importre
fromscriptsimporthubot_script
classHubotDispatch(object):
def__init__(self):
self.hear_regexes= {}
self.resp_regexes= {}
self.instance_map= {}
self.load_scripts()
self.start_listening()
defstart_listening(self):
whileTrue:
line=sys.stdin.readline()
ifline:
self.receive(line)
else:
return
defreceive(self, json_str):
try:
json_dict=json.loads(json_str)
self.dispatch(json_dict)
exceptExceptionase:
pass
defsend(self, message):
ifmessage:
sys.stdout.write(json.dumps(message) +'\n')
sys.stdout.flush()
defdispatch(self, json_dict):
msg_type=json_dict['type']
ifmsg_type=='hear':
json_dict['message'] =json_dict['message']
self.dispatch_generic(json_dict, self.hear_regexes)
elifmsg_type=='respond':
self.dispatch_generic(json_dict, self.resp_regexes)
defdispatch_generic(self, message, regexes):
forregexinregexes:
search=re.search(regex, message['message'], re.IGNORECASE)
ifsearch:
handler=regexes[regex]
response=message
instance=self.instance_map[handler]
try:
response_text=handler(instance, message, search.groups())
ifresponse_text:
response['message'] =response_text
self.send(response)
exceptExceptionase:
response['message'] ='Python exception: {0}'.format(str(e))
self.send(response)
defno_handler(self, message):
pass
defload_scripts(self):
prefix='{root}{sep}'.format(root=os.path.dirname(os.path.realpath(__file__)), sep=os.sep)
sys.path.append('{0}scripts'.format(prefix))
package=json.load(open('{0}package.json'.format(prefix)))
self.scripts= []
forfilenameinpackage['enabled_scripts']:
modname=filename.replace('.py', '')
modf=imp.find_module(modname)
hubot_script._hear_regexes.clear()
hubot_script._resp_regexes.clear()
try:
mod=imp.load_module(modname, *modf)
regexes= {}
regexes.update(hubot_script._hear_regexes)
regexes.update(hubot_script._resp_regexes)
self.hear_regexes.update(hubot_script._hear_regexes)
self.resp_regexes.update(hubot_script._resp_regexes)
forname, memberininspect.getmembers(mod):
ifinspect.isclass(member):
ifissubclass(member, hubot_script.HubotScript) andmember!=hubot_script.HubotScript:
instance=member()
forkeyinregexes:
self.instance_map[regexes[key]] =instance
self.scripts+= [instance]
exceptExceptionase:
pass
if__name__=='__main__':
dispatch=HubotDispatch()