Пример #1
0
def duckduckgo_search(string_input):
    """
	function responsible for retrieving data
	from Wikipedia. Info returned in list
	"""

    answer = ""

    try:
        answer = duckduckgo.get_zci(string_input,
                                    urls=False,
                                    web_fallback=False)
        if answer == "Sorry, no results.":
            refined_input = stop_words.stopwrd_removal(string_input)
            answer = duckduckgo.get_zci(refined_input,
                                        urls=False,
                                        web_fallback=False)
            if answer == "Sorry, no results.":
                answer = wolfram_search(string_input)
            else:
                answer = refined_search

        return answer

    except Exception, e:
        print(e)
Пример #2
0
    def getHeadlines(self):
        try:
            #news headlines
            headlines_url = 'https://news.google.com/news?ned=us&output=rss'
            feed = feedparser.parse(headlines_url)
            self.newsHeadlines = [post.title for post in feed.entries[:5]]
            #hackernews headlines
            hackerNews_url_top = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
            r = requests.get(hackerNews_url_top)
            hackerNews_items = [item
                                for item in json.loads(r.text)[:5]]  #top 5
            for newsItem in hackerNews_items:
                HackerNewsItem = newsItem
                hackerNews_URL = 'https://hacker-news.firebaseio.com/v0/item/%s.json?print=pretty' % (
                    HackerNewsItem)
                request_item = requests.get(hackerNews_URL)
                newsOutput = json.loads(request_item.text)
                self.hackerHeadlines.append(newsOutput['title'])

            #searchAnswer
            if displayNews == 'Search':
                self.result.append(duckduckgo.get_zci(self.searchstring))

        except Exception as e:
            print('Error: %s. Cannot get news' % e)
        self.after(600000, self.getHeadlines)
Пример #3
0
    def handle_fallback(self, message):
        utt = message.data.get('utterance')
        LOG.debug("DuckDuckGo fallback attempt: " + utt)
        lang = message.data.get('lang')
        if not lang:
            lang = "en-us"

        utterance = normalize(utt, lang)
        parsed_question = self.question_parser.parse(utterance)

        query = utterance
        if parsed_question:
            # Try to store pieces of utterance (None if not parsed_question)
            utt_word = parsed_question.get('QuestionWord')
            utt_verb = parsed_question.get('QuestionVerb')
            utt_query = parsed_question.get('Query')
            if utt_verb == "'s":
                utt_verb = 'is'
                parsed_question['QuestionVerb'] = 'is'
            query = "%s %s %s" % (utt_word, utt_verb, utt_query)
            phrase = "know %s %s %s" % (utt_word, utt_query, utt_verb)
            LOG.debug("Falling back to DuckDuckGo: " + query)
        else:
            # This utterance doesn't look like a question, don't waste
            # time with DuckDuckgo.

            # TODO: Log missed intent
            LOG.debug("Unknown intent: " + utterance)
            return

        resp = duckduckgo.get_zci(utt_query, web_fallback=False)
        print resp.split("(")[0]
        self.speak(resp.split("(")[0])
Пример #4
0
def searchDuck(intent, session):
    if 'query' in intent['slots']:
        lookupString = intent['slots']['query']['value']
    else:
        speech_output = "I'm sorry, I didn't understand, you can say something like 'Who is Tycho the musician?'"
        card_title = None
        should_end_session = True
        reprompt_text = ""
        return build_response({}, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

    #Gets the First Result of a DuckDuckGo
    try:
    	queryRun = duckduckgo.get_zci(lookupString) 
    except ValueError:
    	speech_output = "There was a problem contacting DuckDuckGo, could you try a little later?"
        card_title = "Hello World"
        card_text = speech_output
        reprompt_text = ""
        should_end_session = True
        return build_response({}, build_speechlet_response(
            card_title, speech_output, reprompt_text, should_end_session, card_text))
    else:
        #withOut = re.sub(r"\(http\S+", "", queryRun, flags=re.MULTILINE)
        withOut = re.sub(r"http\S+", "", queryRun, flags=re.MULTILINE)
        speech_output = withOut + ", I've included a link for more info in the Alexa App."
        card_title = "DuckDuckGo - " + lookupString
        reprompt_text = ""
        should_end_session = True
        card_text = queryRun.encode('utf-8')
        return build_response({}, build_speechlet_response(
            card_title, speech_output, reprompt_text, should_end_session, card_text))
Пример #5
0
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
Пример #6
0
	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))
Пример #7
0
def search():
    """Do a search

    @return json, with the result    
    """
    if request.method == 'GET':
        query = request.args.get('q')
        audio = True if request.args.get('speak') == 'true' else False
    else:
        content = request.get_json(silent=True)
        query, audio = get_content_data(content)
    result = duckduckgo.get_zci(query)
    if result is not None:
        if audio:
            text = re.sub(r'(?:\@|https?\://)\S+',
                          '',
                          str(result).strip(),
                          flags=re.MULTILINE)
            print(text)
            if not bool(text and text.strip()):
                text = query
            print(text)
            get_audio_response(text)
        result = bleach.linkify(result)
        return jsonify(data=result), 200

    return jsonify(data='No search results.'), 200
Пример #8
0
def qa(request):
    # print("hic")
    question = request.GET.get('q', "muktosoft")

    if question=="Tell me! What don't you know?":
        questions=Question.objects.all()
        ans={}
        cnt=1
        print(len(questions))
        for q in questions:
            ans["#"+str(cnt)]=q.question
            cnt=cnt+1
        ans=OrderedDict(sorted(ans.items(), key=lambda t: int(t[0][1:])))
        return JsonResponse({"answer": ans})

    answer="Your majesty! Jon Snow knows nothing! So do I!"

    try:
        answer=duckduckgo.get_zci(question)
    except:
        q=Question(question=question)
        q.save()

    if answer[0:4]=="http":
        q=Question(question=question)
        q.save()
        answer="Your majesty! Jon Snow knows nothing! So do I!"

    return JsonResponse({"answer": answer})
Пример #9
0
def search_on_net(data):
    # Search for a response to the question thanks to the DuckDuckGo API
    try:
        response = duckduckgo.get_zci(data)
    except:
        response = "Sorry, I dont't know"
    return response
Пример #10
0
 def search(self, text):
     try:
         return duckduckgo.get_zci(text)
     except Exception as e:
         print(e)
         return self.search_fail[self.randomizer.randint(
             0,
             len(self.search_fail) - 1)]
Пример #11
0
def ddg(query=None):
    searchfor = ' '.join(query)
    if not searchfor or not len(searchfor):
        return ['Search term not defined']
    try:
        result = duckduckgo.get_zci(searchfor)
    except ValueError:
        return ['Plugin found no results']
    return [result]
Пример #12
0
def makeWebhookResult(req):
    speech = 'Sorry not able to get result'
    try:
        result = req.get("result")
        parameters = result.get("parameters")
        given = parameters.get("given-name")
        resolvedQuery = result.get("resolvedQuery")

        print(given)
        print(resolvedQuery)
        print(result.get("action"))
        if result.get("action") == "whatis":
            speech = duckduckgo.get_zci(given)

            if speech.find('http://') != -1 or speech.find(
                    'https://') != -1 or speech == 'Sorry, no results.':
                speech = duckduckgo.get_zci(resolvedQuery)
                if speech.find('http://') != -1 or speech.find(
                        'https://') != -1:
                    speech = 'Sorry!!! Unable to retive any abstract from search result.'

        elif result.get("action") == "greetings":
            username = '******'
            contextsList = result.get("contexts")
            for context in contextsList:
                if context.get("name") == "userinfo":
                    username = context.get("parameters").get("given-name")
            print(given)
            print(username)
            currentTime = datetime.datetime.utcnow()
            print(currentTime.hour)
            temp = weather.processWeatherPuneRequest()

            if currentTime.hour < 7:
                speech = ',Good morning '
            elif 7 <= currentTime.hour < 13:
                speech = ',Good afternoon '
            else:
                speech = ',Good evening '
            speech = 'Hey ' + username + speech + temp + '.May I help you with something more? '
    except Exception, err:
        speech = 'Sorry Internal Error'
Пример #13
0
def duckduckgo_cb(bot, message, *args, **kwargs):
    '''
    Answer query using DuckDuckGo.
    '''
    try:
        query = extract_query(message)
        return duckduckgo.get_zci(query)
    except ValueError:
        return 'Sorry, no results.'
    except AttributeError:
        return 'Sorry, no results.'
Пример #14
0
def ddg(query):
  sleep(.5) # so we aren't querying EVERYTHING we type
  d = duckduckgo.get_zci(query)
  if len(d['text']) > 0 and len(d['url']) > 0:
    append_output(d['text'], "xdg-open " + d['url'])
    update_output()
  elif len(d['text']) > 0:
    append_output(d['text'], '')
    update_output()
  elif len(d['url']) > 0:
    append_output(d['url'], "xdg-open " + d['url'])
    update_output()
Пример #15
0
def web_search(query):
    try:
      answer=duckduckgo.get_zci(query,safesearch=False)
    except:
      return "I am having trouble searching it...try something else."    

    answer=answer.split('(')[0]
    
    if("..." in answer):
        answer = answer + "wait! Are you testing me?!?!"
    if('http' in answer):
        answer = "TBH i don't know...but i can give you a link....go find it there :)\n"+answer
    else:
        answer = "Umm..let me recall...\n"+answer
    return answer    
Пример #16
0
def web_search(query):
    try:
        answer = duckduckgo.get_zci(query, safesearch=False)
    except:
        return "I am having trouble searching it...try something else."

    answer = answer.split('(')[0]

    if ("..." in answer):
        answer = answer + "wait! Are you testing me?!?!"
    if ('http' in answer):
        answer = "TBH i don't know...but i can give you a link....go find it there :)\n" + answer
    else:
        answer = "Umm..let me recall...\n" + answer
    return answer
Пример #17
0
    def respond(self, **kwargs):

        plain_text = kwargs.get('plain_text').lower()

        try:
            for i in range(5):
                print "Attempt #%d"%(i + 1)
                try:
                    result = str(duckduckgo.get_zci(plain_text))#.split()
                    result = re.sub("\(https?.*\)", "", result)
                    return result
                except:
                    pass
        except:
            return "Oops! .. Having some problem!"
        return "Oops! .. Having some problem!"
Пример #18
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')
Пример #19
0
    def ddg(self, irc, msg, args, options, query):
        """[--answer | --abstract | --related | --define | --nourl] <query>

        Searches duckduckgo.com and returns any zero-click information or a web
        result, if any. Using options overrides normal priority. --nourl
        overrides the webLink config."""
        
        showurl = self.registryValue('showURL')
        safesearch = self.registryValue('safeSearch')
        maxreplies = self.registryValue('maxReplies')
        weblink = self.registryValue('webLink')
        showaddionalhits = False
        nourloverride = False
        
        PRIORITY = ['answer', 'abstract', 'related.0', 'definition', 'related']
        
        if options:
            weblink = False
            for (key, value) in options:
                if key == 'nourl':
                    nourloverride = True
                    continue
                if key == 'answer':
                    PRIORITY = ['answer']
                    break
                if key == 'abstract':
                    PRIORITY = ['abstract']
                    break
                if key == 'related':
                    PRIORITY = ['related.0']
                    break
                if key == 'define':
                    PRIORITY = ['definition']
                    break
        if nourloverride:
            web_fallback = False
        res = duckduckgo.get_zci(
                query,
                web_fallback=weblink,
                safesearch=safesearch,
                priority=PRIORITY,
                urls=showurl,
                useragent='Supybot plugin (IRC-bot) https://github.com/Hoaas/Supybot-plugins/tree/master/DuckDuckGo'
        )
        res = res.encode('utf-8')
        irc.reply(res)
Пример #20
0
    def ddg(self, irc, msg, args, options, query):
        """[--answer | --abstract | --related | --define | --nourl] <query>

        Searches duckduckgo.com and returns any zero-click information or a web
        result, if any. Using options overrides normal priority. --nourl
        overrides the webLink config."""
        
        showurl = self.registryValue('showURL')
        safesearch = self.registryValue('safeSearch')
        maxreplies = self.registryValue('maxReplies')
        weblink = self.registryValue('webLink')
        showaddionalhits = False
        nourloverride = False
        
        PRIORITY = ['answer', 'abstract', 'related.0', 'definition', 'related']
        
        if options:
            weblink = False
            for (key, value) in options:
                if key == 'nourl':
                    nourloverride = True
                    continue
                if key == 'answer':
                    PRIORITY = ['answer']
                    break
                if key == 'abstract':
                    PRIORITY = ['abstract']
                    break
                if key == 'related':
                    PRIORITY = ['related.0']
                    break
                if key == 'define':
                    PRIORITY = ['definition']
                    break
        if nourloverride:
            web_fallback = False
        res = duckduckgo.get_zci(
                query,
                web_fallback=weblink,
                safesearch=safesearch,
                priority=PRIORITY,
                urls=showurl,
                useragent='Supybot plugin (IRC-bot) https://github.com/Hoaas/Supybot-plugins/tree/master/DuckDuckGo'
        )
        irc.reply(res)
Пример #21
0
def index():

    # Get the text message body sent by Twilio
    search = request.args.get('Body')

    # Grab the ZCI from DuckDuckGo
    text = duckduckgo.get_zci(search, web_fallback=False, urls=False)

    # Make sure the response fits inside one text message
    if len(text) > 160:
        text = text[:157] + '...'

    # Create a TwiML response object
    r = twiml.Response()
    r.sms(text)

    # Return the TwiML response
    return str(r)
Пример #22
0
def index():

    # Get the text message body sent by Twilio
    search = request.args.get('Body')

    # Grab the ZCI from DuckDuckGo
    text = duckduckgo.get_zci(search, web_fallback=False, urls=False)

    # Make sure the response fits inside one text message
    if len(text) > 160:
        text = text[:157] + '...'

    # Create a TwiML response object
    r = twiml.Response()
    r.sms(text)

    # Return the TwiML response
    return str(r)
Пример #23
0
def searchDuck(intent, session):
    if 'query' in intent['slots']:
        lookupString = intent['slots']['query']['value']
    else:
        speech_output = "I'm sorry, I didn't understand, you can say something like 'Who is Tycho the musician?'"
        card_title = None
        should_end_session = True
        reprompt_text = ""
        return build_response({},
                              build_speechlet_response(card_title,
                                                       speech_output,
                                                       reprompt_text,
                                                       should_end_session))

    #Gets the First Result of a DuckDuckGo
    try:
        queryRun = duckduckgo.get_zci(lookupString)
    except ValueError:
        speech_output = "There was a problem contacting DuckDuckGo, could you try a little later?"
        card_title = "Hello World"
        card_text = speech_output
        reprompt_text = ""
        should_end_session = True
        return build_response({},
                              build_speechlet_response(card_title,
                                                       speech_output,
                                                       reprompt_text,
                                                       should_end_session,
                                                       card_text))
    else:
        #withOut = re.sub(r"\(http\S+", "", queryRun, flags=re.MULTILINE)
        withOut = re.sub(r"http\S+", "", queryRun, flags=re.MULTILINE)
        speech_output = withOut + ", I've included a link for more info in the Alexa App."
        card_title = "DuckDuckGo - " + lookupString
        reprompt_text = ""
        should_end_session = True
        card_text = queryRun.encode('utf-8')
        return build_response({},
                              build_speechlet_response(card_title,
                                                       speech_output,
                                                       reprompt_text,
                                                       should_end_session,
                                                       card_text))
Пример #24
0
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))
def search(command):
    '''
    Gets a result from DuckDuckGo's API.
    Also a prototype for the new duckduckgo-python3 get_zci() logic.
    '''

    try:
        result = ddg.get_zci(command)
    except Exception as e:
        result = broken_msg.format(e.__class__.__name__, str(e))
    if result.startswith('https://api.duckduckgo.com'):
        result = '**Sorry, no results were found.**'

    # result = ddg.query(search, html=True)
    # if result == ' ' or result == '':
    #    result = ddg.get_zci(search)
    # if len(result):

    return result
Пример #26
0
async def ddg(ctx, *, search):
    search = duckduckgo.get_zci(search)
    await ctx.send(f'```{search}```')
Пример #27
0
	def on_data(self, sdata):
		sdatal = []
		sdatal.append(sdata)
		ndel = 0
		for b, data in enumerate(list(sdatal)):
			print "{}: Started at {}".format(METHOD, time.ctime())
			jdata = json.loads(data.strip())
			print METHOD+": Question from @"+ jdata.get("user",{}).get("screen_name") + ": " + jdata.get("text")
			tweetsl  = " ".join([x for x in jdata.get("text").split() if not x.startswith("@")])
			tweetsl = str("".join([i if ord(i) < 128 else " " for i in tweetsl]))

			retweeted = jdata.get("retweeted")
			from_self = jdata.get("user",{}).get("id_str","") == TWITTER_ID

			if retweeted is not None and not retweeted and not from_self:
				#We are using v2 of the Wolfram Alpha API 
				t2 = None
				answer = None
				client = wolframalpha.Client(WOLFRAM_API_ID)
				res = client.query(tweetsl)

				if len(res.pods) > 0 and res.pods[1].title == "Result":
					pod = res.pods[1]
					if pod.text:
						answer = pod.text
					else:
						answer = "Sorry, I have no answer for that question."
					# to skip ascii character in case of error
					answer = answer.encode("ascii", "ignore")
				else:
					short = duckduckgo.get_zci(q = tweetsl, priority = ["answer", "abstract", "definition", "related.0"], web_fallback = True, urls = True) # Get DuckDuckGo response
					if short != "Sorry, no results.":
						answer = "Closest answer: " + str(short)
					else:
						short = urllib2.urlopen("http://v.gd/create.php?format=simple&url=http://duckduckgo.com/?"+str(urllib.urlencode({"q": tweetsl}))).read()
						answer = "Sorry, I have no answer for that. Try this to continue your search: " + str(short)
				
				if not answer:
					answer = "Sorry, I have no answer for that question." # Final response

				furl = re.findall("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", answer)
				if furl:
					for fu in furl:
						if fu:
							newurl = urllib2.urlopen("http://v.gd/create.php?"+urllib.urlencode({"format": "simple", "url": str(fu)})).read() # To shorten the URL
							answer = answer.replace(fu,newurl)
				try:	
					if len(answer) > 140:
						iterate = 138-len(jdata.get("user",{}).get("screen_name"))
						listt = [answer[i:i+iterate] for i in range(0, len(answer), iterate)]
						recentt = jdata.get("id_str","")
						for lt in listt:
							ltt = "@" + jdata.get("user",{}).get("screen_name") + " " + lt
							print METHOD+": Reply: "+ltt
							api.update_status(ltt, in_reply_to_status_id = recentt)
							recentt = str("".join([m.id_str for m in api.user_timeline(user_id = TWITTER_ID, count = 1)]))
							time.sleep(5)
					else:
						lt = "@" + jdata.get("user",{}).get("screen_name") + " " + answer
						print METHOD+": Reply: "+lt
						api.update_status(lt, in_reply_to_status_id = jdata.get("id_str",""))
				except tweepy.error.TweepError:
					pass
			print "{}: Ended at {}".format(METHOD, time.ctime())
			return True
			del sdatal[b-ndel]
			ndel += 1
			time.sleep(5)
Пример #28
0
def longSummaryFromQuery(query):
	g = d.get_zci(query, True)
	if "(" in g:
		return Summarize(query, g, 15)
	else:
		return SummarizeUrl(g, 15)
Пример #29
0
 def ddgia(self, msg, matches):
     '''Returns DDG instant answer'''
     query = matches.group(1)
     reply = ddg.get_zci(query)
     return reply
Пример #30
0
def wholeArticleFromQuery(query):
	g = d.get_zci(query, True)
	if "(" in g:
	 	return Summarize(query, g, 1500)
	else:
		return SummarizeUrl(g, 1500)
Пример #31
0
 def define_concepts(self):
     for concept in self.concepts:
         definition = duckduckgo.get_zci(concept['text'])
         print('%s -> %s' % (concept['text'], definition))
         print('')
Пример #32
0
def wholeArticleFromQuery(query):
    g = d.get_zci(query, True)
    if "(" in g:
        return Summarize(query, g, 1500)
    else:
        return SummarizeUrl(g, 1500)
Пример #33
0
def search(query):
    return duckduckgo.get_zci(query)
              "'When someone tells me to stop acting like a flamingo, I put my foot down'",
              "'I taught a wolf to meditate. Now he is Aware Wolf'",
              "'Two silk worms challenged each other to a race. it ended in a tie'"]
     jokeprint = (random.choice(jokes)) # Choose a random joke
     jokesay = "say " + jokeprint
     print(jokeprint)
     os.system(jokesay)
 elif(question == "search the web"):
     print("What should I search for")
     os.system("say 'what should I search for'")
     with mic as source:
         r.adjust_for_ambient_noise(source)
         audio = r.listen(source)
     searcher = r.recognize_google(audio)
     print(searcher)
     duck = duckduckgo.get_zci(searcher) # Search for text and save result in variable
     print("Here is what I found:")
     os.system("say 'Here is what I found'")
     print(duck)
 elif(question == "track coronavirus"):
     print("Total confirmed: " + str(covid.get_total_confirmed_cases())) # Get total confirmed cases from JHU CSSE
     print("Deaths: " + str(covid.get_total_deaths())) # Get total deaths from JHU CSSE
     print("Recovered: " + str(covid.get_total_recovered())) # Get total recoveries from JHU CSSE
     print("Data from John Hopkins University")
     print(" ")
     print("Which country should I get data for?")
     os.system("say 'which country should I get data for'")
     with mic as source:
         r.adjust_for_ambient_noise(source)
         audio = r.listen(source)
     country = r.recognize_google(audio)
Пример #35
0
    def on_data(self, sdata):
        sdatal = []
        sdatal.append(sdata)
        ndel = 0
        for b, data in enumerate(list(sdatal)):
            print "{}: Started at {}".format(METHOD, time.ctime())
            jdata = json.loads(data.strip())
            print METHOD + ": Question from @" + jdata.get(
                "user", {}).get("screen_name") + ": " + jdata.get("text")
            tweetsl = " ".join([
                x for x in jdata.get("text").split() if not x.startswith("@")
            ])
            tweetsl = str("".join(
                [i if ord(i) < 128 else " " for i in tweetsl]))

            retweeted = jdata.get("retweeted")
            from_self = jdata.get("user", {}).get("id_str", "") == TWITTER_ID

            if retweeted is not None and not retweeted and not from_self:
                #We are using v2 of the Wolfram Alpha API
                t2 = None
                answer = None
                client = wolframalpha.Client(WOLFRAM_API_ID)
                res = client.query(tweetsl)

                if len(res.pods) > 0 and res.pods[1].title == "Result":
                    pod = res.pods[1]
                    if pod.text:
                        answer = pod.text
                    else:
                        answer = "Sorry, I have no answer for that question."
                    # to skip ascii character in case of error
                    answer = answer.encode("ascii", "ignore")
                else:
                    short = duckduckgo.get_zci(
                        q=tweetsl,
                        priority=[
                            "answer", "abstract", "definition", "related.0"
                        ],
                        web_fallback=True,
                        urls=True)  # Get DuckDuckGo response
                    if short != "Sorry, no results.":
                        answer = "Closest answer: " + str(short)
                    else:
                        short = urllib2.urlopen(
                            "http://v.gd/create.php?format=simple&url=http://duckduckgo.com/?"
                            + str(urllib.urlencode({"q": tweetsl}))).read()
                        answer = "Sorry, I have no answer for that. Try this to continue your search: " + str(
                            short)

                if not answer:
                    answer = "Sorry, I have no answer for that question."  # Final response

                furl = re.findall(
                    "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
                    answer)
                if furl:
                    for fu in furl:
                        if fu:
                            newurl = urllib2.urlopen(
                                "http://v.gd/create.php?" +
                                urllib.urlencode({
                                    "format": "simple",
                                    "url": str(fu)
                                })).read()  # To shorten the URL
                            answer = answer.replace(fu, newurl)
                try:
                    if len(answer) > 140:
                        iterate = 138 - len(
                            jdata.get("user", {}).get("screen_name"))
                        listt = [
                            answer[i:i + iterate]
                            for i in range(0, len(answer), iterate)
                        ]
                        recentt = jdata.get("id_str", "")
                        for lt in listt:
                            ltt = "@" + jdata.get(
                                "user", {}).get("screen_name") + " " + lt
                            print METHOD + ": Reply: " + ltt
                            api.update_status(ltt,
                                              in_reply_to_status_id=recentt)
                            recentt = str("".join([
                                m.id_str
                                for m in api.user_timeline(user_id=TWITTER_ID,
                                                           count=1)
                            ]))
                            time.sleep(5)
                    else:
                        lt = "@" + jdata.get(
                            "user", {}).get("screen_name") + " " + answer
                        print METHOD + ": Reply: " + lt
                        api.update_status(lt,
                                          in_reply_to_status_id=jdata.get(
                                              "id_str", ""))
                except tweepy.error.TweepError:
                    pass
            print "{}: Ended at {}".format(METHOD, time.ctime())
            return True
            del sdatal[b - ndel]
            ndel += 1
            time.sleep(5)
Пример #36
0
def longSummaryFromQuery(query):
    g = d.get_zci(query, True)
    if "(" in g:
        return Summarize(query, g, 15)
    else:
        return SummarizeUrl(g, 15)
Пример #37
0
 def define_keywords(self):
     for keyword in self.keywords:
         definition = duckduckgo.get_zci(keyword['text'])
         print('%s -> %s' % (keyword['text'], definition))
         print('')
Пример #38
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)


Пример #39
0
import duckduckgo
print duckduckgo.get_zci("my ip")
Пример #40
0
def trova_sito(ente):
    try:
        link = duckduckgo.get_zci(ente)
    except:
        link = ''
    return link
Пример #41
0
def ddg(query):
    """
    DuckDuckGo search
    """
    return duckduckgo.get_zci(query)
Пример #42
0
 async def run(self, message, trigger, client):
     searchquery = message.content[len(trigger):]
     duckquery = duckduckgo.get_zci(
         searchquery)  # get_zci is basically auto select best result
     await message.channel.send(duckquery)
     return False
Пример #43
0
 def i_feel_lucky(self, term):
     return duckduckgo.get_zci(term, kad=self.language)