Ejemplo n.º 1
0
async def ascii2d(bot: Bot, purl: str):
    print(ascii2dUrl + "search/url/" + purl)
    async with bot.config.session.get(ascii2dUrl + "search/url/" +
                                      purl) as resp:
        if resp.status != 200:
            return "错误:" + str(resp.status)
        resUrl = str(resp.url)
        logger.debug("接收到:" + resUrl)
    resUrl = resUrl.replace("/color/", "/bovw/")
    print(resUrl)

    async with bot.config.session.get(resUrl) as resp:
        if resp.status != 200:
            return "错误:" + str(resp.status)
        content = await resp.read()
        sp = BeautifulSoup(content, "lxml")

        res = sp.find_all("div", class_="row item-box")

        title, source = None, None
        flg = 1
        for item in res:
            if flg == 1:
                flg = 0
                continue
            thumbnail = cq.image(ascii2dUrl +
                                 item.find("img", loading="lazy")["src"])
            h6 = item.find("h6")
            if h6:
                title, author = [i.text for i in h6.find_all("a")]
                source = h6.find("a")["href"]
                site = h6.find("small").text.strip()
                break
        if title == None:
            title = author = source = site = "🈚️"
            thumbnail = cq.image(purl)
        if "pixiv" in source:
            fd = re.search(r"/[0-9]+", source)
            _id = source[fd.start() + 1:fd.end()]
            pixiv = _id
            logger.debug("搜索到 " + pixiv)
        else:
            pixiv = None
            _id = None

    if pixiv:
        try:
            pixiv = await getPixivDetail(bot.config.session, _id)
            pixiv = pixiv["tags"]
        except:
            pixiv = False

    return (thumbnail + f"\n标题:" + title + "\n作者:" + author +
            (("\ntags: {}".format("、".join(pixiv))) if pixiv else "") +
            (("\npixiv id: {}".format(_id)) if pixiv != None else "") +
            "\n来源:" + site +
            (f"\n网址:{hourse(source) if source != '🈚️' else source}"
             if pixiv == None else ""))
Ejemplo n.º 2
0
async def catPixiv(bot: Bot, _id: int, p=None, **kwargs):
    data = {"p": _id}
    async with bot.config.session.post("https://api.pixiv.cat/v1/generate",
                                       json=data) as resp:
        if resp.status != 200:
            return ["网络错误:" + str(resp.status)]
        ShitJson = await resp.json()
        if ShitJson["success"]:
            total = len(
                ShitJson["original_urls"]) if ShitJson["multiple"] else 1
        else:
            return [ShitJson["error"]]
    if p != None:
        if p == "*":
            if total > 1:
                return ["这是一个有 {} 页的pid!".format(total)] + [
                    "https://pixiv.cat/{}-{}.jpg".format(_id, i)
                    for i in range(1, total + 1)
                ]
            else:
                return [cq.image("https://pixiv.cat/{}.jpg".format(_id))]
        elif p > 0 and p <= total:
            return [
                "https://pixiv.cat/{}-{}.jpg".format(_id, p)
                if total > 1 else "https://pixiv.cat/{}.jpg".format(_id)
            ]
        else:
            return ["页数不对哦~~ 这个 id 只有 {} 页".format(total)]
    if total > 1:
        return ["这是一个有多页的pid!", "https://pixiv.cat/{}-1.jpg".format(_id)]
    else:
        return ["https://pixiv.cat/{}.jpg".format(_id)]
Ejemplo n.º 3
0
async def getSetuLow(sess, r18: bool) -> str:
    random.seed(datetime.datetime.now())
    async with sess.get(
            "https://cdn.jsdelivr.net/gh/ipchi9012/setu_pics@latest/setu{}_index.js"
            .format("_r18" if r18 else "")) as resp:
        if resp.status != 200:
            return "网络错误:" + str(resp.status)
        ShitText = await resp.text()
        ind1, ind2 = ShitText.index("("), ShitText.index(")")
        ShitText = ShitText[ind1 + 1:ind2]
        ShitList = json.loads(ShitText)
        ch = random.choice(ShitList)

    async with sess.get(
            "https://cdn.jsdelivr.net/gh/ipchi9012/setu_pics@latest/{}.js".
            format(ch)) as resp:
        if resp.status != 200:
            return "网络错误:" + str(resp.status)
        ShitText = await resp.text()
        ind1 = ShitText.index("(")
        ShitText = ShitText[ind1 + 1:-1]
        ShitList = json.loads(ShitText)
        ch = random.choice(ShitList)
        return cq.image(
            "https://cdn.jsdelivr.net/gh/ipchi9012/setu_pics@latest/" +
            ch["path"])
Ejemplo n.º 4
0
async def catPixiv(bot: Bot, _id: int, p=None, **kwargs):
    ShitJson = await getPixivDetail(bot.config.session, _id)
    try:
        total = ShitJson["page_count"]
    except:
        return [ShitJson]
    if p != None:
        if p == "*":
            if total > 1:
                return ["这是一个有 {} 页的pid!".format(total)] + [
                    "https://pixiv.cat/{}-{}.jpg".format(_id, i)
                    for i in range(1, total + 1)
                ]
            else:
                return [cq.image("https://pixiv.cat/{}.jpg".format(_id))]
        elif p > 0 and p <= total:
            return [
                "https://pixiv.cat/{}-{}.jpg".format(_id, p)
                if total > 1 else "https://pixiv.cat/{}.jpg".format(_id)
            ]
        else:
            return ["页数不对哦~~ 这个 id 只有 {} 页".format(total)]
    if total > 1:
        return ["这是一个有多页的pid!", "https://pixiv.cat/{}-1.jpg".format(_id)]
    else:
        return ["https://pixiv.cat/{}.jpg".format(_id)]
Ejemplo n.º 5
0
async def backup():
    bot = get_bot()
    await bot.send_group_msg(
        group_id=383647564,
        message=cq.at("all") + """٩( °༥° )و ₎₎能动手就别吵吵
开始击剑了,兄弟萌!!淦死野人!!""" + cq.image("a.gif"),
    )
Ejemplo n.º 6
0
async def getImage(session: ClientSession, url: str, dir: str = "", **kwargs):
    fd = re.search(r"\?", url)
    if len(dir) > 0 and dir[-1] != "/":
        dir += "/"
    if fd != None:
        url = url[:fd.span()[0]]
    _, pic = path.split(url)
    pic = dir + pic
    if path.exists(nonebot.get_driver().config.imgpath + pic):
        logger.info("发送缓存图片{}".format(pic))
        return cq.image(pic)
    async with session.get(url, **kwargs) as resp:
        if resp.status != 200:
            logger.error("下载图片失败,网络错误 {}。".format(resp.status))
            return "下载图片失败,网络错误 {}。".format(resp.status)

        img = await resp.read()
        with open(nonebot.get_driver().config.imgpath + pic, "wb") as fl:
            fl.write(img)
        logger.info("已保存图片{}".format(pic))
        return cq.image('file://' + nonebot.get_driver().config.imgpath + pic)
Ejemplo n.º 7
0
async def searchPic(bot: Bot, key_word: str, maxSanityLevel: int = 4):
    datas = {
        "keyword": key_word,
        "pageSize": 6,
        "page": 1,
        "searchType": "original",
        "illustType": "illust",
        "maxSanityLevel": maxSanityLevel,
    }
    if headers["Authorization"] == "" and os.path.exists(
            os.path.join(os.path.dirname(__file__), "a.txt")):
        with open(os.path.join(os.path.dirname(__file__), "a.txt"), "r") as fl:
            headers["Authorization"] = fl.read()
    async with bot.config.session.get(pixivicurl + "illustrations",
                                      params=datas,
                                      headers=headers) as resp:
        if resp.status != 200:
            return (
                f"网络 {resp.status} 错误哦,咕噜灵波~(∠・ω< )⌒★\n\n如果是401错误,请回复 login 来帮忙识别一下验证🐎哦",
                0,
            )
        ShitJson = await resp.json()
    _id = None
    res = f"暂时没有 {key_word} 的结果哦~"
    try:
        Good = [ind for ind in range(0, len(ShitJson["data"]))]
        while len(Good) != 0:
            pic = random.choice(ShitJson["data"])
            res = await getImage(bot.config.session,
                                 imageProxy(pic["imageUrls"][0]["large"]))
            if "失败" in res:
                if "404" in res:
                    ShitJson["data"].remove(pic)
                    continue
                else:
                    res = cq.image(imageProxy_cat(
                        pic["imageUrls"][0]["large"]))
            _id = pic["id"]
            break
    except Exception as e:
        pass
    if _id == None:
        res = f"暂时没有 {key_word} 的结果哦~"
    return (
        res,
        _id if _id != None else res,
    )
Ejemplo n.º 8
0
async def sauce(bot: Bot, purl: str) -> str:
    parm = {
        "db": "999",
        "output_type": "2",
        "numres": "3",
        "url": None,
        "api_key": bot.config.saucekey,
    }
    parm["url"] = purl

    async with bot.config.session.get(sauceUrl, params=parm,
                                      headers=headers) as resp:
        if resp.status != 200:
            return "错误:" + str(resp.status)
        ShitJson = await resp.json()

    if len(ShitJson["results"]) == 0:
        return "啥也没搜到"

    try:
        murl = hourse(ShitJson["results"][0]["data"]["ext_urls"][0])
    except:
        murl = ""

    return (
        cq.image(ShitJson["results"][0]["header"]["thumbnail"]) +
        (f"\n标题:{ShitJson['results'][0]['data']['title']}"
         if "title" in ShitJson["results"][0]["data"] else "") +
        (f"\nsource:{ShitJson['results'][0]['data']['source']}"
         if "source" in ShitJson["results"][0]["data"]
         and "http" != ShitJson["results"][0]["data"]["source"][:4] else "") +
        (f"\n日文名:{ShitJson['results'][0]['data']['jp_name']}"
         if "jp_name" in ShitJson["results"][0]["data"] else "") +
        (f"\n作者:{ShitJson['results'][0]['data']['creator']}"
         if "creator" in ShitJson["results"][0]["data"] else "") +
        ((f"\n素材:{ShitJson['results'][0]['data']['material']}"
          if "material" in ShitJson["results"][0]["data"] else "") +
         (f"\n角色:{ShitJson['results'][0]['data']['characters']}"
          if "characters" in ShitJson["results"][0]["data"] else "")
         if False else "") +
        (f"\npixiv id: {ShitJson['results'][0]['data']['pixiv_id']}\n画师: {ShitJson['results'][0]['data']['member_name']}\n画师id: {ShitJson['results'][0]['data']['member_id']}"
         if "pixiv_id" in ShitJson["results"][0]["data"] else "") +
        ((f"\n网址(请复制到浏览器中打开,不要直接打开):\n{murl}" if murl != "" else "")
         if "pixiv_id" not in ShitJson["results"][0]["data"] else "") +
        "\n相似度:" + str(ShitJson["results"][0]["header"]["similarity"]) + "%")
Ejemplo n.º 9
0
async def catPixiv(bot: Bot, _id: int, p=None, **kwargs):
    data = {"illustId": _id}
    """
    async with bot.config.session.post(
        "https://api.pixiv.cat/v1/generate", json=data
    ) as resp:
        if resp.status != 200:
            return ["网络错误:" + str(resp.status)]
        ShitJson = await resp.json()
        if ShitJson["success"]:
            total = len(ShitJson["original_urls"]) if ShitJson["multiple"] else 1
        else:
            return [ShitJson["error"]]
    """
    if headers["Authorization"] == "" and os.path.exists(
            os.path.join(os.path.dirname(__file__), "st", "a.txt")):
        with open(os.path.join(os.path.dirname(__file__), "st", "a.txt"),
                  "r") as fl:
            headers["Authorization"] = fl.read()
    async with bot.config.session.get(pixivicurl + f"illusts/{_id}",
                                      headers=headers) as resp:
        if resp.status != 200:
            return ["网络错误:" + str(resp.status)]
        ShitJson = await resp.json()
        total = ShitJson["data"]["pageCount"]
    if p != None:
        if p == "*":
            if total > 1:
                return ["这是一个有 {} 页的pid!".format(total)] + [
                    "https://pixiv.re/{}-{}.jpg".format(_id, i)
                    for i in range(1, total + 1)
                ]
            else:
                return [cq.image("https://pixiv.re/{}.jpg".format(_id))]
        elif p > 0 and p <= total:
            return [
                "https://pixiv.re/{}-{}.jpg".format(_id, p)
                if total > 1 else "https://pixiv.re/{}.jpg".format(_id)
            ]
        else:
            return ["页数不对哦~~ 这个 id 只有 {} 页".format(total)]
    if total > 1:
        return ["这是一个有多页的pid!", "https://pixiv.re/{}-1.jpg".format(_id)]
    else:
        return ["https://pixiv.re/{}.jpg".format(_id)]
Ejemplo n.º 10
0
async def handleOverCall(bot: Bot, api, r18, ShitJson: dict = None, now=None):
    if ShitJson:
        overCall[api] = (ShitJson["quota_min_ttl"], now)
    cache = [
        "pixiv/" + ("r18/" if r18 else "") + pic.name
        for pic in os.scandir(bot.config.imgpath + "pixiv/" +
                              ("r18" if r18 else "")) if pic.is_file()
    ]
    pic = random.choice(cache)
    fd = re.search("/\d+", pic)
    _id = pic[fd.start() + 1:fd.end()]
    text = f"现在是缓存时间哦!\n距离下一次在线请求还剩 {overCall[api][0]-(datetime.datetime.now()-overCall[api][1]).seconds+1} 秒。"
    logger.info(re.sub("\n", "", text))
    try:
        text = await getPixivDetail(bot.config.session, _id)
    except:
        pass
    return cq.image(pic), text
Ejemplo n.º 11
0
async def pixiv(mode: str = "day"):
    searchapi = r"https://api.imjad.cn/pixiv/v2/"

    now = datetime.now(pytz.timezone("Asia/Shanghai"))

    retry = 3

    now -= timedelta(days=2)

    ress = [([f"在尝试 {retry} 遍之后,还是没有爬到图片呢。。。"], "Grab Rss Error!", "", "")]

    datas = {"mode": mode, "type": "rank", "date": now.strftime("%Y-%m-%d")}

    sess = nonebot.get_driver().config.session
    ShitJson = {}

    while retry != 0:
        async with sess.get(searchapi, params=datas) as resp:
            if resp.status != 200:
                return "网络错误哦,咕噜灵波~(∠・ω< )⌒★"
            ShitJson = await resp.json()
            if "illusts" in ShitJson:
                break
            await asyncio.sleep(1)
        retry -= 1
    if "illusts" not in ShitJson:
        return ress

    res = []
    _id = -1
    for item in ShitJson["illusts"]:
        res.append(cq.image(imageProxy(item["image_urls"]["medium"])))
        _id = item["id"]
    ress.append((res, _id, "", ""))

    if len(ress) > 1:
        ress = ress[1:]

    return ress
Ejemplo n.º 12
0
async def getSetuHigh(bot: Bot,
                      r18: bool,
                      keyword: str = "",
                      is_save: bool = True) -> str:
    random.seed(datetime.datetime.now())
    LoliUrl = r"https://api.lolicon.app/setu/"
    parm = {"apikey": None, "r18": "1", "size1200": "true", "num": 2}
    if keyword != "":
        parm["keyword"] = keyword
    if r18:
        parm["r18"] = 1
    else:
        parm["r18"] = 0
    OverCalled = True
    RequestApi = None
    if bot.config.loliapi:
        RequestApi = bot.config.loliapi
        OverCalled = False
        logger.debug("检测到 Lolicon API !")
        if bot.config.loliapi in overCall:
            logger.debug(
                f"时间差 {(datetime.datetime.now()-overCall[RequestApi][1]).seconds} 秒。距离下一次在线请求还剩 {overCall[RequestApi][0]-(datetime.datetime.now()-overCall[RequestApi][1]).seconds+1} 秒。"
            )
            if (datetime.datetime.now() - overCall[RequestApi][1]
                ).seconds <= overCall[RequestApi][0]:
                logger.debug("主动截断!")
                OverCalled = True

    if bot.config.loliapis and OverCalled:
        logger.debug("检测到多个 Lolicon API !")
        for api in bot.config.loliapis:
            RequestApi = api
            OverCalled = False
            if api in overCall:
                logger.debug(
                    f"时间差 {(datetime.datetime.now()-overCall[api][1]).seconds} 秒。距离下一次在线请求还剩 {overCall[api][0]-(datetime.datetime.now()-overCall[api][1]).seconds+1} 秒。"
                )
                if (datetime.datetime.now() -
                        overCall[api][1]).seconds <= overCall[api][0]:
                    logger.debug("主动截断!")
                    OverCalled = True
                else:
                    break

    if OverCalled:
        return await handleOverCall(bot, RequestApi, r18)
    if RequestApi:
        parm["apikey"] = RequestApi
    else:
        logger.warning("未检测到 LoliconAPI 的配置!涩图请求可能受限!")
        parm["num"] = 1
    now = datetime.datetime.now()
    async with bot.config.session.get(LoliUrl, params=parm) as resp:
        if resp.status != 200:
            return None, "网络错误:" + str(resp.status)
        ShitJson = await resp.json()
        if ShitJson["quota"] == 0:
            return await handleOverCall(bot, bot.config.loliapi, r18, ShitJson,
                                        now)
        if len(ShitJson["data"]) == 0:
            return None, f"没有搜到关于 {keyword} 的涩图哦。。。"
        if is_save:
            pic = await getImage(
                bot.config.session,
                ShitJson["data"][0]["url"],
                f"pixiv{'/r18' if r18 else '/'}",
            )
        else:
            pic = cq.image(ShitJson["data"][0]["url"])

        ShitJson["data"][0]["tags"] = [
            "#" + i for i in ShitJson["data"][0]["tags"]
        ]
        loop = asyncio.get_event_loop()
        for item in ShitJson["data"]:
            asyncio.run_coroutine_threadsafe(
                getImage(
                    bot.config.session,
                    item["url"],
                    f"pixiv{'/r18' if r18 else '/'}",
                ),
                loop,
            )

        return pic, ShitJson["data"][0]
Ejemplo n.º 13
0
async def firsthandle(bot: Bot, event: Event, state: dict):
    await act.finish(unescape(cq.image("activity.jpg")))
Ejemplo n.º 14
0
        if _id == -1:
            await st.finish("暂时没有搜索到关于 {} 的结果哦~~".format(state["keyword"]))


login = on_command("login")


@login.handle()
async def _(bot: Bot, event: Event, state: dict):
    async with bot.config.session.get(pixivicurl + "verificationCode") as resp:
        if resp.status != 200:
            await login.finish("获取验证码失败")
        ShitJson = await resp.json()
        img = ShitJson["data"]["imageBase64"]
        vid = ShitJson["data"]["vid"]
        state["imageBase64"] = img
        state["vid"] = vid


@login.got("img", prompt=cq.image("base64://{imageBase64}"))
async def _(bot: Bot, event: Event, state: dict):
    msg = str(event.message).strip()
    if msg:
        state["img"] = msg
    q = {"vid": state["vid"], "value": state["img"]}
    parm = {"username": bot.config.username, "password": bot.config.password}

    res = await auth(bot, state, params=q, json=parm)

    await login.send(cq.reply(event.id) + "正确!" if "ok" == res else res)