-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcoily
More file actions
executable file
·225 lines (192 loc) · 8.67 KB
/
coily
File metadata and controls
executable file
·225 lines (192 loc) · 8.67 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
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
#!/usr/bin/python
"""
Copyright 2006-2008 SpringSource (http://springsource.com), All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import cherrypy
import logging
import os
import re
import sys
from optparse import OptionParser
from springbot import DictionaryBot
from springpython.config import PythonConfig
from springpython.config import Object
from springpython.context import ApplicationContext
from springpython.remoting.pyro import PyroProxyFactory
from springpython.remoting.pyro import PyroServiceExporter
def header():
"""Standard header used for all pages"""
return """
<!--
Coily :: An IRC bot used to manage the #springpython irc channel (powered by CherryPy/Spring Python)
-->
<html>
<head>
<title>Coily :: An IRC bot used to manage the #springpython irc channel (powered by CherryPy/Spring Python)</title>
<style type="text/css">
td { padding:3px; }
div#top {position:absolute; top: 0px; left: 0px; background-color: #E4EFF3; height: 50px; width:100%; padding:0px; border: none;margin: 0;}
div#image {position:absolute; top: 50px; right: 0%; background-image: url(images/spring_python_white.png); background-repeat: no-repeat; background-position: right; height: 100px; width:300px }
</style>
</head>
<body>
<div id="top"> </div>
<div id="image"> </div>
<br clear="all">
<p> </p>
"""
def footer():
"""Standard footer used for all pages."""
return """
<hr>
<table style="width:100%"><tr>
<td><A href="/">Home</A></td>
<td style="text-align:right;color:silver">Coily :: a <a href="http://springpython.webfactional.com">Spring Python</a> IRC bot (powered by <A HREF="http://www.cherrypy.org">CherryPy</A>)</td>
</tr></table>
</body>
"""
def markup(text):
"""Convert any http://xyz references into real web links."""
httpR = re.compile(r"(http://[\w.:/?-]*\w)")
alteredText = httpR.sub(r'<A HREF="\1">\1</A>', text)
return alteredText
class CoilyView:
"""Presentation layer of the web application."""
def __init__(self, bot = None):
"""Inject a controller object in order to fetch live data."""
self.bot = bot
@cherrypy.expose
def index(self):
"""CherryPy will call this method for the root URI ("/") and send
its return value to the client."""
return header() + """
<H2>Welcome</H2>
<P>
Hi, I'm Coily! I'm a bot used to manage the IRC channel <a href="irc://irc.ubuntu.com/#springpython">#springpython</a>.
<P>
If you visit the channel, you may find I have a lot of information to offer while you are there. If I seem to be missing some useful definitions, then you can help grow my knowledge.
<small>
<TABLE border="1">
<TH>Command</TH>
<TH>Description</TH>
<TR>
<TD>!coily, what is <i>xyz</i>?</TD>
<TD>This is how you ask me for a definition of something.</TD>
</TR>
<TR>
<TD>!<i>xyz</i></TD>
<TD>This is a shortcut way to ask the same question.</TD>
</TR>
<TR>
<TD>!coily, <i>xyz</i> is <i>some definition for xyz</i></TD>
<TD>This is how you feed me a definition.</TD>
</TR>
</TABLE>
</small>
<P>
To save you from having to query me for every current definition I have, there is a link on this web site
that lists all my current definitions. NOTE: These definitions can be set by other users.
<P>
<A href="listDefinitions">List current definitions</A>
<P>
""" + footer()
@cherrypy.expose
def listDefinitions(self):
results = header()
results += """
<small>
<TABLE border="1">
<TH>Keyword</TH>
<TH>Definition</TH>
"""
for key, value in self.bot.getDefinitions().items():
results += markup("""
<TR>
<TD>%s</TD>
<TD>%s</TD>
</TR>
""" % (value[0], value[1]))
results += "</TABLE></small>"
results += footer()
return results
class CoilyWebClient(PythonConfig):
"""
This container represents the context of the web application used to interact with the bot and present a
nice frontend to the user community about the channel and the bot.\
"""
def __init__(self):
super(CoilyWebClient, self).__init__()
@Object
def root(self):
return CoilyView(self.bot())
@Object
def bot(self):
proxy = PyroProxyFactory()
proxy.service_url = "PYROLOC://localhost:7766/bot"
return proxy
class CoilyIRCServer(PythonConfig):
"""This container represents the context of the IRC bot. It needs to export information, so the web app can get it."""
def __init__(self):
super(CoilyIRCServer, self).__init__()
@Object
def remoteBot(self):
return DictionaryBot([("irc.ubuntu.com", 6667)], "#springpython", ops=["Goldfisch"], nickname="coily", realname="Coily the Spring Python assistant", logfile="springpython.log")
@Object
def bot(self):
exporter = PyroServiceExporter()
exporter.service_name = "bot"
exporter.service = self.remoteBot()
return exporter
if __name__ == "__main__":
# Parse some launching options.
parser = OptionParser(usage="usage: %prog [-h|--help] [options]")
parser.add_option("-w", "--web", action="store_true", dest="web", default=False, help="Run the web server object.")
parser.add_option("-i", "--irc", action="store_true", dest="irc", default=False, help="Run the IRC-bot object.")
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Turn up logging level to DEBUG.")
(options, args) = parser.parse_args()
if options.web and options.irc:
print "You cannot run both the web server and the IRC-bot at the same time."
sys.exit(2)
if not options.web and not options.irc:
print "You must specify one of the objects to run."
sys.exit(2)
if options.debug:
logger = logging.getLogger("springpython")
loggingLevel = logging.DEBUG
logger.setLevel(loggingLevel)
ch = logging.StreamHandler()
ch.setLevel(loggingLevel)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
if options.web:
# This runs the web application context of the application. It allows a nice web-enabled view into
# the channel and the bot that supports it.
applicationContext = ApplicationContext(CoilyWebClient())
# Configure cherrypy programmatically.
conf = {"/": {"tools.staticdir.root": os.getcwd()},
"/images": {"tools.staticdir.on": True,
"tools.staticdir.dir": "images"},
"/html": {"tools.staticdir.on": True,
"tools.staticdir.dir": "html"},
"/styles": {"tools.staticdir.on": True,
"tools.staticdir.dir": "css"}
}
cherrypy.config.update({'server.socket_port': 9001})
cherrypy.tree.mount(applicationContext.get_object(name = "root"), '/', config=conf)
cherrypy.engine.start()
cherrypy.engine.block()
if options.irc:
# This runs the IRC bot that connects to a channel and then responds to various events.
applicationContext = ApplicationContext(CoilyIRCServer())
coily = applicationContext.get_object("bot")
coily.service.start()