Esempio n. 1
0
async def sendpic(session: ClientSession, url: str, **kwargs):
    try:
        fd = re.search(r"\?", url)
        if fd != None:
            url = url[:fd.span()[0]]
        async with session.get(url, **kwargs) as resp:
            if resp.status != 200:
                print(await resp.text("utf-8"))
                return "下载图片失败,网络错误 {}。原因 {}".format(resp.status, await
                                                     resp.text("utf-8"))
            else:
                _, pic = path.split(url)
                if path.splitext(pic)[1] == ".gif":
                    bot = nonebot.get_bot()
                    if not path.exists(bot.config.IMGPATH + pic):
                        with open(bot.config.IMGPATH + pic, "wb") as fl:
                            while True:
                                ck = await resp.content.read(8196)
                                if not ck:
                                    break
                                fl.write(ck)
                    pic = cq.image(pic)
                else:
                    ShitData = await resp.content.read()
                    ShitBase64 = base64.b64encode(ShitData)
                    pic = cq.image("base64://" +
                                   str(ShitBase64, encoding="utf-8"))

        return pic
    except:
        return "下载图片失败"
Esempio n. 2
0
async def sst(session: CommandSession):
    msg = session.current_arg_text.strip()
    if session.event.detail_type == "group":
        safe = await cksafe(session.event.group_id)
    else:
        safe = False
    if ("r18" in msg or "R18" in msg) and not safe:
        parm["r18"] = 1
    else:
        parm["r18"] = 0
    async with aiohttp.ClientSession() as sess:
        async with sess.get(api, params=parm) as resp:
            if resp.status != 200:
                session.finish("网络错误:" + str(resp.status))
            ShitJson = await resp.json()
            if ShitJson["quota"] == 0:
                session.finish(
                    f"返回码:{ShitJson['code']}\napi调用额度已耗尽,距离下一次调用额度恢复还剩 {ShitJson['quota_min_ttl']+1} 秒。"
                )
            data = ShitJson["data"][0]
            _id = await session.send(
                """发送中,。,。,。\npixiv id:{}\ntitle:{}\n作者:{}\ntgas:{}""".format(
                    data["pid"],
                    data["title"],
                    data["author"],
                    "、".join(["#" + i for i in data["tags"]]),
                ),
                at_sender=True,
            )
            print("1232312321")
            print(cq.image(ShitJson["data"][0]["url"]))
            await session.send(cq.image(ShitJson["data"][0]["url"]))
Esempio n. 3
0
async def catPixiv(_id: int, p=None, **kwargs):
    parm = {"id": _id}
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.imjad.cn/pixiv/v2/",
                               params=parm) as resp:
            if resp.status != 200:
                return ["网络错误哦!{}".format(resp.status)]
            ShitJson = await resp.json()
            total = ShitJson["illust"]["page_count"]
        if p != None:
            if p == "*":
                if total > 1:
                    return [
                        "这是一个有多页的pid!",
                        (cq.image("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 [
                    cq.image(
                        "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!",
                cq.image("https://pixiv.cat/{}-1.jpg".format(_id))
            ]
        else:
            return [cq.image("https://pixiv.cat/{}.jpg".format(_id))]
Esempio n. 4
0
async def login(session: CommandSession):
    parm = {"username": bot.config.USERNAME, "password": bot.config.PASSWORD}

    if session.is_first_run:
        async with aiohttp.ClientSession() as sess:
            async with sess.get(pixivicurl + "verificationCode") as resp:
                if resp.status != 200:
                    session.finish("获取验证码失败")
                ShitJson = await resp.json()
                img = ShitJson["data"]["imageBase64"]
                vid = ShitJson["data"]["vid"]
                session.state["imageBase64"] = img
                session.state["vid"] = vid
                session.get("img", prompt=cq.image("base64://" + img))
    q = {"vid": session.state["vid"], "value": session.state["img"]}
    async with aiohttp.ClientSession() as sess:
        async with sess.post(pixivicurl + "users/token", params=q,
                             json=parm) as resp:
            if resp.status != 200:
                session.finish("验证🐎错误!")
            headers["Authorization"] = resp.headers["Authorization"]
            print(resp.headers["Authorization"])
            await session.send(cq.reply(session.event.message_id) + "正确!")
            imgdata = base64.b64decode(session.state["imageBase64"])
            file = open(
                "/root/image/{}.jpg".format(session.state["img"].lower()),
                "wb")
            file.write(imgdata)
            file.close()
Esempio n. 5
0
async def sauce(purl: str) -> str:

    data["url"] = purl

    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=data, 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"] else "") +
        (f"\n日文名:{ShitJson['results'][0]['data']['jp_name']}"
         if "jp_name" in ShitJson["results"][0]["data"] 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 "") +
        "\n相似度:" + str(ShitJson["results"][0]["header"]["similarity"]) + "%")
Esempio n. 6
0
async def getSetu(r18: bool) -> str:
    random.seed(datetime.datetime.now())
    async with aiohttp.ClientSession() as sess:
        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)
            ind1 = random.randint(0, len(ShitList))

        async with sess.get(
                "https://cdn.jsdelivr.net/gh/ipchi9012/setu_pics@latest/{}.js".
                format(ShitList[ind1])) 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)
            ind1 = random.randint(0, len(ShitList))
            return cq.image(
                "https://cdn.jsdelivr.net/gh/ipchi9012/setu_pics@latest/" +
                ShitList[ind1]["path"])
Esempio n. 7
0
async def searchPic(key_word: str, maxSanityLevel: int = 4):
    datas = {
        "keyword": key_word,
        "pageSize": 15,
        "page": 1,
        "searchType": "original",
        "illustType": "illust",
        "maxSanityLevel": maxSanityLevel,
    }
    async with aiohttp.ClientSession() as sess:
        async with sess.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
        Good = [ind for ind in range(0, len(ShitJson["data"]))]
        try:
            while len(Good) != 0:
                pics = ShitJson["data"]
                ind = random.randint(0, len(Good))
                ind = Good[ind]
                res = await sendpic(
                    sess,
                    imageProxy(pics[ind]["imageUrls"][0]["large"],
                               "img.cheerfun.dev"),
                    headers=headers,
                )
                if "失败" in res:
                    if "404" in res:
                        Good.remove(ind)
                        continue
                    else:
                        res = cq.image(
                            imageProxy_cat(pics[ind]["imageUrls"][0]["large"]))
                _id = pics[ind]["id"]
                break
        except KeyError:
            res = f"暂时没有 {key_word} 的结果哦~"
        if _id == None:
            res = f"暂时没有 {key_word} 的结果哦~"
        return (
            res,
            _id if _id != None else res,
        )
Esempio n. 8
0
async def _(session: CommandSession):
    if session.is_first_run:
        return

    if "flg" in session.state:
        if session.current_arg_text == "rl":
            session.state["rl"] = session.current_arg_text
        else:
            if session.state["flg"] == 1:
                session.switch(session.current_arg_text)
            session.finish("套娃结束!" if session.state["flg"] == 0 else None)

    if session.current_arg_text == "r16":
        async with aiohttp.ClientSession() as sess:
            async with sess.get("http://api.rosysun.cn/cos") as resp:
                if resp.status != 200:
                    return "网络错误哦,咕噜灵波~(∠・ω< )⌒★"
                ShitJson = await resp.text()
                await session.send(cq.image(ShitJson + ",cache=0"))
            async with sess.get(
                    "https://api.uomg.com/api/rand.img3?sort=胖次猫&format=json"
            ) as resp:
                if resp.status != 200:
                    return "网络错误哦,咕噜灵波~(∠・ω< )⌒★"
                ShitData = await resp.read()
                ShitData = json.loads(ShitData)
                ShitData = ShitData["imgurl"]
                session.finish(cq.image(ShitData + ",cache=0"))

    elif len(session.current_arg_images) == 0:
        if session.current_arg_text.strip() != "":
            session.state["search"] = session.current_arg_text
        else:
            session.finish("嘛,什么都没输入嘛~~")
    else:
        session.state["url"] = session.current_arg_images[0]
Esempio n. 9
0
async def getRelated(_id, ind=-1):
    datas = {"type": "related", "id": _id}
    random.seed(datetime.datetime.now())
    async with aiohttp.ClientSession() as sess:
        async with sess.get(searchapi, params=datas) as resp:
            if resp.status != 200:
                return "网络错误哦,咕噜灵波~(∠・ω< )⌒★"
            ShitJson = await resp.json()
        if ind == -1 or ind >= len(ShitJson["illusts"]):
            ind = random.randint(0, len(ShitJson["illusts"]))
        try:
            res = cq.image(
                imageProxy(ShitJson["illusts"][ind]["image_urls"]["large"]))
        except:
            res = f"暂时没有 {_id} 的相关结果哦~"
        return (
            res,
            ShitJson["illusts"][ind]["id"]
            if ind < len(ShitJson["illusts"]) else -1,
        )
Esempio n. 10
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")}

    async with aiohttp.ClientSession() as sess:

        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
Esempio n. 11
0
async def tulai(session: CommandSession):
    await session.send(unescape(cq.image("zs.jpg")))