DDG: Add region and safeSearch configs.

This commit is contained in:
oddluck 2020-07-06 19:43:45 +00:00 committed by Valentin Lorentz
parent 902677a378
commit 1c1ba1119d
2 changed files with 29 additions and 4 deletions

View File

@ -47,6 +47,8 @@ def configure(advanced):
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('DDG', True)
class SafeSearch(registry.OnlySomeStrings):
validStrings = ['active', 'moderate', 'off']
DDG = conf.registerPlugin('DDG')
conf.registerChannelValue(DDG, 'maxResults',
@ -56,6 +58,14 @@ conf.registerChannelValue(DDG, 'showSnippet',
registry.Boolean(True, _("""Determines whether the bot will show a
snippet of each resulting link. If False, it will show the title
of the link instead.""")))
conf.registerChannelValue(DDG, 'region',
registry.String("", _("""Set the DDG search region to return results
for the language/country of your choice. E.g. 'us-en' for United States.
https://duckduckgo.com/params""")))
conf.registerChannelValue(DDG, 'searchFilter',
SafeSearch('moderate', _("""Determines what level of search filtering to use
by default. 'active' - most filtering, 'moderate' - default filtering,
'off' - no filtering""")))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -54,10 +54,21 @@ class DDG(callbacks.Plugin):
threaded = True
@staticmethod
def _ddgurl(text):
def _ddgurl(text, region=None, safeSearch=None):
# DuckDuckGo has a 'lite' site free of unparseable JavaScript
# elements, so we'll use that to our advantage!
url = "https://lite.duckduckgo.com/lite?" + urlencode({"q": text})
url = "https://lite.duckduckgo.com/lite?"
params = {"q": text}
if region:
params["kl"] = region
if safeSearch:
if safeSearch == "active":
params["kp"] = 1
elif safeSearch == "moderate":
params["kp"] = -1
elif safeSearch == "off":
params["kp"] = -2
url += urlencode(params)
log.debug("DDG: Using URL %s for search %s", url, text)
@ -87,7 +98,10 @@ class DDG(callbacks.Plugin):
# still somewhat tricky.
results = []
url, real_url, raw_results = self._ddgurl(text)
region = self.registryValue("region", channel_context)
safeSearch = self.registryValue("searchFilter", channel_context)
url, real_url, raw_results = self._ddgurl(text, region, safeSearch)
if real_url != url:
# We received a redirect, likely from something like a !bang request.
@ -146,3 +160,4 @@ Class = DDG
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: