Ejemplo n.º 1
0
async def query_text(query):
    q = query.query.split(maxsplit=1)[1]

    wiki = Wikipya("ru")
    search = await wiki.search(q, 3)

    buttons = []
    for item in search:
        page = await wiki.page(item)
        soup = BeautifulSoup(page.text, "lxml")
        text = page.fixed

        btn_defaults = {"id": page.pageid, "title": page.title,
                        "description": soup.text[:100],
                        "thumb_width": 48, "thumb_height": 48,
                        "input_message_content": InputTextMessageContent(
                            message_text=text,
                            parse_mode="HTML"
                        )}

        try:
            img = await page.image(75)
            buttons.append(InlineQueryResultArticle(**btn_defaults,
                                                    thumb_url=img.source))

        except NotFound:
            default_image = locale.default_wiki_image
            buttons.append(InlineQueryResultArticle(**btn_defaults,
                                                    thumb_url=default_image))

    await bot.answer_inline_query(query.id, buttons)
Ejemplo n.º 2
0
async def wikiSearch(message, lang="ru", logs=False):
    opts = message.text.split(maxsplit=1)

    if len(opts) == 1:
        await message.reply(_("errors.enter_wiki_query").format(opts[0]),
                            parse_mode="Markdown")
        return

    query = opts[1]
    print(f"[Wikipedia Search {lang.upper()}] {query}")

    wiki = Wikipya(lang)

    r = await wiki.search(query, 20)

    if r == -1:
        await message.reply(_("error.not_found"))
        return

    text = ""

    for item in r:
        text += bold(fixWords(item.title)) + "\n"
        text += f"└─/w_{item.pageid}\n"

    await message.reply(text, parse_mode="HTML")
Ejemplo n.º 3
0
async def query_text(query):
    params = query.query.split(maxsplit=1)

    q = params[1]
    lang = params[0].split(":", maxsplit=1)
    lang = "ru" if len(lang) == 0 else lang[1]

    if not (lang in LANGS_LIST):
        return

    wiki = Wikipya(lang)

    try:
        search = await wiki.search(q, 3)
    except Exception as e:
        print(e)
        await bot.answer_inline_query(query.id, [
            InlineQueryResultArticle(
                id=0,
                title="При выполнении запроса возникла ошибка",
                description=e,
                input_message_content=InputTextMessageContent(
                    message_text=bold("При выполнении запроса возникла ошибка:") +
                                 code(e),
                    parse_mode="HTML"
                )
            )
        ])

        return

    buttons = []
    for item in search:
        page = await wiki.page(item)
        page.blockList = WIKIPYA_BLOCKLIST
        soup = BeautifulSoup(page.text, "lxml")
        text = page.fixed

        btn_defaults = {"id": page.pageid, "title": page.title,
                        "description": soup.text[:100],
                        "thumb_width": 48, "thumb_height": 48,
                        "input_message_content": InputTextMessageContent(
                            message_text=text,
                            parse_mode="HTML"
                        )}

        try:
            img = await page.image(75)
            buttons.append(InlineQueryResultArticle(**btn_defaults,
                                                    thumb_url=img.source))

        except NotFound:
            default_image = ("https://upload.wikimedia.org/wikipedia"
                             "/commons/thumb/8/80/Wikipedia-logo-v2.svg/"
                             "75px-Wikipedia-logo-v2.svg.png")
            buttons.append(InlineQueryResultArticle(**btn_defaults,
                                                    thumb_url=default_image))

    await bot.answer_inline_query(query.id, buttons)
Ejemplo n.º 4
0
async def wiki(response=None, name=None, lang=None):
    wiki = Wikipya("ru" if lang is None else lang)
    search = await wiki.search(name)

    if search == -1:
        raise NotFound()

    page = await wiki.page(search[0])

    if page == -1:
        text = ""

    elif str(page) == "":
        text = ""

    else:
        page.blockList = [["table", {
            "class": "infobox"
        }], ["ol", {
            "class": "references"
        }], ["link"], ["style"], ["img"], ["div", {
            "class": "tright"
        }], ["table", {
            "class": "noprint"
        }], ["div", {
            "class": "plainlist"
        }], ["table", {
            "class": "sidebar"
        }], ["span", {
            "class": "mw-ext-cite-error"
        }]]
        text = makeBelarus(page.parsed)

    try:
        image = await page.image()
        image = image.source

    except (AttributeError, NotFound):
        image = -1

    if image == WGR_FLAG:
        image = WRW_FLAG

    text = text.replace("<body>", "") \
                .replace("</body>", "") \
                .replace("<html>", "") \
                .replace("</html>", "")

    return {
        "title": makeBelarus(search[0].title),
        "content": text,
        "image_url": image
    }
Ejemplo n.º 5
0
async def query_text(query):
    params = query.query.split(maxsplit=1)

    q = params[1]
    lang = params[0].split(":", maxsplit=1)
    lang = "ru" if len(lang) == 1 else lang[1]

    if not (lang in LANGS_LIST):
        return

    wiki = Wikipya(lang)

    try:
        search = await wiki.search(q, 3)
    except Exception as e:
        print(e)
        await bot.answer_inline_query(query.id, [
            InlineQueryResultArticle(
                id=0,
                title="При выполнении запроса возникла ошибка",
                description=e,
                input_message_content=InputTextMessageContent(
                    message_text=bold("При выполнении запроса возникла ошибка:") +
                                 code(e),
                    parse_mode="HTML"
                )
            )
        ])

        return

    buttons = []

    for item in search:
        page = await wiki.page(item)
        page.blockList = WIKIPYA_BLOCKLIST

        soup = BeautifulSoup(page.text, "lxml")
        text = page.fixed

        btn_defaults = {"id": page.pageid, "title": page.title,
                        "description": soup.text[:100],
                        "input_message_content": InputTextMessageContent(
                            message_text=text,
                            parse_mode="HTML"
                        )}

        buttons.append(InlineQueryResultArticle(**btn_defaults))

    await bot.answer_inline_query(query.id, buttons)
Ejemplo n.º 6
0
async def detect(message):
    text = message.text.replace("/w_", "")
    if text.find("@") != -1:
        text = text.split("@", maxsplit=1)[0]

    w = Wikipya("ru")

    try:
        id_ = int(text)

    except Exception:
        message.reply("id должен быть числом")
        return

    name = await w.getPageName(id_)

    if name == -1:
        await message.reply("Не получилось найти статью по айди")
        return

    await getWiki(message, name=name)
Ejemplo n.º 7
0
async def detect(message):
    text = message.text.replace("/w_", "")
    if text.find("@") != -1:
        text = text.split("@", maxsplit=1)[0]

    w = Wikipya("ru")

    try:
        id_ = int(text)

    except Exception:
        message.reply(_("errors.invalid_post_id"))
        return

    name = await w.getPageName(id_)

    if name == -1:
        await message.reply(_("errors.not_found"))
        return

    await wiki(message, "wikipedia", lang="ru", query=name, version="1.35")
Ejemplo n.º 8
0
async def getWiki(message=None, lang="ru", logs=False, name=None):
    wiki = Wikipya(lang)

    if name is None:
        opts = message.text.split(maxsplit=1)
        if len(opts) == 1:
            await message.reply(_("errors.enter_wiki_query").format(opts[0]),
                                parse_mode="Markdown")
            return

        name = opts[1]

    logging.info(f"[Wikipedia {lang.upper()}] {name}")
    # print(f"[Wikipedia {lang.upper()}] {name}")

    try:
        search = await wiki.search(name)

    except NotFound:
        await message.reply(_("errors.not_found"))
        return

    opensearch = await wiki.opensearch(search[0].title)
    url = opensearch[-1][0]

    page = await wiki.page(search[0])

    if page == -1:
        text = ""

    elif str(page) == "":
        text = ""

    else:
        page.blockList = WIKIPYA_BLOCKLIST
        text = fixWords(page.parsed)

    try:
        image = await page.image()
        image = image.source
    except AttributeError:
        pass
    except NotFound:
        image = -1

    keyboard = types.InlineKeyboardMarkup()

    try:
        name = search[0].title
    except KeyError:
        name = name

    try:
        url
    except NameError:
        url = f"https://{lang}.wikipedia.org/wiki/{name}"

    keyboard.add(types.InlineKeyboardButton(text=_("wiki.read_full"), url=url))

    if type(image) is int:
        await bot.send_chat_action(message.chat.id, "typing")
        try:
            await message.reply(cuteCrop(text, limit=4096),
                                parse_mode="HTML",
                                reply_markup=keyboard)

        except Exception:
            pass

    else:
        if image == WGR_FLAG:
            image = WRW_FLAG

        await bot.send_chat_action(message.chat.id, "upload_photo")

        try:
            await message.reply_photo(image,
                                      caption=cuteCrop(text, limit=1024),
                                      parse_mode="HTML",
                                      reply_markup=keyboard)

        except Exception as e:
            await message.reply(bold(_("errors.error")) + "\n" + code(e),
                                parse_mode="HTML")
Ejemplo n.º 9
0
async def getWiki(message=None, lang="ru", logs=False, name=None):
    wiki = Wikipya(lang)

    if name is None:
        opts = message.text.split(maxsplit=1)
        if len(opts) == 1:
            await message.reply(locale.wikierror.format(opts[0]),
                                parse_mode="Markdown")
            return

        name = opts[1]

    logging.info(f"[Wikipedia {lang.upper()}] {name}")
    # print(f"[Wikipedia {lang.upper()}] {name}")

    try:
        search = await wiki.search(name)

    except NotFound:
        await message.reply("Ничего не найдено")
        return

    opensearch = await wiki.opensearch(search[0].title)
    url = opensearch[-1][0]

    page = await wiki.page(search[0])

    if page == -1:
        text = ""

    elif str(page) == "":
        text = ""

    else:
        page.blockList = [["table", {"class": "infobox"}],
                          ["ol", {"class": "references"}],
                          ["link"], ["style"],
                          ["table", {"class": "noprint"}]]
        text = fixWords(page.parsed)

    try:
        image = await page.image()
        image = image.source
    except AttributeError:
        pass
    except NotFound:
        image = -1

    keyboard = aiogram.types.InlineKeyboardMarkup()

    try:
        name = search[0].title
    except KeyError:
        name = name

    try:
        url
    except NameError:
        url = f"https://{lang}.wikipedia.org/wiki/{name}"

    keyboard.add(aiogram.types.InlineKeyboardButton(text="Читать полностью",
                                                    url=url))

    if type(image) is int:
        await bot.send_chat_action(message.chat.id, "typing")
        try:
            await message.reply(cuteCrop(text, limit=4096), parse_mode="HTML",
                                reply_markup=keyboard)

        except Exception:
            pass

    else:
        if image == WGR_FLAG:
            image = WRW_FLAG

        await bot.send_chat_action(message.chat.id, "upload_photo")

        try:
            await message.reply_photo(image,
                                      caption=cuteCrop(text, limit=1024),
                                      parse_mode="HTML",
                                      reply_markup=keyboard)

        except Exception as e:
            await message.reply(f"*Не удалось отправить статью*\n`{e}`",
                                parse_mode="Markdown")
Ejemplo n.º 10
0
def Wikipedia(lang="ru"):
    return Wikipya(url="https://{lang}.wikipedia.org/w/api.php",
                   lang=lang,
                   version="1.35")
Ejemplo n.º 11
0
async def wiki(message,
               fname,
               url="https://{lang}.wikipedia.org/w/api.php",
               query=None,
               lang=None,
               lurk=False,
               prefix="w",
               **kwargs):
    w = Wikipya(url=url, lang=lang, lurk=lurk, **kwargs)

    try:
        if query is None:
            command, query = message.text.split(maxsplit=1)

        page, image, url = await w.get_all(
            query,
            lurk,
            blocklist=WIKIPYA_BLOCKLIST,
            img_blocklist=kwargs.get("img_blocklist") or (),
            prefix=prefix)
        text = fixWords(page.parsed)

    except NotFound:
        await message.reply(_("errors.not_found"))
        return

    except ValueError:
        await message.reply(_("errors.enter_wiki_query").format(message.text),
                            parse_mode="Markdown")
        return

    soup = BeautifulSoup(text, "lxml")

    i = soup.find_all("i")
    b = soup.find_all("b")

    if len(i) != 0:
        i[0].unwrap()

    if len(b) != 0:
        if url is not None:
            b = b[0]
            b.name = "a"
            b["href"] = url
            b = b.wrap(soup.new_tag("b"))

    text = unbody(soup)

    try:
        if image != -1:
            cropped = cuteCrop(text, limit=1024)

            if cropped == "":
                cropped = text[:1024]

            await bot.send_chat_action(message.chat.id, "upload_photo")
            await message.reply_photo(image,
                                      caption=cropped,
                                      parse_mode="HTML")
        else:
            await message.reply(cuteCrop(text, limit=4096),
                                parse_mode="HTML",
                                disable_web_page_preview=True)

    except Exception as e:
        await message.reply(bold(_("errors.error")) + "\n" + code(e),
                            parse_mode="HTML")
        await message.answer(cuteCrop(text, limit=4096),
                             disable_web_page_preview=True)