示例#1
0
async def _fetch(bot, args):
    """fetch data from wolframalpha and parse the response

    Args:
        bot: HangupsBot instance
        args: tuple of string, query for wolframalpha

    Returns:
        string, the parsed result or an error message
    """
    if not args:
        return _("You need to ask WolframAlpha a question")

    query = ' '.join(args)
    parameters = {'appid': _api_token(bot), 'input': query}

    async with aiohttp.ClientSession() as session:
        async with session.get(API_URL, params=parameters) as resp:
            body = await resp.read()

    result = wolframalpha.Result(body)
    if not result.get('@success'):
        return _('Bad request!')

    if not result.get('pod'):
        return _('Bad response from WolframAlpha, retry or change your query!')

    html = ['WolframAlpha solved the query <b>"{}"</b>\n'.format(query)]

    has_content = False
    try:
        for pod in result.pods:
            if pod.title:
                html.append("<b>{}:</b> ".format(pod.title))

            if pod.text and pod.text.strip():
                html.append(pod.text.strip())
                has_content = True
            elif 'subpod' in pod:
                for subpod in pod.subpods:
                    if 'img' in subpod:
                        html.append(
                            _("%s") % (subpod['img'].get('@src')
                                       or subpod['img'].get('@alt')))
                        has_content = True
    except AttributeError:
        # API Change
        html.append("\n...")

    if has_content:
        return '\n'.join(html)

    return _("<i>Wolfram Alpha did not return any useful data</i>")
示例#2
0
 def query(self, query):
     """
     Query Wolfram|Alpha with query using the v2.0 API
     """
     identity = IdentityManager().get()
     bearer_token = 'Bearer %s:%s' % (identity.device_id, identity.token)
     query = urllib.parse.urlencode(dict(input=query))
     url = 'https://cerberus.mycroft.ai/wolframalpha/v2/query?' + query
     headers = {'Authorization': bearer_token}
     response = requests.get(url, headers=headers)
     if response.status_code == 401:
         raise CerberusAccessDenied()
     return wolframalpha.Result(StringIO(response.content))
示例#3
0
    async def query(self, input, params=(), **kwargs):
        data = dict(
            input=input,
            appid=self.app_id,
        )
        data = itertools.chain(params, data.items(), kwargs.items())

        query = urllib.parse.urlencode(tuple(data))
        url = 'https://api.wolframalpha.com/v2/query?' + query

        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                r = await resp.text()
                return wolframalpha.Result(r)
示例#4
0
 def create_did_you_mean(self, text):
     test = self.format_did_you_mean(text)
     return wolframalpha.Result(StringIO(test))
示例#5
0
 def create_result(self, pod_id, value, pod_num):
     result = self.format_result(pod_id, value, pod_num)
     return wolframalpha.Result(StringIO(result))
 def query(self, input):
     data = self.request({"query": {"input": input}})
     return wolframalpha.Result(StringIO(data.content))
示例#7
0
 def create_result(self, pod_title, value):
     result = self.format_result(pod_title, value)
     return wolframalpha.Result(StringIO(result))
 def query(self, input):
     data = self.request({"query": {"input": input}})
     if sys.version_info[0] < 3:
         return wolframalpha.Result(StringIO(data.content))
     else:
         return wolframalpha.Result(BytesIO(data.content))
示例#9
0
async def query(Bot, msg):

    question = strutils.strip_command(msg.content)
    em = Embed(title=question, description="Requesting Data", colour=0xe4671b)
    oldem = await msgutils.send_embed(Bot, msg, em)
    res = wa_client.query(question)

    if "@pods" not in res:
        try:
            resp = urllib.request.urlopen(res["@recalculate"])
            assert resp.headers.get_content_type() == 'text/xml'
            assert resp.headers.get_param('charset') == 'utf-8'
            res = wolframalpha.Result(resp)
        except ValueError:
            pass

    titles = []
    images = []

    try:

        for pod in res.pods:
            titles.append(textwrap.wrap(pod.title, width=50))
            subimgs = []
            for sub in pod.subpods:
                subimgs.append(
                    Image.open(
                        BytesIO(requests.get(sub['img']['@src']).content)))
            images.append(subimgs)
    except AttributeError:
        em = Embed(title=question, description="No results", colour=0xe4671b)
        await msgutils.edit_embed(Bot, oldem, em)
        return

    chained_imgs = list(itertools.chain.from_iterable(images))

    widths, heights = zip(*(i.size for i in chained_imgs))

    item_padding = 20
    font_size = 15
    font_padding = 3

    max_width = max(widths) + 2 * item_padding
    total_height = sum(heights) + item_padding * (len(chained_imgs) + 2 + len(
        titles)) + (font_padding + font_size) * len(
            list(itertools.chain.from_iterable(titles)))

    new_im = imgutils.round_rectangle((max_width, total_height), item_padding,
                                      "white")

    font = ImageFont.truetype("Data/Roboto-Regular.ttf", font_size)

    total_pods = 0

    draw = ImageDraw.Draw(new_im)
    y_offset = item_padding
    for i in range(len(titles)):
        pod = images[i]
        for line in titles[i]:
            draw.text((item_padding, y_offset),
                      line,
                      fill=(119, 165, 182),
                      font=font)
            y_offset += font_size + font_padding

        y_offset += item_padding
        for im in pod:
            total_pods += 1
            new_im.paste(im, (item_padding, y_offset))
            y_offset += im.size[1] + item_padding
            if (total_pods < len(chained_imgs)):
                draw.line((0, y_offset - item_padding / 2, max_width,
                           y_offset - item_padding / 2),
                          fill=(233, 233, 233),
                          width=1)

    new_im.save("Data/wa_save.png")

    res_img = imgur_client.upload_image("Data/wa_save.png", title=question)

    em = Embed(title=question, url=res_img.link, colour=0xe4671b)
    em.set_image(url=res_img.link)
    await msgutils.edit_embed(Bot, oldem, em)
 def query(self, input, params=()):
     data = self.request({"query": {"input": input, "params": params}})
     return wolframalpha.Result(StringIO(data.content))