Пример #1
0
def apertium_translate(phenny, input):
    '''Translates a phrase using APy.'''
    pairRE = langRE + r'-' + langRE
    line, line_error = strict_check(
        r'((?:' + pairRE + r'(?:\|' + pairRE + r')*' + r' ?)+)\s+(.*)',
        input.group(1), apertium_translate)

    if line_error:
        phenny.say(line_error)
        return

    if (len(line.group(2)) > 350) and (not input.admin):
        #raise GrumbleError('Phrase must be under 350 characters.')
        phenny.say('Phrase must be under 350 characters.')

    blocks = line.group(1).split(' ')
    for block in blocks:
        pairs = block.split('|')
        translated = line.group(2)
        for (input_lang, output_lang) in [pair.split('-') for pair in pairs]:
            if input_lang == output_lang:
                #raise GrumbleError('Stop trying to confuse me! Pick different languages ;)')
                phenny.say(
                    'Stop trying to confuse me! Pick different languages ;)')

            # TODO: Remove this try/except block? web.decode doesn't seem to raise any GrumbleError's
            try:
                translated = web.decode(
                    translate(phenny, translated, input_lang, output_lang))
            except GrumbleError as err:
                phenny.say('{:s}-{:s}: {:s}'.format(input_lang, output_lang,
                                                    str(err)))
                return
        phenny.reply(web.decode(translated))
Пример #2
0
def tr(phenny, context):
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode("utf-8")

    if (len(phrase) > 350) and (not context.admin):
        return phenny.reply("Phrase must be under 350 characters.")

    input = input or "auto"
    input = input.encode("utf-8")
    output = (output or "en").encode("utf-8")

    if input != output:
        msg, input = translate(phrase, input, output)
        if isinstance(msg, str):
            msg = msg.decode("utf-8")
        if msg:
            msg = web.decode(msg)  # msg.replace(''', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else:
            msg = "The %s to %s translation failed, sorry!" % (input, output)

        phenny.reply(msg)
    else:
        phenny.reply("Unable to guess your crazy moon language, sorry. Maybe you can suggest one?")
Пример #3
0
def c(phenny, input): 
   """Google calculator."""
   for x in phenny.bot.commands["high"].values():
      if x[0].__name__ == "aa_hook":
         if x[0](phenny, input):
            return # Abort function
   if not input.group(2):
      return phenny.reply("Nothing to calculate.")
   q = input.group(2).encode('utf-8')
   q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
   q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
   print("[LOG]: %s calculated '%s'" % (input.nick,q))
   uri = 'http://www.google.com/ig/calculator?q='
   bytes = web.get(uri + web.urllib.quote(q))
   parts = bytes.split('",')
   answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
   if answer: 
      answer = answer.decode('unicode-escape')
      answer = ''.join(chr(ord(c)) for c in answer)
      answer = answer.decode('utf-8')
      answer = answer.replace(u'\xc2\xa0', ',')
      answer = answer.replace('<sup>', '^(')
      answer = answer.replace('</sup>', ')')
      answer = web.decode(answer)
      phenny.say(answer)
   else: phenny.say('Sorry, no result.')
Пример #4
0
def tr(jenni, context): 
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode('utf-8')

    if (len(phrase) > 350) and (not context.admin): 
        return jenni.reply('Phrase must be under 350 characters.')

    input = input or detect(phrase)
    if not input: 
        err = 'Unable to guess your crazy moon language, sorry.'
        return jenni.reply(err)
    input = input.encode('utf-8')
    output = (output or 'en').encode('utf-8')

    if input != output: 
        msg = translate(phrase, input, output)
        if msg: 
            msg = web.decode(msg) # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else: msg = 'The %s to %s translation failed, sorry!' % (input, output)

        jenni.reply(msg)
    else: jenni.reply('Language guessing failed, so try suggesting one!')
Пример #5
0
def tr(jenni, context): 
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode('utf-8')

    if (len(phrase) > 350) and (not context.admin): 
        return jenni.reply('Phrase must be under 350 characters.')

    input = input or detect(phrase)
    if not input: 
        err = 'Unable to guess your crazy moon language, sorry.'
        return jenni.reply(err)
    input = input.encode('utf-8')
    output = (output or 'en').encode('utf-8')

    if input != output: 
        msg = translate(phrase, input, output)
        if isinstance(msg, str):
            msg = msg.decode('utf-8')
        if msg: 
            msg = web.decode(msg) # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else: msg = 'The %s to %s translation failed, sorry!' % (input, output)

        jenni.reply(msg)
    else: jenni.reply('Language guessing failed, so try suggesting one!')
Пример #6
0
def tr(code, context):
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode('utf-8')

    if (len(phrase) > 350) and (not context.admin):
        return code.reply('Phrase must be under 350 characters.')

    input = input or 'auto'
    input = input.encode('utf-8')
    output = (output or 'en').encode('utf-8')

    if input != output:
        msg, input = translate(phrase, input, output)
        if isinstance(msg, str):
            msg = msg.decode('utf-8')
        if msg:
            msg = web.decode(msg)  # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translation)' % (msg, input, output)
        else:
            msg = 'The %s to %s translation failed, sorry!' % (input, output)

        code.reply(msg)
    else:
        code.reply('Language guessing failed, so try suggesting one!')
Пример #7
0
def c(jenni, input):
    """.c -- Google calculator."""
    if not input.group(2):
        return jenni.reply('Nothing to calculate.')
    q = input.group(2).encode('utf-8')
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
    uri = 'https://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    equation = [p for p in parts if p.startswith('{lhs: "')][0][7:]
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer and equation:
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = uc.decode(answer)
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        answer = answer.strip()
        equation = uc.decode(equation)
        equation = equation.strip()
        max_len = 450 - len(answer) - 6
        new_eq = equation
        if len(new_eq) > max_len:
            end = max_len - 10
            new_eq = new_eq[:end]
            new_eq += '[..]'
        output = '\x02' + answer + '\x02' + ' == ' + new_eq
        jenni.say(output)
    else:
        jenni.say('Sorry, no result.')
Пример #8
0
 def escape(seq):
     seq = seq.decode('unicode-escape')
     seq = seq.replace(u'\xc2\xa0', ',')
     seq = seq.replace('<sup>', '^(')
     seq = seq.replace('</sup>', ')')
     seq = web.decode(seq)
     return seq
Пример #9
0
def tr2(phenny, input): 
   """Translates a phrase, with an optional language hint."""
   command = input.group(2).encode('utf-8')

   def langcode(p): 
      return p.startswith(':') and (2 < len(p) < 10) and p[1:].isalpha()

   args = ['auto', 'en']

   for i in xrange(2): 
      if not ' ' in command: break
      prefix, cmd = command.split(' ', 1)
      if langcode(prefix): 
         args[i] = prefix[1:]
         command = cmd
   phrase = command

   if (len(phrase) > 350) and (not input.admin): 
      return phenny.reply('Phrase must be under 350 characters.')

   src, dest = args
   if src != dest: 
      msg, src = translate(phrase, src, dest)
      if isinstance(msg, str): 
         msg = msg.decode('utf-8')
      if msg: 
         msg = web.decode(msg) # msg.replace('&#39;', "'")
         msg = '"%s" (%s to %s, translate.google.com)' % (msg, src, dest)
      else: msg = 'The %s to %s translation failed, sorry!' % (src, dest)

      phenny.reply(msg)
   else: phenny.reply('Language guessing failed, so try suggesting one!')
Пример #10
0
def c(phenny, input):
    """Google calculator."""
    q = input.group(2)
    if not q:
        return phenny.reply("Could not calculate. Missing terms?")
    q = q.encode('utf-8')
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer:
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = answer.decode('utf-8')
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = answer.replace('<sub>', '(')
        answer = answer.replace('</sub>', ')')
        answer = web.decode(answer)
        phenny.say(answer)
    else:
        phenny.say('Sorry, no result.')
Пример #11
0
def calc(phenny, input): 
   """Google calculator."""
   if not input.group(2):
      return phenny.reply("Nothing to calculate.")
   q = input.group(2).encode('utf-8')
   q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
   q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
   uri = 'http://www.google.com/search?q='
   bytes = web.get(uri + web.urllib.quote(q))
   html = lxml.html.fromstring(bytes)
   try:
      answer = html.get_element_by_id("cwos").text_content().strip()
   except KeyError:
      try:
         answer = lxml.etree.tostring(html.find_class("vk_ans")[0])
         answer = answer[answer.find('>')+1:answer.rfind('<')]
      except IndexError:
         answer = None
   if answer:
      answer = web.decode(answer)
      answer = answer.replace(u'\xc2\xa0', ',')
      answer = answer.replace('<sup>', '^(')
      answer = answer.replace('</sup>', ')')
      answer = answer.encode('utf-8')
      phenny.say(answer)
   else: phenny.say('Sorry, no result.')
Пример #12
0
def tr2(jenni, input):
    """Translates a phrase, with an optional language hint."""
    if not input.group(2): return jenni.say("No input provided.")
    command = input.group(2).encode('utf-8')

    def langcode(p):
        return p.startswith(':') and (2 < len(p) < 10) and p[1:].isalpha()

    args = ['auto', 'en']

    for i in xrange(2):
        if not ' ' in command: break
        prefix, cmd = command.split(' ', 1)
        if langcode(prefix):
            args[i] = prefix[1:]
            command = cmd
    phrase = command

    if (len(phrase) > 350) and (not input.admin):
        return jenni.reply('Phrase must be under 350 characters.')

    src, dest = args
    if src != dest:
        msg, src = translate(phrase, src, dest)
        if isinstance(msg, str):
            msg = msg.decode('utf-8')
        if msg:
            msg = web.decode(msg)  # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, src, dest)
        else:
            msg = 'The %s to %s translation failed, sorry!' % (src, dest)

        jenni.reply(msg)
    else:
        jenni.reply('Language guessing failed, so try suggesting one!')
Пример #13
0
def c(jenni, input):
    """.c -- Google calculator."""
    if not input.group(2):
        return jenni.reply('Nothing to calculate.')
    q = input.group(2).encode('utf-8')
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
    uri = 'https://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    equation = [p for p in parts if p.startswith('{lhs: "')][0][7:]
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer and equation:
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = uc.decode(answer)
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        answer = answer.strip()
        equation = uc.decode(equation)
        equation = equation.strip()
        max_len = 450 - len(answer) - 6
        new_eq = equation
        if len(new_eq) > max_len:
            end = max_len - 10
            new_eq = new_eq[:end]
            new_eq += '[..]'
        output = '\x02' + answer + '\x02' + ' == ' + new_eq
        jenni.say(output)
    else:
        jenni.say('Sorry, no result.')
Пример #14
0
def tr(torp, context):
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode("utf-8")

    if (len(phrase) > 350) and (not context.admin):
        return torp.reply("Phrase must be under 350 characters.")

    input = input or detect(phrase)
    if not input:
        err = "Unable to guess your crazy moon language, sorry."
        return torp.reply(err)
    input = input.encode("utf-8")
    output = (output or "en").encode("utf-8")

    if input != output:
        msg = translate(phrase, input, output)
        if isinstance(msg, str):
            msg = msg.decode("utf-8")
        if msg:
            msg = web.decode(msg)  # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else:
            msg = "The %s to %s translation failed, sorry!" % (input, output)

        torp.reply(msg)
    else:
        torp.reply("Language guessing failed, so try suggesting one!")
Пример #15
0
def duck_search(query): 
    query = query.replace('!', '')
    query = web.quote(query)
    uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query
    bytes = web.get(uri)
    m = r_duck.search(bytes)
    if m: return web.decode(m.group(1))
Пример #16
0
def tr(jenni, context):
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase.encode('utf-8')

    if (len(phrase) > 350) and (not context.admin):
        return jenni.reply('Phrase must be under 350 characters.')

    input = input or 'auto'
    input = input.encode('utf-8')
    output = (output or 'en').encode('utf-8')

    if input != output:
        msg, input = translate(phrase, input, output)
        if isinstance(msg, str):
            msg = msg.decode('utf-8')
        if msg:
            msg = web.decode(msg)
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else:
            msg = 'The %s to %s translation failed, sorry!' % (input, output)

        jenni.reply(msg)
    else:
        jenni.reply('Language guessing failed, so try suggesting one!')
Пример #17
0
def duck_search(query): 
   query = query.replace('!', '')
   query = web.urllib.quote(query)
   uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query
   bytes = web.get(uri)
   m = r_duck.search(bytes)
   if m: return web.decode(m.group(1))
Пример #18
0
def google_count(query):
    query = web.quote(query)
    uri = 'https://google.co.uk/search?q=%s' % query
    bytes = web.get(uri)
    m = r_google_count.search(bytes)
    if m:
        result = web.decode(m.group(1)).replace(',', '')
        return int(result)
    else:
        return 0
Пример #19
0
def clean_up_answer(answer):
    answer = answer.encode('utf-8')
    answer = answer.decode('utf-8')
    answer = ''.join(chr(ord(c)) for c in answer)
    answer = uc.decode(answer)
    answer = answer.replace('<sup>', '^(')
    answer = answer.replace('</sup>', ')')
    answer = web.decode(answer)
    answer = answer.strip()
    answer += ' [GC]'
    return answer
Пример #20
0
def c(phenny, input):
    """Google calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2)
    bytes = generic_google(q)
    m = r_google_calc_exp.search(bytes)
    if not m:
        m = r_google_calc.search(bytes)

    if not m:
        num = None
    elif m.lastindex == 1:
        num = web.decode(m.group(1))
    else:
        num = "^".join((web.decode(m.group(1)), web.decode(m.group(2))))

    if num:
        num = num.replace('×', '*')
        phenny.say(num)
    else:
        phenny.reply("Sorry, no result.")
Пример #21
0
def imdb_search(query):
    query = query.replace('!', '')
    query = web.quote(query)
    uri = 'http://imdb.com/find?q=%s' % query
    bytes = web.get(uri)
    m = r_imdb_find.search(bytes)
    if not m: return m
    ID = web.decode(m.group(1))
    uri = 'http://imdb.com/title/%s' % ID
    bytes = web.get(uri)
    bytes = bytes.replace('\n', '')
    info = r_imdb_details.search(bytes)
    info = {'Title': info.group(1), 'Year': info.group(2), 'Plot': info.group(3), 'imdbID': ID}
    return info
Пример #22
0
def apertium_translate(phenny, input):
    '''Translates a phrase using APy.'''
    line = strict_check(r'((?:' + langRE + r'-' + langRE + r' ?)+)\s+(.*)',
                        input.group(2), apertium_translate)
    if (len(line.group(2)) > 350) and (not input.admin):
        raise GrumbleError('Phrase must be under 350 characters.')

    pairs = [tuple(langs.split('-')) for langs in line.group(1).split(' ')]
    for (input_lang, output_lang) in pairs:
        if input_lang == output_lang:
            raise GrumbleError('Stop trying to confuse me! Pick different languages ;)')
        try:
            translated = translate(phenny, line.group(2), input_lang, output_lang)
            phenny.reply(web.decode(translated))
        except GrumbleError as err:
            phenny.say('{:s}-{:s}: {:s}'.format(input_lang, output_lang, str(err)))
Пример #23
0
def apertium_translate(phenny, input):
    """Translates a phrase using the apertium API"""
    line = input.group(2)
    if not line:
        raise GrumbleError("Need something to translate!")
    #line = line.encode('utf-8')

    pairs = []
    guidelines = line.split('|')
    if len(guidelines) > 1:
        for guideline in guidelines[1:]:
            #phenny.say(guideline)
            pairs.append(guideline.strip().split('-'))
    guidelines = guidelines[0]
    #phenny.say("guidelines: "+str(guidelines))
    stuff = re.search('(.*) ([a-z]+-[a-z]+)', guidelines)
    #phenny.say('groups: '+str(stuff.groups()))
    pairs.insert(0, stuff.group(2).split('-'))
    translate_me = stuff.group(1)
    #phenny.say(str(pairs))

    #output_lang = line.split(' ')[-1]
    #input_lang = line.split(' ')[-2]
    #translate_me = ' '.join(line.split(' ')[:-2])

    if (len(translate_me) > 350) and (not input.admin):
        raise GrumbleError('Phrase must be under 350 characters.')

    msg = translate_me
    finalmsg = False
    translated = ""
    for (input_lang, output_lang) in pairs:
        if input_lang == output_lang:
            raise GrumbleError(
                'Stop trying to confuse me!  Pick different languages ;)')
        msg = translate(msg, input_lang, output_lang)
        if not msg:
            raise GrumbleError('The %s to %s translation failed, sorry!' %
                               (input_lang, output_lang))
        msg = web.decode(msg)  # msg.replace('&#39;', "'")
        this_translated = "(%s-%s) %s" % (input_lang, output_lang, msg)
        translated = msg

    #if not finalmsg:
    #   finalmsg = translated
    #phenny.reply(finalmsg)
    phenny.reply(translated)
Пример #24
0
def c(phenny, input): 
   """Google calculator."""
   q = input.group(2).encode('utf-8')
   q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
   q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
   uri = 'http://www.google.com/ig/calculator?q='
   bytes = web.get(uri + web.urllib.quote(q))
   parts = bytes.split('",')
   answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
   if answer: 
      answer = answer.decode('unicode-escape')
      answer = answer.replace(u'\xc2\xa0', ',')
      answer = answer.replace('<sup>', '^(')
      answer = answer.replace('</sup>', ')')
      answer = web.decode(answer)
      phenny.say(answer)
   else: phenny.say('Sorry, no result.')
Пример #25
0
def apertium_translate(phenny, input): 
   """Translates a phrase using the apertium API"""
   line = input.group(2)
   if not line:
      raise GrumbleError("Need something to translate!")
   #line = line.encode('utf-8')

   pairs = []
   guidelines = line.split('|')
   if len(guidelines) > 1:
      for guideline in guidelines[1:]:
         #phenny.say(guideline)
         pairs.append(guideline.strip().split('-'))
   guidelines = guidelines[0]
   #phenny.say("guidelines: "+str(guidelines))
   stuff = re.search('(.*) ([a-z]+-[a-z]+)', guidelines)
   #phenny.say('groups: '+str(stuff.groups()))
   pairs.insert(0, stuff.group(2).split('-'))
   translate_me = stuff.group(1)
   #phenny.say(str(pairs))

   #output_lang = line.split(' ')[-1]
   #input_lang = line.split(' ')[-2]
   #translate_me = ' '.join(line.split(' ')[:-2])

   if (len(translate_me) > 350) and (not input.admin): 
      raise GrumbleError('Phrase must be under 350 characters.')

   msg = translate_me
   finalmsg = False
   translated = ""
   for (input_lang, output_lang) in pairs:
      if input_lang == output_lang: 
         raise GrumbleError('Stop trying to confuse me!  Pick different languages ;)')
      msg = translate(msg, input_lang, output_lang)
      if not msg:
         raise GrumbleError('The %s to %s translation failed, sorry!' % (input_lang, output_lang))
      msg = web.decode(msg) # msg.replace('&#39;', "'")
      this_translated = "(%s-%s) %s" % (input_lang, output_lang, msg)
      translated = msg

   #if not finalmsg:
   #   finalmsg = translated
   #phenny.reply(finalmsg)
   phenny.reply(translated)
Пример #26
0
def convertvals(imperial):
   q = imperial
   q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
   q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
   uri = 'http://www.google.com/ig/calculator?q='
   bytes = web.get(uri + web.urllib.quote(q))
   parts = bytes.split('",')
   answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
   if answer:
      answer = answer.decode('unicode-escape')
      answer = ''.join(chr(ord(c)) for c in answer)
      answer = answer.decode('utf-8')
      answer = answer.replace(u'\xc2\xa0', ',')
      answer = answer.replace('<sup>', '^(')
      answer = answer.replace('</sup>', ')')
      answer = web.decode(answer)
      return answer
   else: return 0
Пример #27
0
def convertvals(imperial):
    q = imperial
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer:
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = answer.decode('utf-8')
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        return answer
    else:
        return 0
Пример #28
0
def imdb_search(query):
    query = query.replace('!', '')
    query = web.quote(query)
    uri = 'http://imdb.com/find?q=%s' % query
    bytes = web.get(uri)
    m = r_imdb_find.search(bytes)
    if not m: return m
    ID = web.decode(m.group(1))
    uri = 'http://imdb.com/title/%s' % ID
    bytes = web.get(uri)
    bytes = bytes.replace('\n', '')
    info = r_imdb_details.search(bytes)
    info = {
        'Title': info.group(1),
        'Year': info.group(2),
        'Plot': info.group(3),
        'imdbID': ID
    }
    return info
Пример #29
0
def devwiki(phenny, input):
	term = input.group(2)
	if not term:
		return

	log.log("event", "%s queried Developer Wiki for '%s'" % (log.fmt_user(input), term), phenny)
	term = term.replace(" ", "_")
	term = web.urlencode(term)

	data, scode = web.get(wikiuri_g % term)
	if scode == 404:
		return phenny.say("No such page.")
	data = str(data, "utf-8")

	m = re.search(r_content, data)
	if not m:
		return phenny.say("Sorry, did not find any text to display. Here's the link: %s" % (wikiuri_r % term,))
	data = data[m.span()[1]:]

	mi = re.finditer(r_paragraph, data)
	text = ""
	for m in mi:
		abort = False
		for e in nottext:
			if re.search(e, m.group(1)):
				abort = True
				break
		if abort:
			continue
		text = m.group(1)
		break
	if not text:
		m = re.search(r_headline, data)
		if m:
			text = "<b>" + m.group(1) + "</b>"
		else:
			return phenny.say("Sorry, did not find any text to display. Here's the link: %s" % (wikiuri_r % term,))
	for tf in transforms:
		text = re.sub(tf[0], tf[1], text)
	m = re.search(r_sentenceend, text)
	if m:
		text = text[:m.span()[1]-1]
	phenny.say('"%s" - %s' % (web.decode(text), wikiuri_r % term))
Пример #30
0
def c(phenny, input): 
    """Google calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2)
    q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer: 
        #answer = ''.join(chr(ord(c)) for c in answer)
        #answer = answer.decode('utf-8')
        answer = answer.replace('\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        phenny.say(answer)
    else: phenny.say('Sorry, no result.')
Пример #31
0
def tr(phenny, context): 
    """Translates a phrase, with an optional language hint."""
    input, output, phrase = context.groups()

    phrase = phrase

    if (len(phrase) > 350) and (not context.admin): 
        return phenny.reply('Phrase must be under 350 characters.')

    input = input or 'auto'
    output = (output or 'en')

    if input != output: 
        msg, input = translate(phrase, input, output)
        if msg: 
            msg = web.decode(msg) # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
        else: msg = 'The %s to %s translation failed, sorry!' % (input, output)

        phenny.reply(msg)
    else: phenny.reply('Language guessing failed, so try suggesting one!')
Пример #32
0
def tr2(phenny, input):
    """Translates a phrase, with an optional language hint."""
    command = input.group(2)
    if not command:
        return phenny.reply("Need something to translate!")
    command = command.encode("utf-8")

    def langcode(p):
        return p.startswith(":") and (2 < len(p) < 10) and p[1:].isalpha()

    args = ["auto", "en"]

    for i in xrange(2):
        if not " " in command:
            break
        prefix, cmd = command.split(" ", 1)
        if langcode(prefix):
            args[i] = prefix[1:]
            command = cmd
    phrase = command

    # if (len(phrase) > 350) and (not input.admin):
    #    return phenny.reply('Phrase must be under 350 characters.')

    src, dest = args
    if src != dest:
        msg, src = translate(phrase, src, dest)
        if isinstance(msg, str):
            msg = msg.decode("utf-8")
        if msg:
            msg = web.decode(msg)  # msg.replace('&#39;', "'")
            if len(msg) > 450:
                msg = msg[:450] + "[...]"
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, src, dest)
        else:
            msg = "The %s to %s translation failed, sorry!" % (src, dest)

        phenny.reply(msg)
    else:
        phenny.reply("Unable to guess your crazy moon language, sorry. Maybe you can suggest one?")
Пример #33
0
def etymology(word):
    # @@ <nsh> sbp, would it be possible to have a flag for .ety to get 2nd/etc
    # entries? - http://swhack.com/logs/2006-07-19#T15-05-29

    if len(word) > 25:
        raise ValueError("Word too long: %s[...]" % word[:10])
    word = {'axe': 'ax/axe'}.get(word, word)

    grab = urllib._urlopener
    urllib._urlopener = Grab()
    urllib._urlopener.addheader("Referer", "http://www.etymonline.com/")
    bytes = web.get(etyuri % web.urllib.quote(word))
    urllib._urlopener = grab
    definitions = r_definition.findall(bytes)

    if not definitions:
        return None

    defn = text(definitions[0])
    m = r_sentence.match(defn)
    if not m:
        return None
    sentence = m.group(0)

    try:
        sentence = unicode(sentence, 'iso-8859-1')
        sentence = sentence.encode('utf-8')
    except:
        pass
    sentence = web.decode(sentence)

    maxlength = 275
    if len(sentence) > maxlength:
        sentence = sentence[:maxlength]
        words = sentence[:-5].split(' ')
        words.pop()
        sentence = ' '.join(words) + ' [...]'

    sentence = '"' + sentence.replace('"', "'") + '"'
    return sentence + ' - etymonline.com'
Пример #34
0
def c(phenny, input):
    """Google calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2).encode("utf-8")
    q = q.replace("\xcf\x95", "phi")  # utf-8 U+03D5
    q = q.replace("\xcf\x80", "pi")  # utf-8 U+03C0
    uri = "http://www.google.com/ig/calculator?q="
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer:
        answer = answer.decode("unicode-escape")
        answer = "".join(chr(ord(c)) for c in answer)
        answer = answer.decode("utf-8")
        answer = answer.replace(u"\xc2\xa0", ",")
        answer = answer.replace("<sup>", "^(")
        answer = answer.replace("</sup>", ")")
        answer = web.decode(answer)
        phenny.say(answer)
    else:
        phenny.say("Sorry, no result.")
Пример #35
0
 def c(self, mess, args):
    #google-calc
    if not args:
       return "Nothing to calculate."
    q = args.encode('utf-8')
    q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer: 
       answer = answer.decode('unicode-escape')
       answer = ''.join(chr(ord(c)) for c in answer)
       answer = answer.decode('utf-8')
       answer = answer.replace(u'\xc2\xa0', ',')
       answer = answer.replace('<sup>', '^(')
       answer = answer.replace('</sup>', ')')
       answer = web.decode(answer)
       return answer
    else: 
       return 'Sorry, no result.'
Пример #36
0
def c(phenny, input): 
    """Google calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2)
    q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer: 
        #answer = ''.join(chr(ord(c)) for c in answer)
        #answer = answer.decode('utf-8')
        answer = answer.replace('\\x26#215;', '*')
        answer = answer.replace('\\x3c', '<')
        answer = answer.replace('\\x3e', '>')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        phenny.say(answer)
    else: phenny.reply('Sorry, no result.')
Пример #37
0
 def c(self, mess, args):
     #google-calc
     if not args:
         return "Nothing to calculate."
     q = args.encode('utf-8')
     q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
     q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
     uri = 'http://www.google.com/ig/calculator?q='
     bytes = web.get(uri + web.urllib.quote(q))
     parts = bytes.split('",')
     answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
     if answer:
         answer = answer.decode('unicode-escape')
         answer = ''.join(chr(ord(c)) for c in answer)
         answer = answer.decode('utf-8')
         answer = answer.replace(u'\xc2\xa0', ',')
         answer = answer.replace('<sup>', '^(')
         answer = answer.replace('</sup>', ')')
         answer = web.decode(answer)
         return answer
     else:
         return 'Sorry, no result.'
Пример #38
0
def etymology(word): 
   # @@ <nsh> sbp, would it be possible to have a flag for .ety to get 2nd/etc
   # entries? - http://swhack.com/logs/2006-07-19#T15-05-29
   
   if len(word) > 25: 
      raise ValueError("Word too long: %s[...]" % word[:10])
   word = {'axe': 'ax/axe'}.get(word, word)

   grab = urllib._urlopener
   urllib._urlopener = Grab()
   urllib._urlopener.addheader("Referer", "http://www.etymonline.com/")
   bytes = web.get(etyuri % web.urllib.quote(word))
   urllib._urlopener = grab
   definitions = r_definition.findall(bytes)

   if not definitions: 
      return None

   defn = text(definitions[0])
   m = r_sentence.match(defn)
   if not m: 
      return None
   sentence = m.group(0)

   # try: 
   #    sentence = unicode(sentence, 'iso-8859-1')
   #    sentence = sentence.encode('utf-8')
   # except: pass
   sentence = web.decode(sentence)

   maxlength = 275
   if len(sentence) > maxlength: 
      sentence = sentence[:maxlength]
      words = sentence[:-5].split(' ')
      words.pop()
      sentence = ' '.join(words) + ' [...]'

   sentence = '"' + sentence.replace('"', "'") + '"'
   return sentence + ' - ' + ('http://etymonline.com/index.php?term=%s' % web.urllib.quote(word))
Пример #39
0
def etymology(word): 
   """Returns the historical information (usually) for a word"""
   
   if len(word) > 25: 
      raise ValueError("Word too long: %s[...]" % word[:10])
   word = {'axe': 'ax/axe'}.get(word, word)

   grab = urllib._urlopener
   urllib._urlopener = Grab()
   urllib._urlopener.addheader("Referer", "http://www.etymonline.com/")
   bytes = web.get(etyuri % web.urllib.quote(word))
   urllib._urlopener = grab
   definitions = r_definition.findall(bytes)

   if not definitions: 
      return None

   defn = text(definitions[0])
   m = r_sentence.match(defn)
   if not m: 
      return None
   sentence = m.group(0)

   # try: 
   #    sentence = unicode(sentence, 'iso-8859-1')
   #    sentence = sentence.encode('utf-8')
   # except: pass
   sentence = web.decode(sentence)

   maxlength = 275
   if len(sentence) > maxlength: 
      sentence = sentence[:maxlength]
      words = sentence[:-5].split(' ')
      words.pop()
      sentence = ' '.join(words) + ' [...]'

   sentence = '"' + sentence.replace('"', "'") + '"'
   return sentence + ' - etymonline.com'
Пример #40
0
def etymology(word):
    """Returns the historical information (usually) for a word"""

    if len(word) > 25:
        raise ValueError("Word too long: %s[...]" % word[:10])
    word = {'axe': 'ax/axe'}.get(word, word)

    grab = urllib._urlopener
    urllib._urlopener = Grab()
    urllib._urlopener.addheader("Referer", "http://www.etymonline.com/")
    bytes = web.get(etyuri % web.urllib.quote(word))
    urllib._urlopener = grab
    definitions = r_definition.findall(bytes)

    if not definitions:
        return None

    defn = text(definitions[0])
    m = r_sentence.match(defn)
    if not m:
        return None
    sentence = m.group(0)

    # try:
    #    sentence = unicode(sentence, 'iso-8859-1')
    #    sentence = sentence.encode('utf-8')
    # except: pass
    sentence = web.decode(sentence)

    maxlength = 275
    if len(sentence) > maxlength:
        sentence = sentence[:maxlength]
        words = sentence[:-5].split(' ')
        words.pop()
        sentence = ' '.join(words) + ' [...]'

    sentence = '"' + sentence.replace('"', "'") + '"'
    return sentence + ' - etymonline.com'
Пример #41
0
def tr(jenni, input):
    """Translates a phrase, with optional languages parameter."""
    if not input.group(2): return jenni.say("No input provided.")
    try:
        abc = input.group(2).split(' -')[2]
        command = input.group(2).split(' -')[0].encode('utf-8')
        args = [input.group(2).split(' -')[1], input.group(2).split(' -')[2]]
    except:
        command = input.group(2).encode('utf-8')
        args = ['auto', 'en']

    def langcode(p):
        return p.startswith(':') and (2 < len(p) < 10) and p[1:].isalpha()

    for i in xrange(2):
        if not ' ' in command: break
        prefix, cmd = command.split(' ', 1)
        if langcode(prefix):
            args[i] = prefix[1:]
            command = cmd
    phrase = command

    if (len(phrase) > 350) and (not input.admin):
        return jenni.reply('Phrase must be under 350 characters.')

    src, dest = args
    if src != dest:
        msg, src = translate(phrase, src, dest)
        if isinstance(msg, str):
            msg = msg.decode('utf-8')
        if msg:
            msg = web.decode(msg) # msg.replace('&#39;', "'")
            msg = '"%s" (%s to %s, translate.google.com)' % (msg, src, dest)
        else: msg = 'The %s to %s translation failed, sorry!' % (src, dest)

        jenni.reply(msg)
    else: jenni.reply('Language guessing failed, so try suggesting one!')
Пример #42
0
def calc(code, input):
    """Google calculator."""
    if not input.group(2):
        return code.reply(code.color('red', 'Nothing to calculate.'))
    q = input.group(2).encode('utf-8')
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0
    uri = 'http://www.google.com/ig/calculator?q='
    bytes = web.get(uri + web.urllib.quote(q))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer:
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = answer.decode('utf-8')
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        answer.encode('ascii', 'ignore')
        #if any(c.isalpha() for c in answer):
        try:
            #firstchar = re.search(r'(\d )+ (.*)',answer)
            fletter = next(i for i, c in enumerate(answer) if c.isalpha())
            number = answer[0:fletter - 1]
            words = answer[fletter:len(answer)]
            number.strip()
            cnumb = number.join(number.split())
            words = ' ' + words.strip()
            #[17:02:55] <Avaris> Liam-: next(i for i, c in enumerate(s) if c.isalpha())
            #[17:03:59] <Avaris> (throws StopIteration if there is no letter in the original string)
            code.say(code.bold(cnumb) + code.color('blue', words))
        except:
            answer.strip()
            code.say(answer)
    else:
        code.say(code.color('red', 'Sorry, no result.'))
Пример #43
0
def irb(phenny, input):
    query = input.group(2).encode('utf-8')
    query = "p begin\n  %s\nrescue Exception\n  puts \"#{$!} (#{$!.class})\"\n  $stdout.flush\n  raise e\nend" % query
    uri = 'https://eval.in/'
    data = {"utf8": "\xce\xbb", "execute": "on", "private": "on", "lang": "ruby/mri-2.0.0",
        "input": "", "code": query}
    raw_answer, furl = web.post_with_url(uri, data)
    try:
        _, _, answer = raw_answer.partition("<h2>Program Output</h2>")
        answer = answer.lstrip()
        answer = answer[5: answer.index("</pre>")]
        answer = web.decode(answer).rstrip()
        lines = answer.split("\n")
    except ValueError as e:
      phenny.notice(input.nick, "ValueError " + str(e) + ": " + answer[:100])
    if input.nick not in phenny.ident_admin:
        if len(answer) > 150: return phenny.notice(input.nick,input.nick + ": F**k off. You're not funny, you're not cool. Nobody likes you.")
    if answer:
        sep = " ... " if len(lines) > 1 else " "
        answer = ''.join((lines[0], sep, "(", furl, ")"))
        if input.nick in phenny.ident_admin:
            phenny.say(answer)
        elif (time.time() - (irb.lastused + irb.throttle)) > 30:
            irb.throttle = 2
            irb.lastused = time.time()
            irb.warned = False
            phenny.say(answer)
        elif (time.time() - irb.lastused) > irb.throttle:
            irb.throttle = 2*irb.throttle
            irb.lastused = time.time()
            irb.warned = False
            phenny.say(answer)
        elif not irb.warned:
            irb.warned = True
            phenny.say(".irb has been throttled: limit 1 use per " + str(irb.throttle) + " seconds")
        else: return
    else: phenny.reply('Sorry, no result.')
    def gcalc(self, irc, msg, args, expression):
        """Google calculator."""
        expression = ' '.join(expression)

        q = expression.encode('utf-8')
        q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
        q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
        uri = 'http://www.google.com/ig/calculator?q='
        bytes = web.get(uri + web.urllib.quote(q))
        parts = bytes.split('",')
        answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
        if not answer:
            irc.reply('Sorry, no result.')
            return

        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = answer.decode('utf-8')
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        irc.reply(answer)
        return
Пример #45
0
def calc(code, input): 
   """Google calculator."""
   if not input.group(2):
      return code.reply(code.color('red', 'Nothing to calculate.'))
   q = input.group(2).encode('utf-8')
   q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
   q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
   uri = 'http://www.google.com/ig/calculator?q='
   bytes = web.get(uri + web.urllib.quote(q))
   parts = bytes.split('",')
   answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
   if answer: 
      answer = answer.decode('unicode-escape')
      answer = ''.join(chr(ord(c)) for c in answer)
      answer = answer.decode('utf-8')
      answer = answer.replace(u'\xc2\xa0', ',')
      answer = answer.replace('<sup>', '^(')
      answer = answer.replace('</sup>', ')')
      answer = web.decode(answer)
      answer.encode('ascii','ignore')
      #if any(c.isalpha() for c in answer):
      try:
          #firstchar = re.search(r'(\d )+ (.*)',answer)
          fletter = next(i for i, c in enumerate(answer) if c.isalpha())
          number = answer[0:fletter-1]
          words = answer[fletter:len(answer)]
          number.strip()
          cnumb = number.join(number.split())
          words = ' ' + words.strip()
          #[17:02:55] <Avaris> Liam-: next(i for i, c in enumerate(s) if c.isalpha())
          #[17:03:59] <Avaris> (throws StopIteration if there is no letter in the original string)
          code.say(code.bold(cnumb) + code.color('blue', words))
      except:
          answer.strip()
          code.say(answer)
   else: code.say(code.color('red', 'Sorry, no result.'))
Пример #46
0
def c(phenny, input): 
    """Google calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2).encode('utf-8')
    q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0
    if "wiggie" in q:
        return phenny.say(wiggie(q))
    uri = 'http://www.google.com/ig/calculator?q='

    addon=""
    if not "to" in q and re.search("m$",q,re.IGNORECASE):
        addon =' to feet'
    if not "to" in q and re.search("km$",q,re.IGNORECASE):
        addon =' to miles'
    if not "to" in q and re.search("c$",q,re.IGNORECASE):
        addon =' to fahrenheit'
    if not "to" in q and re.search("f$",q,re.IGNORECASE):
        addon =' to celsius'
    print uri
    bytes = web.get(uri + web.urllib.quote(q+addon))
    parts = bytes.split('",')
    answer = [p for p in parts if p.startswith('rhs: "')][0][6:]
    if answer: 
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = answer.decode('utf-8')
        answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('<sub>', '_(')
        answer = answer.replace('</sub>', ')_')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        phenny.say(answer)
    else: phenny.say('Sorry, no result.')
Пример #47
0
def c(jenni, input):
    '''.c -- Google calculator.'''

    ## let's not bother if someone doesn't give us input
    if not input.group(2):
        return jenni.reply('Nothing to calculate.')

    ## handle some unicode conversions
    q = input.group(2).encode('utf-8')
    q = q.replace('\xcf\x95', 'phi')  # utf-8 U+03D5
    q = q.replace('\xcf\x80', 'pi')  # utf-8 U+03C0

    ## Attempt #1 (Google)
    uri = 'https://www.google.com/search?gbv=1&q='
    uri += web.urllib.quote(q)

    ## To the webs!
    try:
        page = web.get(uri)
    except:
        ## if we can't access Google for calculating
        ## let us move on to Attempt #2
        page = None
        answer = None

    if page:
        ## if we get a response from Google
        ## let us parse out an equation from Google Search results
        answer = c_answer.findall(page)

    if answer:
        ## if the regex finding found a match we want the first result
        answer = answer[0]
        #answer = answer.replace(u'\xc2\xa0', ',')
        answer = answer.decode('unicode-escape')
        answer = ''.join(chr(ord(c)) for c in answer)
        answer = uc.decode(answer)
        answer = answer.replace('<sup>', '^(')
        answer = answer.replace('</sup>', ')')
        answer = web.decode(answer)
        answer = answer.strip()
        jenni.say(answer)
    else:
        #### Attempt #2 (DuckDuckGo's API)
        ddg_uri = 'https://api.duckduckgo.com/?format=json&q='
        ddg_uri += urllib.quote(q)

        ## Try to grab page (results)
        ## If page can't be accessed, we shall fail!
        try:
            page = web.get(ddg_uri)
        except:
            page = None

        ## Try to take page source and json-ify it!
        try:
            json_response = json.loads(page)
        except:
            ## if it can't be json-ified, then we shall fail!
            json_response = None

        ## Check for 'AnswerType' (stolen from search.py)
        ## Also 'fail' to None so we can move on to Attempt #3
        if (not json_response) or (hasattr(json_response, 'AnswerType')
                                   and json_response['AnswerType'] != 'calc'):
            answer = None
        else:
            ## If the json contains an Answer that is the result of 'calc'
            ## then continue
            answer = re.sub(r'\<.*?\>', '', json_response['Answer']).strip()

        if answer:
            ## If we have found answer with Attempt #2
            ## go ahead and display it
            jenni.say(answer)
        else:
            #### Attempt #3 (DuckDuckGo's HTML)
            ## This relies on BeautifulSoup; if it can't be found, don't even bother
            try:
                from BeautifulSoup import BeautifulSoup
            except:
                return jenni.say(
                    'No results. (Please install BeautifulSoup for additional checking.)'
                )

            ddg_html_page = web.get(
                'https://duckduckgo.com/html/?q=%s&kl=us-en&kp=-1' %
                (web.urllib.quote(q)))
            soup = BeautifulSoup(ddg_html_page)

            ## use BeautifulSoup to parse HTML for an answer
            zero_click = str()
            if soup('div', {'class': 'zero-click-result'}):
                zero_click = str(
                    soup('div', {'class': 'zero-click-result'})[0])

            ## remove some excess text
            output = r_tag.sub('', zero_click).strip()
            output = output.replace('\n', '').replace('\t', '')

            ## test to see if the search module has 'remove_spaces'
            ## otherwise, let us fail
            try:
                output = search.remove_spaces(output)
            except:
                output = str()

            if output:
                ## If Attempt #3 worked, display the answer
                jenni.say(output)
            else:
                ## If we made it this far, we have tried all available resources
                jenni.say('Absolutely no results!')
Пример #48
0
def google_search(query):
    bytes = generic_google(query)
    m = r_google.search(bytes)
    if m:
        uri = web.decode(m.group(1))
        return web.unquote(uri)
Пример #49
0
def duck_sanitize(incoming):
    return web.decode((incoming).decode('utf-8'))