-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
282 lines (251 loc) · 10.2 KB
/
plugin.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
###
# Copyright (c) 2014, Julian Paul Glass
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import re
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('GoogleCSE')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x:x
from .local.GoogleAPI import searchEngine
def validateEngine(irc, msg, args, state):
"""Validate engines."""
callConverter('somethingWithoutSpaces', irc, msg, args, state)
addConverter('validateEngine', validateEngine)
def isChannel(s):
return True if s.startswith('#') else False
class GoogleCSE(callbacks.Plugin):
"""The GoogleCSE plugin enables searching via their CSEv1 API"""
home = 'https://github.com/joulez/GoogleCSE'
searchOpts = ('number', 'snippet', 'safe')
def __init__(self, irc):
self.__parent = super(GoogleCSE, self)
self.__parent.__init__(irc)
self._test_response = None
self.opts = {}
self.engine = {}
self._current = {} #cache current results
def _error(self, error):
self.irc.error(error, Raise=True)
def getAPIKey(self):
apikey = self.registryValue('apikey')
if not apikey:
self.irc.error('Please add an API key to the default configuration.',
Raise=True)
return apikey
def setOpts(self, channel, opts=None):
if not isChannel(channel):
channel = None
self.opts['engine'] = self.registryValue('defaultEngine', channel)
self.opts['number'] = self.registryValue('maxPageResults', channel)
self.opts['maxDisplayResults'] = self.registryValue('maxDisplayResults',
channel)
self.opts['snippet'] = self.registryValue('includeSnippet', channel)
self.opts['safe'] = self.registryValue('safeLevel', channel)
self.opts['maxPages'] = self.registryValue('maxPages', channel)
self.opts['engineAPI'] = self.registryValue('engineAPI', channel)
if opts:
for option, arg in opts:
self.opts[option] = arg
def formatOutput(self, channel, page, nav):
l = []
ctr = 0
max = self.registryValue('maxDisplayResults')
def rebold(s):
return s.replace('<b>', '\x02').replace('</b>', '\x02')
def setFormat(title, link):
v= format('%s: %u', ircutils.bold(item.title), item.link)
if self.opts['snippet']:
v += format(' %s',(item.snippet.replace('\n','')))
if self.opts['engineAPI'] == 'legacy':
v = rebold(v)
return v
if isChannel(channel):
max = self.registryValue('maxDisplayResults', channel)
try:
while ctr < max:
ctr += 1
if nav == 'next':
item = page.nextItem()
l.append(setFormat(item.title, item.link))
else:
item = page.previousItem()
l.insert(0, setFormat(item.title, item.link))
except:
return l
return l
def _next(self, caller):
if self._test_response:
self.engine[caller].response = self._test_response
self.engine[caller]._test_feed = True
return self.engine[caller].next()
def evalQuery(self, query):
return re.sub('["\']', '', query.strip())
@wrap([getopts({'engine': 'somethingWithoutSpaces', 'number': 'Int',
'snippet': ''}), 'text'])
def search(self, irc, msg, args, opts, query):
"""[--engine <CSE Code>] [--number <value>] [--snippet] query
Standard basic search. Uses the channel configured engine by default.
See plugins.googlecse.defaultEngine
"""
self.irc = irc
if not self.evalQuery(query):
return irc.error()
self.setOpts(msg.args[0], opts)
if self.opts['engineAPI'] == 'cse':
apikey = self.getAPIKey()
if not self.opts.get('engine'):
self._error('A search engine is required use --engine or'
' configure a default engine for the channel')
self.engine[msg.args[0]] = searchEngine(self.opts['engineAPI'],
query, self.opts, api_key=apikey,
engine_id=self.opts['engine'])
self.log.info(format('\"%s\" Search Engine API created with'
' custom engine ID \"%s\"', self.opts['engineAPI'],
self.opts['engine']))
else:
self.engine[msg.args[0]] = searchEngine(self.opts['engineAPI'],
query, self.opts)
self.log.info(format('\"%s\" Search Engine API initialized',
self.opts['engineAPI']))
page = self._next(msg.args[0])
if page.count == 0:
return irc.reply('No results found.')
fList = self.formatOutput(msg.args[0], page, 'next')
self._current[msg.args[0]] = fList
return self.printResults(fList)
google = search
@wrap
def current(self, irc, msg, args):
"""Returns previously cached results."""
self.irc = irc
L = self._current.get(msg.args[0])
if L:
return self.printResults(L)
else:
return irc.error('No current search cache for %r.'%msg.args[0])
@wrap
def next(self, irc, msg, args):
"""Return next list of items."""
self.irc = irc
eng = self.engine.get(msg.args[0])
if eng:
page = eng.currentPage
fList = self.formatOutput(msg.args[0], page, 'next')
if fList:
if isChannel(msg.args[0]):
self._current[msg.args[0]] = fList
return self.printResults(fList)
return irc.error('No next item.')
else:
return irc.error('No active search.')
@wrap
def previous(self, irc, msg, args):
"""Return previous list of items."""
self.irc = irc
eng = self.engine.get(msg.args[0])
if eng:
page = eng.currentPage
fList = self.formatOutput(msg.args[0], page, 'previous')
if fList:
if isChannel(msg.args[0]):
self._current[msg.args[0]] = fList
return self.printResults(fList)
return irc.error('No previous item.')
else:
return irc.error('No active search.')
@wrap
def nextpage(self, irc, msg, args):
"""Cue the next page."""
eng = self.engine.get(msg.args[0])
if eng:
try:
page = eng.next()
return irc.reply(format('Current page startIndex: %i',page.startIndex))
except:
return irc.error('No next pages.')
return irc.error('No active search.')
@wrap
def previouspage(self, irc, msg, args):
"""Cue the previous page."""
eng = self.engine.get(msg.args[0])
if eng:
try:
page = eng.previous()
return irc.reply(format('Current page startIndex: %i',page.startIndex))
except:
return irc.error('No previous pages.')
return irc.error('No active search.')
def printResults(self, L):
if len(L) > 1:
self.irc.replies(L)
else:
self.irc.reply(L[0])
@wrap(['text'])
def cache(self, irc, msg, args, query):
"""<query>
Search the cache for matches and load the results.
"""
self.irc = irc
class cache(callbacks.Commands):
@wrap
def list(self, irc, msg, args):
"""List search cache."""
@wrap
def add(self, irc, msg, args):
"""Add current search result to the cache if not
already added."""
@wrap(['positiveInt'])
def remove(self, irc, msg, args, id):
"""<id>
Remove cache with <id>.
"""
@wrap
def about(self, irc, msg, *args):
"""<about>
Return information about the plugin.
"""
self.irc = irc
self.setOpts(msg.args[0])
irc.reply(format('%s - Google Custom Search Engine plugin '
'(Engine API: %s) for the Limnoria IRC bot %u',
ircutils.bold(self.__class__.__name__),
ircutils.bold(self.opts['engineAPI']),
ircutils.bold(self.home)))
def _test_feed(self, response):
"""Testing purposes, feed a DResponse object from ./local/test.py"""
self._test_response = response
Class = GoogleCSE
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: