/modules/duckduckgo.py
Python | 58 lines | 47 code | 8 blank | 3 comment | 2 complexity | f38a1137065c7216a1024db21d0c8177 MD5 | raw file
- from __common__ import shorten_url, format_responses
- import requests
- # Constants
- MODULE_NAME = 'DuckDuckGo Instance Answer Search'
- MODULE_ENABLE = True
- MODULE_TYPE = 'command'
- DUCKDUCKGO_URL = u'http://api.duckduckgo.com'
- DUCKDUCKGO_RE = r'^!(ddg|duckduckgo)\s+'
- # DuckDuckGo Instance Answer function
- # https://duckduckgo.com/api
- def duckduckgo(bot, nick, query, channel):
- query = query[len(query.split()[0]) + 1:].strip()
- params = {'q': query, 'format': 'json', 'no_html': 1, 'no_redirect': 1}
- results = requests.get(DUCKDUCKGO_URL, params=params, timeout=bot.conn.requests_timeout)
- response = u'No results'
- try:
- result = results.json()
- if query.startswith('!'):
- title = query[len(query.split()[0]) + 1:].strip()
- content = ''
- url = result['Redirect']
- else:
- title = result['Heading']
- content = result['AbstractText']
- url = result['AbstractURL']
- if not title:
- raise KeyError
- if not content:
- response = u'{title} @ {url}'.format(**locals())
- else:
- response = u'{title} - {content} @ {url}'.format(**locals())
- shorturl = shorten_url(url)
- if url != shorturl:
- response = u'{response} || {shorturl}'.format(**locals())
- except (KeyError, IndexError):
- response = u'No results'
- return format_responses([response], nick, channel)
- # Registration hook
- def register_patterns(bot):
- return (
- (DUCKDUCKGO_RE, lambda nick, message, channel: duckduckgo(bot, nick, message, channel)),
- )
- # vim: set sts=4 sw=4 ts=8 expandtab ft=python: