예제 #1
0
    def ddg(self, irc, msg, args, query):
        """<query>

        Searches duckduckgo.com and returns any zero-click information or a web
        result, if any."""
        
        showurl = self.registryValue('showURL')
        safesearch = self.registryValue('safeSearch')
        maxreplies = self.registryValue('maxReplies')
        weblink = self.registryValue('webLink')
        PRIORITY = ['answer', 'abstract', 'related.0', 'definition', 'related']
        showaddionalhits = False
        
        repliessofar = 0
        
        res = duckduckgo.query(
                query,
                safesearch=safesearch,
                useragent='Supybot plugin (IRC-bot) https://github.com/Hoaas/Supybot-plugins/tree/master/DuckDuckGo'
        )

        
        response = []

        for p in PRIORITY:
            ps = p.split('.')
            ptype = ps[0]
            index = int(ps[1]) if len(ps) > 1 else None

            result = getattr(res, ptype)
            if index is not None and len(result) >= index+1: result = result[index]

            if type(result) != list: result = [result]

            for r in result:
                if len(response) >= maxreplies: break
                rline = ''
                if r.text: rline = r.text
                if r.text and hasattr(r,'url') and showurl: 
                    if r.url: rline += ' (%s)' % r.url
                if rline: response.append(rline)

            if response: break

        # if there still isn't anything, try to get the first web result
        if not response and weblink:
            ddgr = duckduckgo.query(
                    '! '+query,
                    safesearch=safesearch,
                    useragent='Supybot plugin (IRC-bot) https://github.com/Hoaas/Supybot-plugins/tree/master/DuckDuckGo'
            ).redirect.url
            if ddgr:
                response = [ddgr]

        # final fallback
        if not response: 
            response = ['Sorry, no results.']

        for resp in response:
            irc.reply(unicode(resp).encode('utf-8'), prefixNick=True)
예제 #2
0
파일: web.py 프로젝트: pratheekms/alex
def generic(query):
    """ generic(query) -- process a generic user query using the Stanford 
	NLTK NER and duckduckgo api.
	"""

    try:
        response = unirest.post(
            "https://textanalysis.p.mashape.com/nltk-stanford-ner",
            headers={
                "X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            params={"text": query},
        )
    except:
        print "Unable to connect to internet"
        return
    web_query = ""
    for entity in response.body["result"].split():
        word, tag = entity.split("/")
        if tag != "O":
            web_query += " " + word
    if web_query != "":
        web_query = web_query.strip().split()
        duckduckgo.query(web_query)
    else:
        print "I do not know how to process this query at this moment."
예제 #3
0
 def general_search(self, term):
     try:
         r = duckduckgo.query(term, kad=self.language)
     except:
         print "duckduck search error, trying again in 30 seconds..."
         time.sleep(30)
         r = duckduckgo.query(term, kad=self.language)
     all_results = ''
     all_results += self.try_add_category(r, 'abstract', 'text')
     all_results += self.try_add_category(r, 'definition', 'text')
     all_results += self.try_add_category(r, 'answer', 'text')
     all_results += self.try_add_category(r, 'redirect', 'text')
     all_results += self.try_add_results(r, "results")
     all_results += self.try_add_results(r, "related")
     return all_results
예제 #4
0
파일: chat.py 프로젝트: DmytroYurchuk/chat
 def duck_n(self):
     r = duckduckgo.query(self.body)
     self.body = ""
     for i in xrange(min(10, len(r.related))):
         self.body += r.related[i].url
         self.body += r.related[i].text
         self.body += " ***** "
예제 #5
0
def get_duckduckgo_content(term):
    response = duckduckgo.query(term)
    content = list()
    if response.type is "answer":
        for i in range(0,len(response.results)):
            content.append({"type":"url","data":{"url":response.results[i].url,"info":response.results[i].text},"score":3})
    return content
예제 #6
0
def DuckWebSearch(search, youtube=False):
    """Performs a DuckDuckGo Web search and returns the results.

    youtube : bool
        True if doing a Youtube lookup

    Returns:
        str : the result of the web search
    """
    if debug: print 'DuckWebSearch: search=', search
    if debug: print 'DuckWebSearch: youtube=', youtube
    if youtube:
        #search = 'youtube' + ' ' + search
        args = {'ia': 'videos'}
    else:
        args = {'ia': 'web'}
    response = duckduckgo.query(search, **args)
    result = ''
    json = response.json
    keys = sorted(json.keys())
    #result += str(keys)
    if 'Image' in keys:
        result += '\n' + json['Image']
    if 'AbstractURL' in keys:
        result += '\n' + json['AbstractURL']
    if 'Abstract' in keys:
        result += '\n' + json['Abstract']
    #for key in keys:
    #    result += '\n%s: %s' % (key, json[key])
    return result.strip()
예제 #7
0
def hello_monkey():
    """Respond to incoming text with a simple text message."""
    account_sid = request.values['AccountSid']
    input_text = request.values['Body']

    #print input_text
    twil_resp = twilio.twiml.Response()
    input_text = input_text.encode('ascii','ignore')

    wolf_response = client.query(input_text)
    try:
        wolf_text = (next(wolf_response.results).text).encode('ascii','ignore')
        print wolf_text
        twil_resp.message(wolf_text)
        return str(twil_resp)
    except StopIteration:
        duck_query = duckduckgo.query(input_text)
        print 'hello'
        print duck_query.type
        if duck_query.type.encode('ascii','ignore') == 'answer' or duck_query.type.encode('ascii','ignore') == 'disambiguation':
            twil_resp.message(duck_query.related[2].text)
            print len(duck_query.related)
            final_response = str(twil_resp) + '..press for more...'
            return str(twil_resp)

        elif duck_query.type.encode('ascii','ignore') == 'nothing':
            failed_text = 'Sorry, no output for this results, try entering something else'
            print failed_text
            twil_resp.message(failed_text)
            return str(twil_resp)
        else:
            pass
예제 #8
0
파일: duck.py 프로젝트: comRamona/SlackBot
def findImage(img=""):
    key = ""
    theurl = "https://duckduckgo-duckduckgo-zero-click-info.p.mashape.com/?callback=process_duckduckgo&format=json&no_html=1&no_redirect=1&q=%s&skip_disambig=1" % (
        img)
    response = unirest.get(theurl,
                           headers={
                               "X-Mashape-Key": key,
                               "Accept": "application/json"
                           })
    response_text = response.body
    p = re.compile(r'(Image\":\")(.*)(\",\"ImageIsLogo)')
    m = p.search(response_text)
    res = m.group(2)
    if len(res) < 2:
        p = re.compile(r'(http[^\"]*((\.png)|(\.jpg)))')
        m = p.search(response_text)
        if (m != None):
            res = m.group()
        else:
            r = duckduckgo.query(img)
            if r.related and hasattr(r.related[0], 'text'):
                res = r.related[0].text
            elif r.results and hasattr(r.results[0], 'text'):
                res = r.results[0].text
            else:
                res = duckduckgo.get_zci(img)

    return res
예제 #9
0
def webhook():
    data = request.get_json()
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                if messaging_event.get("message"):
                    sender_id = messaging_event["sender"]["id"]
                    message_text = messaging_event["message"]["text"]
                    r = duckduckgo.query(message_text)
                    print sender_id, '----> ', message_text
                    msg = ''
                    if r.abstract.text.encode('ascii', 'ignore')[:320] == '':
                        msg = 'Looks like I dont know that ! I need some more training'
                    else:
                        msg = r.abstract.text.encode('ascii', 'ignore')[:320]
                    send_message(sender_id, msg)

                if messaging_event.get("delivery"):
                    pass

                if messaging_event.get("optin"):
                    pass

                if messaging_event.get("postback"):
                    pass

    return "ok", 200
예제 #10
0
    def run(self, edit):
        """Run KristinitaLuckyLink for DuckDuckGo.

        Using DuckDuckGo module, ported to Sublime Text 3:
            https://github.com/Kristinita/python-duckduckgo
        If use duckduckpy, not all results display correct:
            https://stackoverflow.com/q/11722465/5951529
        That to know, how it works, see:
            https://stackoverflow.com/a/12027009/5951529

        Arguments:
            edit {str} -- edit text in Sublime Text.
        """
        selection_text, selection_region = self.get_selection()
        print('KristinitaLuckyLink DuckDuckGo called')

        # [DEPRECATED] Long way to get DuckDuckGo url:
        #
        # Reasons:
        #
        # 1. Long; new way is short;
        # 2. Additional problems with paths, see http://bit.ly/2CVZizl ,
        # 3. HTML structure of DuckDuckGo SERP can change.
        #
        # import re
        # import sys
        # import urllib
        #
        # from w3lib.url import safe_url_string
        # from bs4 import BeautifulSoup
        # # ASCII link for solved encoding problems —
        # # http://stackoverflow.com/a/40654295/5951529
        # ascii_duckduckgo_link = safe_url_string(
        #     u'http://duckduckgo.com/html/?q=' + (selection_text),
        #     encoding="UTF-8")
        # print(ascii_duckduckgo_link)
        # # SERP DuckDuckGo
        # duckduckgo_serp = urllib.request.urlopen(ascii_duckduckgo_link)
        # # Reading SERP
        # read_duckduckgo_serp = duckduckgo_serp.read()
        # # BeautifulSoup — http://stackoverflow.com/a/11923803/5951529
        # parsed_duckduckgo = BeautifulSoup(read_duckduckgo_serp, "lxml")
        # # Parsed first link
        # first_duckduckgo_link = parsed_duckduckgo.findAll(
        #     'div', {'class': re.compile('links_main*')})[0].a['href']
        # # Remove DuckDuckGo specific characters —
        # # http://stackoverflow.com/a/3942100/5951529
        # remove_duckduckgo_symbols = first_duckduckgo_link.replace(
        #     "/l/?kh=-1&uddg=", "")
        # # Final link — http://stackoverflow.com/a/32451970/5951529
        # final_duckduckgo_link = (
        #     urllib.parse.unquote(remove_duckduckgo_symbols))
        final_duckduckgo_link = query('! ' + selection_text).redirect.url
        print(final_duckduckgo_link)
        markdown_duckduckgo_link = '[' + selection_text + ']' + \
            '(' + final_duckduckgo_link + ')'

        # Replace selected text to Markdown link
        self.replace_selection(edit, selection_region,
                               markdown_duckduckgo_link)
예제 #11
0
파일: bot.py 프로젝트: shinarit/lulzbot
	def cmd_ddg(self, e, args):
		if len(u' '.join(args)) == 0:
			self.reply(e, u'Használat: ddg anal bleaching')
		else:
			answer = None
			ddg = duckduckgo.query(" ".join(args).encode("utf-8"), safesearch = False)
			if ddg.answer.text:
				answer = ddg.answer.text
			if not answer and ddg.abstract.text:
				answer = ddg.abstract.text
				if ddg.abstract.url:
					answer += u' ('+ddg.abstract.url+u')'
			if not answer and len(ddg.related):
				if hasattr(ddg.related[0], 'text'):
					if ddg.related[0].text:
						answer = ddg.related[0].text
						if ddg.related[0].url:
							answer += u' ('+ddg.related[0].url+u')'
				elif hasattr(ddg.related[0], 'topics'):
					if len(ddg.related[0].topics) and ddg.related[0].topics[0].text:
						answer = ddg.related[0].topics[0].text
						if ddg.related[0].topics[0].url:
							answer += ddg.related[0].topics[0].url
			if not answer and ddg.definition.text:
				answer = ddg.definition.text
				if ddg.definition.url:
					answer += u' ('+ddg.definition.url+u')'
			if not answer:
				answer = duckduckgo.get_zci(" ".join(args).encode("utf-8"), safesearch=False)
			self.reply(e, HTMLParser.HTMLParser().unescape(answer))
def movie_name_to_imdb_page(query) :
	import duckduckgo
	print query
	r = duckduckgo.query(query)
	
	print r.results
	#imdb_url= r.results[0].url
	print imdb_url
	return imdb_url
예제 #13
0
def movie_name_to_imdb_page(query):
    import duckduckgo
    print query
    r = duckduckgo.query(query)

    print r.results
    #imdb_url= r.results[0].url
    print imdb_url
    return imdb_url
예제 #14
0
 def testPythonDjango(self):
     dataset = query('python django')
     ds = dataset
     self.assertEqual(ds.type, 'nothing')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 0)
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract, None)
     self.assertEqual(ds.redirect, None)
예제 #15
0
 def test4_pow_10(self):
     dataset = query('4 ^ 10')
     ds = dataset
     self.assertEqual(ds.type, 'exclusive')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 0)
     self.assertEqual(ds.answer.primary, '4 ^ 10 = 1,048,576')
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract, None)
     self.assertEqual(ds.redirect, None)
예제 #16
0
 def testPythonDuckDuckGo(self):
     dataset = query('python-duckduckgo')
     ds = dataset
     self.assertEqual(ds.type, 'answer')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 0)
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract.url, 'https://github.com/mikejs/python-duckduckgo')
     self.assertEqual(ds.redirect, None)
예제 #17
0
 def testNFAK(self):
     dataset = query('NFAK')
     ds = dataset
     self.assertEqual(ds.type, 'answer')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 8)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/c/Harmonium_players?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract.url, 'https://en.wikipedia.org/wiki/Nusrat_Fateh_Ali_Khan')
     self.assertEqual(ds.redirect, None)
예제 #18
0
 def test42(self):
     dataset = query('42')
     ds = dataset
     self.assertEqual(ds.type, 'disambiguation')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 7)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/42?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract, None)
     self.assertEqual(ds.redirect, None)
예제 #19
0
 def testDuckDuckGo(self):
     dataset = query('duckduckgo')
     ds = dataset
     self.assertEqual(ds.type, 'answer')
     self.assertEqual(ds.result[0].url, 'https://duckduckgo.com/')
     self.assertEqual(len(ds.related), 1)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/c/Internet_search_engines?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract.url, 'https://en.wikipedia.org/wiki/Duck_Duck_Go')
     self.assertEqual(ds.redirect, None)
예제 #20
0
 def testGenomeProject(self):
     dataset = query('Genome Project')
     ds = dataset
     self.assertEqual(ds.type, 'answer')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 6)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/Joint_Genome_Institute?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract.url, 'https://en.wikipedia.org/wiki/Genome_project')
     self.assertEqual(ds.redirect, None)
예제 #21
0
 def testGoLang(self):
     dataset = query('golang')
     ds = dataset
     self.assertEqual(ds.type, 'answer')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 7)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/Go!_(programming_language)?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition, None)
     self.assertEqual(ds.abstract.url, 'https://en.wikipedia.org/wiki/Go_(programming_language)')
     self.assertEqual(ds.redirect, None)
예제 #22
0
 def testBeetle(self):
     dataset = query('Beetle')
     ds = dataset
     self.assertEqual(ds.type, 'disambiguation')
     self.assertEqual(ds.result, [])
     self.assertEqual(len(ds.related), 20)
     self.assertEqual(ds.related[0].url, 'http://duckduckgo.com/Beetle?kp=1')
     self.assertEqual(ds.answer, None)
     self.assertEqual(ds.definition.url, 'http://www.merriam-webster.com/dictionary/beetle')
     self.assertEqual(ds.abstract, None)
     self.assertEqual(ds.redirect, None)
예제 #23
0
def query(q):
    total = 0.0
    score = 0.0
    resp = duckduckgo.query(str(q).replace(" ", "+").lower())
    print(len(resp.results))
    for result in resp.results:
        #todo add limiter
        print(result.text)
        sim_rating = similarity(str(q), str(result.text), False)
        print(sim_rating)
        total += 1
        score += sim_rating
    return [total, score]
예제 #24
0
def main(term):
    results = duckduckgo.query(str(term))
    if results.type is not 'answer':
        print results.type
    else:
        for i,result in enumerate(results.results):
            print i, result.url, result.text
        browser = raw_input('[o]pen (default) or [l]inks? ').lower()
        print browser
        if browser in ['o', 'open', '']:
            choice = int(raw_input('Open which URL? '))
            os.system('open %s' % results.results[choice].url)
        elif browser in ['l', 'links']:
            choice = int(raw_input('Open which URL? '))
            os.system('links %s' % results.results[choice].url)
예제 #25
0
def getResults(question, mic):
	result=duckduckgo.query(question)
	flag=True
	switch=False
	count=1
	count_topics=0
	#Look at the best (hopefully) answer first
	mic.say(duckduckgo.get_zci(question))
	mic.say('Were you talking about this ?')
	yesno=mic.activeListen()
	if re.search('no',yesno):
		if result.type=='exclusive':
			mic.say(result.answer.text)
		elif result.type!='nothing':
			while flag:
				try:
					if(switch==False):	
						mic.say(result.related[count].text)
					else:
						mic.say(result.related[count].topics[count_topics].text)
					mic.say('Were you talking about this ?')
					yesno=mic.activeListen()
					if re.search('no',yesno) and count<len(result.related)-1:
						if switch==False:
							count=count+1
						else:
							if(count_topics==len(result.related[count].topics)-1):
								count_topics=0
								count=count+1
							else:
								count_topics=count_topics+1
					elif re.search('yes', yesno):
						flag=False
						mic.say('Glad I could help you')
					else:
						flag=False
						mic.say("OK I'll stop")
				#Switch to topics
				except Exception:
					switch=True

		else :
			#get the best results
			mic.say("Sorry, sometime, I'm no good...")
	else:
		mic.say('Glad I could help you')
예제 #26
0
def ComputeMetaRatings(object_common_name = 'MAME', topic_keyword_array = ['arcade', 'emulator']):
	print('ComputeMetaRatings() object_common_name = ' + object_common_name)
	seach_string = object_common_name
	for s_keyword in topic_keyword_array:
		seach_string = seach_string + ' ' + s_keyword

	##seach_string = string.replace(seach_string, ' ', ',')

	print('seach_string = ' + seach_string)

	r = duckduckgo.query(seach_string)
	print(r.type)
	print(r.answer.text)

	if (r.type == 'answer'):
		for result in r.results:
			print('url found : ' + result.url)
    def get_results_duckduckgo(self, query):
        """
        Pobiera linki z DuckDuckGo.
        """
        results = []

        r = duckduckgo.query(query)
        
        print "\nDuckDuckGo result type: %s\n" % r.type 
        
        for result in r.results:
            response = Response()
            response.url = result.url
            response.snippet = result.text
            response.engine = "DuckDuckGo"
            results.append(response)

        return results
예제 #28
0
def ddg_request(msg):
    rep = duckduckgo.query(msg)
    if rep.type == "answer":
        return "%s - %s" % (rep.abstract.text, rep.abstract.url)
    elif rep.type == "nothing" or rep.type == "exclusive":
        if rep.answer.text != "":
            return rep.answer.text
    elif rep.type == "disambiguation":
        res = []
        for result in rep.related:
            if hasattr(result, "text"):
                res.append("%s - %s" % (result.text, result.url))
            else:
                res.append("%s - %s" % (result.topics[0].text,
                                        result.topics[0].url))
        return "\n".join(res[:MAX_RESULT])
    # If the API does not have return any usefull result, we do a real search in ddg
    return html_request(msg)
예제 #29
0
def ddg_request(msg):
    rep = duckduckgo.query(msg)
    if rep.type == "answer":
        return "%s - %s" % (rep.abstract.text, rep.abstract.url)
    elif rep.type == "nothing" or rep.type == "exclusive":
        if rep.answer.text != "":
            return rep.answer.text
    elif rep.type == "disambiguation":
        res = []
        for result in rep.related:
            if hasattr(result, "text"):
                res.append("%s - %s" % (result.text, result.url))
            else:
                res.append("%s - %s" %
                           (result.topics[0].text, result.topics[0].url))
        return "\n".join(res[:MAX_RESULT])
    # If the API does not have return any usefull result, we do a real search in ddg
    return html_request(msg)
예제 #30
0
    def duckduckgo_query(self, search):
        print search
        results = []  # (Text, Link)
        if not search:
            return results
        print '\n'
        print 'searchingggggggggggg'
        print search
        query = duckduckgo.query(search)
        if query.answer is not None:
            results.append((query.answer.text, 'http://duckduckgo.com/'))
            return results
        for result in query.results:
            results.append((result.text, result.url))
        for related in query.related:
            text = 'Related: %s' % related.text
            results.append((text, related.url))

        return results
예제 #31
0
    def duckduckgo_query(self, search):
        print search
        results = []  # (Text, Link)
        if not search:
            return results
        print '\n'
        print 'searchingggggggggggg'
        print search
        query = duckduckgo.query(search)
        if query.answer is not None:
            results.append((query.answer.text, 'http://duckduckgo.com/'))
            return results
        for result in query.results:
            results.append((result.text, result.url))
        for related in query.related:
            text = 'Related: %s' % related.text
            results.append((text, related.url))

        return results
예제 #32
0
파일: search.py 프로젝트: Prodject/OSCAR
def search():
    """Searches and interprets a given string. Can extract summaries from some sites and services. Uses duckduckgo"""
    identifier_string = None
    for string in oscar_functions.inputs[1][0]:
        if re.search(string, oscar_functions.command):
            identifier_string = string
            break
    index = re.search(identifier_string, oscar_functions.command).end()
    query = oscar_functions.command[index:]
    if query.endswith("?"):
        query = query[:-1]
    if query != "":
        answer = duckduckgo.get_zci(query)
        duck_query = duckduckgo.query(query)
        if answer != "":
            print(answer + "\n")
            if duck_query.type != "nothing":
                confirm = input(oscar_functions.get_response(4)).lower()
                if oscar_functions.get_yes_no(confirm):
                    oscar_functions.open_in_browser(duck_query.related[0].url)
                else:
                    print(oscar_functions.get_response(19))
            elif answer.startswith("http"):
                if answer.startswith("https://www.youtu.be") or answer.startswith("https://www.youtube.com"):
                    confirm = input(oscar_functions.get_response(31))
                else:
                    confirm = input(oscar_functions.get_response(3)).lower()
                if oscar_functions.get_yes_no(confirm):
                    oscar_functions.open_in_browser(answer)
                else:
                    print(oscar_functions.get_response(20))

        else:
            confirm = input(oscar_functions.get_response(3)).lower()
            if oscar_functions.get_yes_no(confirm):
                for c in query:
                    if c == ' ':
                        c = '+'
                oscar_functions.open_in_browser("https://www.duckduckgo.com/?q=" + query)
            else:
                print(oscar_functions.get_response(20))
    else:
        print(oscar_functions.get_response(2))
예제 #33
0
def build_web_tree(qr, depth=0):
    print ' '* depth * 4 + qr
    ds = query(qr)
    if depth == 2:
        return 
    if ds.error_code != 0:
        return 
    visited.append(qr)
    if ds.related == []:
        return 
    else:
         for r in ds.related:
             if isinstance(r, Topic) == True:
                 r_used = r.name.encode('ascii', 'ignore')
             else:
                 r_used = r.text.encode('ascii', 'ignore').split('-')[0].strip()
             try:
                 visited.index(r_used) 
             except:
                 build_web_tree(r_used, depth=depth+1)
예제 #34
0
파일: pybotX.py 프로젝트: dezka/pybot
def ddg(query_string, sock_obj):
    ''' This function uses the duckduckgo library to search ddg
    for matches to `query_string`

    :param query_string: String to query ddg for
    :type query_string: ``str``
    :returns:
    :rtype: ``str``
    '''
    if query_string == '':
        sock_obj.send("PRIVMSG {} :Please search something.\r\n".format(CHAN))
    else:
        r = duckduckgo.query(query_string)
        if (r.type == 'disambiguation' or
            r.type == 'answer' or
            r.type == 'nothin'):
            ans = [r.related[0].text, r.related[0].url]
            response = ' | '.join(ans)
        elif r.type == 'nothing':
            response = r.answer.text
        sock_obj.send("PRIVMSG {} :{}\r\n".format(CHAN, response))
예제 #35
0
    def respond(self, query):
        if len(query) == 0:
            return 0.0

        r = ddg.query(query)

        LOG.debug('Query: ' + str(query))
        LOG.debug('Type: ' + r.type)

        if r.answer is not None and r.answer.text and "HASH" not in r.answer.text:
            self.speak(query + self.is_verb + r.answer.text + '.')
        elif len(r.abstract.text) > 0:
            sents = split_sentences(r.abstract.text)
            self.speak(sents[0])
        elif len(r.related) > 0 and len(r.related[0].text) > 0:
            related = split_sentences(r.related[0].text)[0]
            self.speak(self.format_related(related, query))
        else:
            return False

        return True
예제 #36
0
 def lookup(self, mess, args):
     """Look up a word in the very small and useless dictionary
     This command looks for infobits set with the setbit command
     Upd8! It also ducks anything not found in the dictionary
     and W|As anything duckduckgo doesn't know"""
     admin = str(mess.getFrom()).split('@')[0] in admins
     if args.lower() in infobits.keys() and infobits.get(args, ('not found', True))[1]:
         return infobits.get(args.lower(), ('not found', True))[0]
     elif args.lower() in infobits.keys() and not infobits.get(args, ('not found', True))[1] and admin:
         return 'This infobit is not yet approved: ' + infobits.get(args.lower(), ('not found', True))[0]
     res = ddg.query(args.lower())
     out = ''
     abstext = unicode(res.abstract.text)
     if abstext: out += 'From DuckDuckGo: ' + abstext
     elif res.related: 
         for resu in res.related:
             if resu.text: out += resu.text + '\n'
             
     if out: return out
     return self.wa(mess, args)
     return 'That infobit either doesn\'t exist, or has not been approved'
예제 #37
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:

            search_query_list = ircMsg.msg.split(' ')
            search_query_list.pop(0)
            search_query = ' '.join(search_query_list)

            result = duckduckgo.query(search_query)

            irc_msg.msg = ' - '.join(
                [result.results[0].text, result.results[0].url])

        except:
            irc_msg.msg = 'Cagadales, el API del pato es una mierda'\
            ' https://duckduckgo.com/api'

        return irc_msg
예제 #38
0
def ddg(server=None, channel=None, text=None, **kwargs):
    query = unicode(text).split(u' ', 1)[1]
    result = duckduckgo.query(query.encode("utf-8"))

    if len(result.related) > 0:
        for related in result.related[:(
                int(DDG_CREGEX.match(text).groups()[0] or 3))]:
            pack = related.text.split(u',', 1)
            if len(pack) == 2:
                title, info = pack
            else:
                title = pack[0]
                info = None
            server.privmsg(
                channel, u"2%s%s » 4%s" %
                (title, u", 3%s" % info if info is not None else u"",
                 related.url.replace(u"duckduckgo.com", u"ddg.gg").replace(
                     u"?kp=1", u"")))
    else:
        server.privmsg(
            channel, u"No related definitions found. Go to http://ddg.gg/%s" %
            urllib.quote(query.encode("utf-8")))
예제 #39
0
def build_web_tree(node, qr, depth=0):
    cooked_qr = qr.replace('"', '\\"')
    print '"%s" [label="%s", shape="hexagon", style="filled", color="%s"];' % (cooked_qr, cooked_qr, depth_color[depth])
    if node != None:
        print '"%s" -> "%s";' % (node, cooked_qr)
    ds = query(qr)
    if depth == 3:
        return 
    if ds.error_code != 0:
        return 
    visited.append(qr)
    if ds.related == []:
        return 
    else:
         for r in ds.related:
             if isinstance(r, Topic) == True:
                 r_used = r.name.encode('ascii', 'ignore')
             else:
                 r_used = r.text.encode('ascii', 'ignore').split('-')[0].strip()
             try:
                 visited.index(r_used) 
             except:
                 build_web_tree(qr, r_used, depth=depth+1)
예제 #40
0
파일: ddg.py 프로젝트: S4M04NSL4Y3R/AnkhBot
    def on_message(self, user, channel, msg):
        response = None
        if msg.startswith(".ddg"):
            query = msg.replace(".ddg", "").strip()
        else:
            return

        try:  # Do I need this?
            d = duckduckgo.query(query)
        except:
            return

        if d.type == 'answer':
            if d.answer is not None:
                response = "{}".format(d.answer.text)
            else:
                response = "{} :: Source: {} - {}".format(d.abstract.text,
                                                            d.abstract.source,
                                                            d.abstract.url)
            if len(d.results) > 0:  # or should I use !=[]...
                response += " :: {}: {}".format(d.results[0].text,
                                                  d.results[0].url)

        elif d.type == 'exclusive' or d.type == 'nothing':
            if d.answer is not None:
                response = "{}".format(d.answer.text)

        elif d.type == 'disambiguation':
            if len(d.related) > 1:
                response = "Disambiguation: {} :: {}".format(d.related[0].text,
                                                               d.related[1].text)

        if response is None or response == "":
            self.bot.msg(channel, "Sorry, no results found")
        else:
            self.bot.msg(channel, response)
예제 #41
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:

            search_query_list = ircMsg.msg.split(' ')
            search_query_list.pop(0)
            search_query = ' '.join(search_query_list)

            result = duckduckgo.query(search_query)

            irc_msg.msg = ' - '.join([
                result.results[0].text,
                result.results[0].url
            ])

        except:
            irc_msg.msg = 'Cagadales, el API del pato es una mierda'\
            ' https://duckduckgo.com/api'

        return irc_msg
예제 #42
0
 def ddg(self, query, lang='en'):
     r = duckduckgo.query(query)
     if r.type == 'exclusive':
         return r.answer.text.encode('utf-8')
     if r.type == 'disambiguation':
         wik = self.wp_run(query, lang)
         if wik:
             return wik
         elif len(r.related) > 0:
             tmp = u'Is this what you think of: ' + self.ddg_chose(r.related)
             tmp = tmp.encode('utf-8')
             return tmp
         else:
             return u'My head hurts :(.'
     if r.type == 'answer':
         tmp = r.abstract.text
         tmp = self.smart_truncate(tmp) + ' (' + r.abstract.url + ')'
         tmp = tmp.encode('utf-8')
         return tmp
     else:
         wik = self.wp_run(query, lang)
         if wik:
             return wik
         return None
예제 #43
0
def process_chat(*args):
    img = "anna" + str(random.randint(6, 8)) + ".png"
    try:
        ident = args[0]["identifier"]
        global users
        global lastpost
        global cb
        if ident in users:
            interval = (datetime.now() - users[ident]).total_seconds()
            #if interval < 7:
            #    return
        message = args[0]["body"]
        name = args[0]["name"]
        count = str(args[0]["count"])
        convo = args[0]["convo"]
        country_name = args[0]["country_name"]
        country = args[0]["country"]
        if "trip" in args[0]:
            trip = args[0]["trip"]
        else:
            trip = ""
        if trip == "!!n60sL82Wd2" and name == "anna":
            annaposts.append(count)
            return
        # default message
        out_message = ""

        if not message.strip().startswith('.'):
            with sqlite3.connect('lb.sqlite') as conn:
                conn.execute(
                    'INSERT INTO posts(id,ident,name,trip,convo,text,country,country_name,date) VALUES(?,?,?,?,?,?,?,?,?);',
                    (count, ident, name, trip, convo, message, country,
                     country_name, datetime.now()))

        for k, v in replies.items():
            if message.lower() == '.%s' % k:
                out_message = v

        #if (('to die' in message.lower() or 'death' in message.lower() or 'suicide' in message.lower()) and 'want' in message.lower()) or "kill me" in message.lower():
        #    out_message = random.choice(["Kill urself already.", "Just do it. Kill yourself.", "Suicide is the answer.", "Die"])

        # helpful
        t = re.compile('[wW]hat (is|are) (.+)\?').match(message)
        if (t):
            try:
                res = wolfram.query(t.group(2))
                #out_message = next(res.results).text
                out_message = '\n'.join(z.text for z in res.pods[1:] if z)
                #out_message = wikipedia.summary(t.group(1), sentences=1)
            except Exception as e:
                print res.__dict__
                print out_message
                out_message = ""
                print "wolfram error", e

        # kc
        t = re.compile('\.kc( (.+))?').match(message)
        if (t):
            res = kc_quote(t.group(1))
            if res:
                out_message = res

        # reddit
        t = re.compile('\.reddit( (.+))?').match(message)
        if (t):
            if t.group(1) and t.group(1).strip().replace(
                    '_', '').isalpha() and not re.match(
                        '.*(gay|c**k|penis|ass)', t.group(1)):
                res = reddit(t.group(1).strip())
            else:
                res = reddit()
            if res:
                out_message, img = res
        # urban
        t = re.compile('\.urban (.+)').match(message)
        if (t):
            res = ''
            for l in urbandict.define(t.group(1)):
                res += "def: %s\nexample: %s\n" % (l['def'].strip(),
                                                   l['example'].strip())
            if res:
                out_message = res
        # play
        t = re.compile('\.play( (.+))?').match(message)
        if (t):
            out_message, img = game.play(t.group(1), ident, name, country)
            convo = "hangman"

        # wolfram
        t = re.compile('\.wa (.+)').match(message)
        if (t):
            try:
                res = wolfram.query(t.group(1))
                out_message = next(res.results).text
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1, 5)) + ".png"
                #img = "shit.jpg"
                print e

        # wiki
        t = re.compile('\.wiki(pedia)? (.+)').match(message)
        if (t):
            try:
                out_message = wikipedia.summary(t.group(2), sentences=3)
            except wikipedia.DisambiguationError as e:
                out_message = str(e)
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1, 5)) + ".png"
                #img = "shit.jpg"
                print e

        # google
        t = re.compile('\.google( (.+))?').match(message)
        if (t):
            try:
                r = duckduckgo.query(t.group(2))
                for i in xrange(len(r.related) if len(r.related) < 4 else 3):
                    result = r.related[i]
                    out_message += '\n' + result.text + '\n'
                    out_message += '[i]' + result.url + ' [/i]\n'
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1, 5)) + ".png"
                #img = "shit.jpg"
                print e

        # random
        t = re.compile('\.random( (.+))?').match(message)
        if (t):
            try:
                if t.group(1) and t.group(2).isdigit():
                    out_message += str(random.randint(0, int(t.group(2))))
                else:
                    out_message += str(random.randint(0, 100))
                    if int(out_message) % 10 == int(out_message) / 10:
                        out_message += " (you got doubles :3)"
            except Exception as e:
                out_message = "That was ambiguous, Onii-chan"
                img = "anna" + str(random.randint(1, 5)) + ".png"
                #img = "shit.jpg"
                print e
        # fortune
        t = re.compile('\.fortune( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fortunes').read().strip()
        # riddle
        t = re.compile('\.riddle( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune riddles').read().strip()
        # stats
        t = re.compile('\.stats( (.+))?').match(message)
        if (t):
            out_message = stats()
        # scores
        t = re.compile('\.scores( (.+))?').match(message)
        if (t):
            out_message = game.stats()
        # online
        t = re.compile('\.online( (.+))?').match(message)
        if (t):
            out_message = online()
        # countries
        t = re.compile('\.countries( (.+))?').match(message)
        if (t):
            out_message = countries()
        # regions
        t = re.compile('\.regions( (.+))?').match(message)
        if (t):
            out_message = regions()
        # joke
        t = re.compile('\.joke( (.+))?').match(message)
        if (t):
            out_message = norris(
            )  #random.choice(open('jokes.txt').read().split('\n-')).strip()
        # meme
        t = re.compile('\.meme( (.+))?').match(message)
        if (t):
            out_message = " "
            img = 'memes/' + random.choice(os.listdir('memes'))
        # hi
        t = re.compile('\.hi( (.+))?').match(message)
        if (t):
            out_message = "%s, %s!" % (random.choice(
                ['Hi', 'Hello', 'Privet', 'Hola', 'Bonjour', 'Hallo']), name)
        # help
        t = re.compile('\.help( (.+))?').match(message)
        if (t):
            out_message = "commands are .hi .p**n .kc .random .joke .fortune .google .urban .wa .wiki .riddle .meme .play .reddit .stats .countries .regions .online .scores"
            out_message += '\nor "Anna ...?" or "What is/are ...?"'
        # p**n
        t = re.compile('\.p**n( (.+))?').match(message)
        if (t):
            out_message = random.choice([
                'You are wankaholic',
                'You are addicted to masturbating',
                'You are addicted to pornography',
                'Hi wanka',
            ])
            img = 'wanka.jpg'
            img = 'p**n/' + random.choice(os.listdir('p**n'))
            convo = 'nsfw'

        ## add
        #t = re.compile('\.add (\w+) (.+)').match(message)
        #if (t):
        #    #print t.groups(1)[0], t.groups(1)[1]
        #    replies[t.groups(1)[0]] = t.groups(1)[1]

        if (message.splitlines() and message.splitlines()[0].lstrip('>')
                in annaposts) or (message.lower().startswith('anna')
                                  and message.endswith('?')):
            try:
                if message.lower().startswith('anna'):
                    message = message[4:].strip()
                out_message = cb.ask(u'\n'.join(
                    line for line in message.splitlines()
                    if not line.startswith('>')))
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1, 5)) + ".png"
                #img = "shit.jpg"
                print e
                cb = Cleverbot()

        #if count[-1]==count[-2] and random.randint(1,5)==2:
        #    out_message = "CHECKED"
        #    img = "dubs" + str(random.randint(1,5)) + ".jpg"

        #if 'anna' in message.lower():
        #    out_message = "you said my name, Onii-chan?"
        #if 'kcmod' in message.lower():
        #    out_message = "mods are cucks"

        if not out_message and random.randint(
                0,
                45) == 5 and (datetime.now() - lastpost).total_seconds() > 30:
            print(datetime.now() - lastpost).total_seconds()
            out_message = kc_quote()
            count = 0

        if out_message != "":
            users[ident] = datetime.now()
            lastpost = datetime.now()
            if (count):
                out_message = ">>" + count + "\n" + out_message  #.encode('ascii', 'ignore')
            post_chat(out_message,
                      channel,
                      name="anna",
                      trip=config.annaTrip,
                      convo=convo,
                      file=img)
    except Exception as e:
        #print type(e), e
        #raise
        print e
예제 #44
0
import duckduckgo

for r in duckduckgo.query('Sausages').results:
    if 'Text' in r:
        print(r['FirstURL'] + ' - ' + r['Text'])


예제 #45
0
 def __init__(self, bang_id, search_query=''):
     self._query = duckduckgo.query('!{bangId} {searchQuery}'.format(
         bangId=bang_id, searchQuery=search_query))
     self._redirectUrl = ''
예제 #46
0
"""
Purpose: Usage of duckduckgo api
    https://duckduckgo.com/api

    pip install duckduckgo
"""

import sys

import duckduckgo

# print(dir(duckduckgo))

try:
    query_string = input("Enter the query:")
    response = duckduckgo.query(query_string)
except Exception as ex:
    print("request failed with error:", repr(ex))
    sys.exit(1)

# print(dir(response))
print("API version     :", response.api_version)
print("response.type   :", response.type)
print()

if response.type == "answer":  # DuckDuckGo
    print("answer url      :", response.abstract.url)
    print("answer source   :", response.abstract.source)
    print("No. of results  :", len(response.results))

    print()
예제 #47
0
 def _send_request(self, query, **kwargs):
     return duckduckgo.query(query.encode('utf-8'))
예제 #48
0
def search(request):

    #Get the query from the form
    query = str(request.GET.get('query'))

    #If the query is empty
    if query is "":
        #Load the template
        template = loader.get_template('search.html')
        #Make a new temporary template. Will not be stored
        tmpTemplate = Template(
            "<center><h1>Whoops! Looks like we didn't find anything.</h1></center>"
        )
        #Add context
        context = RequestContext(
            request,
            {
                "url": "",
                "site": tmpTemplate,
                "link": "",
                #"related": related,
            })

        #Render template with context
        return HttpResponse(template.render(context))
    #If the query contains something
    else:
        #Force character encoding to utf-8
        reload(sys)
        sys.setdefaultencoding('utf8')

        #Array of allowed domain endings
        allowed = [".com", ".org", ".net"]
        #Get all of the sites
        sites = Sites.objects.all()

        #Call the duckduckgo instant answers api to get result and url
        result = d.query(query)
        url = result.abstract.url

        #Instantiate a variable called simpleUrl
        simpleUrl = None

        #Loop through all of the allowed domain endings
        for i in allowed:
            #If the url ends in one of the allowed url endings
            if i in url:
                #Parse the url along the url ending
                parsed = url.split(i)
                #Take the simple url and add the domain ending back to it
                simpleUrl = parsed[0] + i
                #Break the loop. No need to go on
                break

            #Log url in the database if it is not in it already
            if (url not in str(sites)):
                s = Sites(url=url)
                s.save()
        """
        Get an array of meta data key words from the url
        Go through all of the urls in the database
        if one of the first 10 key words is in the array of the url's meta data then log it as a related keyword
        """

        #related = getMetaData(sites, url)

        #Load the search.html template
        template = loader.get_template('search.html')

        #Open a channel to the site, and retrieve its...
        templateSite = BeautifulSoup(urllib2.urlopen(url))
        #body...
        body = templateSite.body
        #and css href.
        link = templateSite.link["href"]

        #Get all of the <a> in the template
        links = body.findAll("a")

        #Loop through all of the <a>
        for l in links:
            #If the link is not formatted correctly...
            if "//" not in str(l) and "#" not in str(l) and "href" in str(l):
                #Put the link into soup
                soup = BeautifulSoup(str(l))
                #Get the a tag out of the soup
                tag = soup.a
                #Take the simple url and add it to the tag's broken reference
                fixedUrl = simpleUrl + str(tag["href"])
                #Replace the malformatted link with the new, properly formatted link
                body = str(body).replace(str(tag["href"]), fixedUrl)

        #Put site's body into a temporary template. This template will not be stored
        tmpTemplate = Template(body)

        #Define the context for the template
        context = RequestContext(
            request,
            {
                "url": url,
                "site": tmpTemplate,
                "link": simpleUrl + link,
                #"related": related,
            })

        #Return the template with context
        return HttpResponse(template.render(context))
예제 #49
0
def get_image(query):
    answer = duckduckgo.query(query, safesearch=False)
    return answer.image.url
예제 #50
0
import duckduckgo
print duckduckgo.query("! Example").redirect.url
예제 #51
0
	symptoms.add(line[1])

i=1
for string in list(symptoms):
    print("iteration "+str(i))
    i+=1
    string = string.encode('utf-8')
    lst = list()
    lst.append(string)
    string = string.split(",")[0]
    answer1=""
    answer2=""
    answer3=""
    answer=""
    try:
        answer1 = duckduckgo.query(string).abstract.url
    except Exception as e:
        pass

    try:
        answer2 = duckduckgo.query(string).results[0].url
    except Exception as e:
        pass
    try:
        answer3 = duckduckgo.query(string).related[0].url
    except Exception as e:
        pass
    #answer = answer.strip().

    if(len(answer1)<2):
        if(len(answer2)<2):
예제 #52
0
import duckduckgo

r = duckduckgo.query('DuckDuckGo')
if r.type == 'answer':
    print(r.results)
예제 #53
0
 def retrieve_ip_from_ddg(self):
     r = duckduckgo.query('my ip')
     return re.findall(r'[0-9]+(?:\.[0-9]+){3}', r.answer.text)[0]
예제 #54
0
def instant_answer(question):
    r = duckduckgo.query(question)
    ans = r.abstract.text
    speak(ans)
예제 #55
0
def ddg_rel_search(q):
    try:
        return ddg.query(q)
    except urllib2.URLError:
        print 'Alfred: There is a problem connecting to search engine'
예제 #56
0
    def duck_func(self):

        r = duckduckgo.query(str(self.message["body"])[6:])
        for i in range(num_req):
            self.send_bot(r.related[i].text)
예제 #57
0
# this script searches duckduckgo for R packages so we can quickly categorize if the package is a 
# CRAN, bioconductor, github or other package
# creates some nice output
import duckduckgo,time


fname = "./r-libs.txt"

with open(fname) as fp:
    for line in fp:
       # this "dummy request" avoids the problem but i dunno why
       # see https://github.com/mikejs/python-duckduckgo/issues/3 
       duckduckgo.query("foo")
       content = line.strip() + " R"
       search_result = duckduckgo.get_zci(content)
       print content + "\t" + search_result
       time.sleep(10)