예제 #1
0
async def boss_notice(max_num: int = -1):

    bot = get_bot()
    ress = [(["暂时没有公会报表哦!"], "Grab Rss Error!", "", "",)]

    if bot.config.cookies:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36",
            "Cookie": bot.config.cookies,
            "Host": "www.bigfun.cn",
            "Referer": "https://www.bigfun.cn/tools/pcrteam/d_report",
        }
    else:
        return ress

    async with bot.config.session.get(
        "https://www.bigfun.cn/api/feweb?target=gzlj-clan-day-report%2Fa&date={}&size=30".format(
            datetime.today().strftime("%Y-%m-%d")
        ),
        headers=headers,
    ) as resp:
        if resp.status != 200:
            return ress
        ShitJson = await resp.json()
        ShitJson = ShitJson["data"]
        try:
            ls = [
                item
                for per in ShitJson
                for item in per["damage_list"]
                if item["kill"] == 1
            ]
            ls.sort(key=itemgetter("datetime"), reverse=True)
        except Exception as e:
            return ress

    ress = [
        (
            [cq.at("all") + "{} 倒了".format(i["boss_name"])],
            str(i["datetime"]),
            "",
            cq.at("all") + "{} 倒了".format(i["boss_name"]),
        )
        for i in ls
        if i["kill"] == 1
    ]

    return ress
예제 #2
0
파일: schedule.py 프로젝트: yoiyami96/Pbot
async def backup():
    bot = get_bot()
    await bot.send_group_msg(
        group_id=383647564,
        message=cq.at("all") + """٩( °༥° )و ₎₎能动手就别吵吵
开始击剑了,兄弟萌!!淦死野人!!""" + cq.image("a.gif"),
    )
예제 #3
0
파일: __init__.py 프로젝트: yoiyami96/Pbot
async def args(bot: Bot, event: Event, state: dict):
    parser = ArgumentParser()
    subparser = parser.add_mutually_exclusive_group()
    subparser.add_argument("-s", "--subs", nargs="+", help="订阅指定的 rss 源")
    subparser.add_argument("-r", "--route", nargs="+", help="获取自定路由的 rss 源的资讯")
    subparser.add_argument("-d", "--delete", nargs="+", help="删除 rss 订阅")
    subparser.add_argument("-l",
                           "--list",
                           action="store_true",
                           default=False,
                           help="列出已订阅的源")
    subparser.add_argument("-a", "--add", help="开通rss源")
    parser.add_argument("rss", nargs="*", help="获取已存在的 rss 源资讯")
    argv = parser.parse_args(event.plain_text.strip().split(" "))
    state["ls"] = []
    ls = []
    state["list"] = argv.list
    if argv.list:
        return
    if argv.subs != None:
        state["subs"] = argv.subs
        ls = argv.subs
    if argv.delete != None:
        state["del"] = argv.delete
        ls = argv.delete
    if argv.rss != []:
        state["rss"] = argv.rss
        ls = argv.rss
    if argv.route != None:
        state["route"] = argv.route
        state["ls"] = argv.route
        if len(state["ls"]) == 0:
            await rss.finish("查询路由地址不能为空哦!")
        return
    if argv.add != None:
        await rss.finish("目前不支持哦!!!")
        await rss.send(str(event.user_id))
        # result = await add_rss(argv.add.strip(), str(event.user_id))

    ls = list(set(ls))
    if event.detail_type == "group":
        safe = await Mg.query.where(Mg.gid == event.group_id).gino.all()
        print(len(safe))
        if len(safe) > 0 and safe[0].safe:
            ls = [i for i in ls if "r18" not in i]

    for key in doc:
        if key in ls[:]:
            state["ls"].append((gtfun(key), key))
            ls.remove(key)

    if len(ls) > 0 and " ".join(ls).strip() != "":
        await rss.send(
            unescape("没有添加「{}」的订阅源!请联系".format(" ".join(ls)) +
                     cq.at(545870222) + "添加订阅!"))
    if len(state["ls"]) == 0:
        await rss.finish(
            "本次资讯{}为空哦!".format("查看" if state["rss"] != [] else "订阅"))
예제 #4
0
async def firsthandle(bot: Bot, event: Event, state: dict):
    today = datetime.date.today()
    ans = -1
    random.seed(datetime.datetime.now())
    value = await Jrrp.query.where(Jrrp.qid == event.user_id).gino.first()
    if value == None:
        value = await Jrrp.create(qid=event.user_id)
    ans = value.rand
    if value.dt != today:
        ans = random.randint(0, 100)
        await value.update(dt=today, rand=ans).apply()

    await jrrp.finish(
        unescape(cq.at(event.user_id) + "今天的人品为:{} 哦!".format(ans)))
예제 #5
0
파일: notice.py 프로젝트: yoiyami96/Pbot
async def firsthandle(bot: Bot, event: Event, state: dict):
    if event.detail_type == "group_increase":
        await helloNew.send(unescape(cq.at(event.user_id) + " 欢迎新人入群👏!"))
        await bot.send_private_msg(user_id=545870222,
                                   message=f"新入群 {event.group_id}")
예제 #6
0
파일: __init__.py 프로젝트: yoiyami96/Pbot
async def firstHandle(bot: Bot, event: Event, state: dict):
    if "subs" in state:
        for _, item in state["ls"]:
            await Sub.create(qid=event.user_id, dt="No Information", rss=item)
            await rss.send(f"「{doc[item]}」的资讯已添加订阅了!有新资讯发布时,会私信你哦!")
            # except asyncpg.exceptions.ForeignKeyViolationError:
            #    await session.send(f"貌似系统并没有支持该订阅源的订阅!")
            #    logger.error("no", exc_info=True)
            # except asyncpg.exceptions.UniqueViolationError:
            #    await session.send(f"你已经添加过「{doc[item]}」的资讯订阅啦!")
            # except:
            #    await session.send(
            #        f"发生未知错误!错误详细信息已记录了在log中!\n定位 message id 为:{event.message_id}"
            #    )
            #    logger.error("some rss issue", exc_info=True)

    elif "route" in state:
        for rt in state["ls"]:
            resp = await sendrss(
                event.user_id,
                bot,
                "自定义路由",
                None,
                getrss,
                (1, 1),
                route=rt,
            )
            if resp and event.detail_type != "private":
                await rss.send(
                    unescape(cq.at(event.user_id) + f"「{rt}」的资讯已私信,请查收。"))

    elif "del" in state:
        fail = []
        success = []
        for _, dl in state["ls"]:
            resp = await Sub.delete.where((Sub.qid == event.user_id)
                                          & (Sub.rss == dl)).gino.status()
            print(resp)
            if resp[len("delete "):] == "0":
                fail.append(doc[dl])
            else:
                success.append(doc[dl])
        if len(fail) > 0:
            await rss.send(
                cq.at(event.user_id) +
                f"这{'个' if len(fail)==1 else '些'}源「{'、'.join(fail)}」不在你的订阅列表里面哦~"
            )
        if len(success) > 0:
            await rss.send(
                cq.at(event.user_id) +
                f" 取消订阅「{'、'.join(success)}」成功!可喜可贺,可喜可贺!")
    elif state["list"]:
        values = await Sub.query.where(Sub.qid == event.user_id).gino.all()
        if len(values) == 0:
            await rss.finish("貌似你没有订阅任何 rss 源")
        await rss.send(
            cq.at(event.user_id) + "以下是你已订阅的源:\n{}".format("\n".join(
                [doc[i.rss] + " - " + i.rss for i in values])))

    else:
        loop = asyncio.get_event_loop()
        for item, nm in state["ls"]:
            asyncio.run_coroutine_threadsafe(
                sendrss(
                    event.user_id,
                    bot,
                    nm,
                    None,
                    item,
                    feedBack=event.group_id
                    if event.detail_type != "private" else False,
                ),
                loop,
            )
예제 #7
0
async def sendrss(
        qid: int,
        bot,
        source: str,
        ress=None,
        getfun=None,
        num=(-2, 3),
        route=None,
        feedBack=False,
):
    isP = "pixiv" in source
    if qid not in locks:
        locks[qid] = asyncio.Lock()
    async with locks[qid]:
        value = await Sub.query.where((Sub.qid == qid)
                                      & (Sub.rss == source)).gino.first()
        if value == None:
            value = await Rss.query.where(Rss.id == source).gino.first()
            qdt = value.pre
        else:
            qdt = value.dt
        cnt = 0
        is_read = False
        if ress == None:
            kwargs = {}
            if "pixiv" in source:
                kwargs["mode"] = source[len("pixiv_"):]
            else:
                kwargs["max_num"] = num[0] if num[0] != -2 else -1
            try:
                if route != None:
                    ress = await getfun(route,
                                        (num[0] if num[0] != -2 else -1))
                else:
                    ress = await getfun(**kwargs)
            except Exception as e:
                logger.error(str(e), exc_info=True)
                raise
        if num[0] == -2:
            for i in range(len(ress)):
                if ress[i][1] == qdt:
                    if i == 0:
                        try:
                            ress = ress[:1]
                        except:
                            ress = ress
                        break
                    ress = ress[:i]
                    break
        if num[1] != -1:
            ress = ress[:min(len(ress), num[1])]

        success_dt = ""
        fail = 0
        for res, dt, link, _ in reversed(ress):
            if is_read == False and dt == qdt:
                is_read = True
            if num[1] != -1 and cnt >= num[1]:
                break
            see = ""
            is_r = is_read
            cnt += 1
            if isP:
                await asyncio.sleep(1)
            await bot.send_private_msg(user_id=qid, message="=" * 19)
            for text in res:
                see = text
                try:
                    await bot.send_private_msg(
                        user_id=qid, message=("已读:\n" if is_r else "") + text)
                    if "[CQ:image" in text and not isP:
                        await asyncio.sleep(1)
                    is_r = False
                    success_dt = dt
                except (
                        RequestDenied,
                        ApiNotAvailable,
                        NetworkError,
                        ActionFailed,
                ) as e:
                    fail += 1
                    logger.error(f"Not ok here. Not ok message 「{see}」")
                    logger.error(f"Processing QQ 「{qid}」, Rss 「{source}」")
                    logger.error("Informing Pzzzzz!")
                    try:
                        await bot.send_private_msg(
                            user_id=545870222,
                            message=
                            f"Processing QQ 「{qid}」, Rss 「{source}」 error! {e}",
                        )
                    except:
                        logger.error("Inform Pzzzzz failed. ")
                    logger.error("Informing the user!")
                    try:
                        await bot.send_private_msg(
                            user_id=qid,
                            message=f"该资讯发送不完整!丢失信息为:「{see}」,请联系管理员。" +
                            ("\n该消息来源:" +
                             link if link != "" else "该资讯link未提供"),
                            auto_escape=True,
                        )
                    except:
                        try:
                            await bot.send_private_msg(
                                user_id=qid,
                                message=
                                f"该资讯发送不完整!丢失信息无法发送,请联系管理员。这可能是由于消息过长导致的" +
                                ("\n该消息来源:" +
                                 link if link != "" else "该资讯link未提供"),
                                auto_escape=True,
                            )
                        except:
                            logger.error("Informing failed!")
                    success_dt = dt

        try:
            await bot.send_private_msg(user_id=qid, message="=" * 19)
        except (RequestDenied, ApiNotAvailable, NetworkError, ActionFailed):
            pass
        try:
            await bot.send_private_msg(
                user_id=qid,
                message=
                f"已发送 {cnt} 条「{doc[source] if source !='自定义路由' else route}」的资讯!{f'其中失败 {fail} 条!' if fail !=0 else ''}咕噜灵波~(∠・ω< )⌒★",
            )
        except (RequestDenied, ApiNotAvailable, NetworkError, ActionFailed):
            logger.error(f"Send Ending Error! Processing QQ 「{qid}」")
        if success_dt != "" and source != "自定义路由" and value.dt:
            try:
                await value.update(dt=success_dt).apply()
            except:
                logger.error("update 失败", exc_info=True)
    if feedBack:
        await bot.send_group_msg(group_id=feedBack,
                                 message=cq.at(qid) +
                                 f"「{doc[source]}」的资讯已私信,请查收。")