Exemplo n.º 1
0
async def jrrp(session: CommandSession):
    today = datetime.date.today()
    ans = -1
    random.seed(datetime.datetime.now())
    async with db.pool.acquire() as conn:
        values = await conn.fetch(
            """ select dt, rand from jrrp where qid={};""".format(
                session.event.user_id))
        if len(values) == 0:
            ans = random.randint(0, 100)
            await conn.execute(
                """ insert into jrrp values ({},'{}',{})""".format(
                    session.event.user_id, today, ans))
        else:
            values = values[0]
            if values["dt"] != today:
                ans = random.randint(0, 100)
                await conn.execute(
                    """update jrrp set rand = {},dt='{}'  where qid={};""".
                    format(ans, today, session.event.user_id))
            else:
                ans = values["rand"]

    session.finish(
        unescape(cq.at(session.event.user_id) + "今天的人品为:{} 哦!".format(ans)))
Exemplo n.º 2
0
async def tx(session: CommandSession):
    bot = nonebot.get_bot()
    try:
        await bot.send_group_msg(
            group_id=bot.config.QGROUP,
            message=unescape(
                unescape(cq.at("all")) + " Ciallo~(∠・ω< )⌒★,今天你出刀了吗?"),
        )
    except CQHttpError:
        pass
Exemplo n.º 3
0
async def _():
    async with db.pool.acquire() as conn:
        values = await conn.fetch("select gid from mg where ghz = true")
        bot = nonebot.get_bot()
        for item in values:
            item = item["gid"]
            try:
                await bot.send_group_msg(
                    group_id=int(item),
                    message=unescape(
                        unescape(cq.at("all")) + " Ciallo~(∠・ω< )⌒★,今天你出刀了吗?"),
                )
            except CQHttpError:
                pass
Exemplo n.º 4
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]:
        async with db.pool.acquire() as conn:
            values = await conn.fetch(
                f"""select dt from subs where qid={qid} and rss='{source}';""")
            if len(values) > 0:
                qdt = values[0]["dt"]
            else:
                values = await conn.fetch(
                    f"""select pre from rss where id='{source}';""")
                qdt = values[0]["pre"]
            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
                if route != None:
                    ress = await getfun(route,
                                        (num[0] if num[0] != -2 else -1))
                else:
                    ress = await getfun(**kwargs)
            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 CQHttpError:
                        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! ",
                            )
                        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 CQHttpError:
                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 CQHttpError:
                logger.error(f"Send Ending Error! Processing QQ 「{qid}」")
            if success_dt != "" and source != "自定义路由":
                await conn.execute(
                    f"""update subs set dt = '{success_dt}' where qid = {qid} and rss = '{source}';"""
                )
    if feedBack:
        await bot.send_group_msg(group_id=feedBack,
                                 message=cq.at(qid) +
                                 f"「{doc[source]}」的资讯已私信,请查收。")
Exemplo n.º 5
0
async def rss(session: CommandSession):
    if "subs" in session.state:
        async with db.pool.acquire() as conn:
            for _, item in session.state["ls"]:
                try:
                    await conn.execute(
                        """insert into subs values ({},'{}','{}')""".format(
                            session.event.user_id, "No Information", item))
                    await session.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 为:{session.event.message_id}"
                    )
                    logger.error("some rss issue", exc_info=True)

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

    elif "del" in session.state:
        async with db.pool.acquire() as conn:
            fail = []
            success = []
            for _, dl in session.state["ls"]:
                resp = await conn.execute(
                    "delete from subs where qid = {} and rss = '{}'".format(
                        session.event.user_id, dl))
                if resp[len("delete "):] == "0":
                    fail.append(doc[dl])
                else:
                    success.append(doc[dl])
            if len(fail) > 0:
                await session.send(
                    cq.at(session.event.user_id) +
                    f"这{'个' if len(fail)==1 else '些'}源「{'、'.join(fail)}」不在你的订阅列表里面哦~"
                )
            if len(success) > 0:
                await session.send(
                    cq.at(session.event.user_id) +
                    f" 取消订阅「{'、'.join(success)}」成功!可喜可贺,可喜可贺!")
    elif session.state["list"]:
        async with db.pool.acquire() as conn:
            values = await conn.fetch(
                "select * from subs where qid = {}".format(
                    session.event.user_id))
            if len(values) == 0:
                session.finish("貌似你没有订阅任何 rss 源")
            await session.send(
                cq.at(session.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 session.state["ls"]:
            asyncio.run_coroutine_threadsafe(
                sendrss(
                    session.event.user_id,
                    session.bot,
                    nm,
                    None,
                    item,
                    feedBack=session.event.group_id
                    if session.event.detail_type != "private" else False,
                ),
                loop,
            )
Exemplo n.º 6
0
async def _(session: CommandSession):
    if session.is_first_run:
        parser = ArgumentParser(session=session)
        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(session.current_arg_text.strip().split(" "))
        session.state["ls"] = []
        session.state["list"] = argv.list
        if argv.list:
            return
        if argv.subs != None:
            session.state["subs"] = argv.subs
            ls = argv.subs
        if argv.delete != None:
            session.state["del"] = argv.delete
            ls = argv.delete
        if argv.rss != []:
            session.state["rss"] = argv.rss
            ls = argv.rss
        if argv.route != None:
            session.state["route"] = argv.route
            session.state["ls"] = argv.route
            if len(session.state["ls"]) == 0:
                session.finish("查询路由地址不能为空哦!")
            return
        if argv.add != None:
            await session.send(str(session.event.user_id))
            result = await add_rss(argv.add.strip(),
                                   str(session.event.user_id))
            session.finish(result)

    ls = list(set(ls))
    if session.event.detail_type == "group":
        async with db.pool.acquire() as conn:
            values = await conn.fetch(
                "select safe from mg where gid = {}".format(
                    session.event.group_id))
            if len(values) > 0 and values[0]["safe"]:
                ls = [i for i in ls if "r18" not in i]

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

    if len(ls) > 0 and " ".join(ls).strip() != "":
        await session.send(
            unescape("没有添加「{}」的订阅源!请联系".format(" ".join(ls)) +
                     cq.at(545870222) + "添加订阅!"))
    if len(session.state["ls"]) == 0:
        await session.send(
            "本次资讯{}为空哦!".format("查看" if session.state["rss"] != [] else "订阅"))
        session.finish(
            AutoReply(
                "Rss 指令帮助菜单",
                "以下是 rss 指令支持的源",
                [(i, j) for i, j in doc.items() if "r18" not in i],
            ))
Exemplo n.º 7
0
async def stock(session: CommandSession):
    if session.state["s"]:
        await session.send("正在获取股票信息")
        surl = (
            "https://finance.yahoo.com/screener/predefined/most_actives?count=10&offset=0"
            if isinstance(session.state["s"], bool) else session.state["s"])
        async with aiohttp.ClientSession() as sess:
            async with sess.get(surl) as resp:
                if resp.status != 200:
                    session.finish(f"获取股票失败,请检查url是否正确!错误代码:{resp.status}")
                ShitHtml = await resp.text()
        data = pd.read_html(ShitHtml)[0]

        stk_list = data.values

        await session.send("以下是股票查询结果:")
        stk = ""
        cnt = 0
        for i in stk_list:
            if cnt == 10:
                break
            cnt += 1
            stk += (f"股票代码:{i[0]},价格:{i[2]},变动幅度:{i[4]} " +
                    ("↓" if i[4][0] == "-" else "↑") + "\n\n")
        stk += "以上!"
        await session.send(stk)

    if session.state["q"] != None:
        failed = []
        for stk in session.state["q"]:
            await session.send("正在查询 " + stk + "!")
            async with aiohttp.ClientSession() as sess:
                async with sess.get(qurl + stk, params=qdatas) as resp:
                    if resp.status != 200:
                        failed.append(stk)
                        continue
                    ShitJson = await resp.json()

            ShitJson = ShitJson["quoteSummary"]["result"][0]["price"]
            try:
                currency = ShitJson["currency"]
            except:
                fail.append(stk)
                continue
            res = (f"公司名:{ShitJson['shortName']}\n" + "当前货币单位为:" + currency +
                   f"\n当前股票价格为:{ShitJson['regularMarketPrice']['fmt']}")
            res += f"\n当日最高成交价格为:{ShitJson['regularMarketDayHigh']['fmt']}\n当日最低成交价格为:{ShitJson['regularMarketDayLow']['fmt']}\n变动幅度为:{ShitJson['regularMarketChangePercent']['fmt']}"

            await session.send(res)
        if len(failed) > 0:
            session.finish("请检查以下股票代码是否输入正确!\n查询失败的股票代码为「{}」".format(failed))

    if session.state["i"]:
        async with db.pool.acquire() as conn:
            try:
                await conn.execute(
                    f"insert into acc (qid) values ({session.event.user_id})")
                await session.send("注册成功!当前注册资本为 1000000 美元。")
            except:
                session.finish("你已经注册过了!")

    if session.state["h"]:
        async with db.pool.acquire() as conn:
            values = await conn.fetch(
                f"select money from acc where qid={session.event.user_id}")
            if len(values) == 0:
                session.finish("您尚未注册", ensure_private=True)
            money = values[0]["money"]
            values = await conn.fetch(
                f"select * from holds where qid={session.event.user_id}")
            values = [(i["stk"], i["nums"]) for i in values if i["nums"] > 0]
            if len(values) == 0:
                session.finish(f"当前您未持股哦!拥有现金:{money}")

            if session.event.detail_type != "private":
                await session.send(
                    cq.at(session.event.user_id) +
                    " 资产统计信息正在发送中,咕噜灵波~ (∠・ω< )⌒★")

            await session.send("正在统计您的资产。。。", ensure_private=True)
            res = []
            fail = []
            cnt = 0
            tot = 0
            async with aiohttp.ClientSession() as sess:
                for item, nums in values:
                    async with sess.get(qurl + item, params=qdatas) as resp:
                        app = ""
                        if resp.status != 200:
                            fail.append(item)
                        else:
                            ShitJson = await resp.json()
                            ShitJson = ShitJson["quoteSummary"]["result"][0][
                                "price"]
                            price = float(
                                ShitJson["regularMarketPrice"]["raw"]) * nums
                            tot += price
                            app = f"\n价值:{price} USD\n今日变动幅度为:{ShitJson['regularMarketChangePercent']['fmt']}"
                    if cnt < 5 or session.state["h"] == 1:
                        res.append(f"股票代码:{item}\n持股数:{nums} 股" + app)
                    cnt += 1
            await session.send("以下是您持有的股份:", ensure_private=True)
            for msg in res:
                await session.send(msg, ensure_private=True)
            await session.send(
                f"共持股:{len(values)} 支\n共计:{tot+money} USD。现金额度为:{money} USD。" +
                (f"其中 「{', '.join(fail)}」 股票价格获取失败。" if len(fail) > 0 else ""),
                ensure_private=True,
            )
            if session.event.detail_type != "private":
                await session.send(
                    cq.at(session.event.user_id) +
                    f" 共持股:{len(values)} 支\n共计:{tot+money} USD。现金额度为:{money} USD。"
                    + (f"其中 「{', '.join(fail)}」 股票价格获取失败。"
                       if len(fail) > 0 else ""), )

    if "add" in session.state:
        if session.event.detail_type == "private":
            if session.is_first_run:
                ls = session.state["add"]
                fail = []
                success = []
                tot = 0
                async with db.pool.acquire() as conn:
                    values = await conn.fetch(
                        f"select money from acc where qid={session.event.user_id}"
                    )
                    if len(values) == 0:
                        session.finish("您尚未注册!")
                    money = values[0]["money"]
                async with aiohttp.ClientSession() as sess:
                    if len(ls) > 1 and session.state["nums"] == "allin":
                        session.finish("多种股票不支持 allin 操作!")
                    for item in ls:
                        async with sess.get(qurl + item,
                                            params=qdatas) as resp:
                            app = ""
                            if resp.status != 200:
                                fail.append((item, "无法获取最新股票价格"))
                            else:
                                ShitJson = await resp.json()
                                ShitJson = ShitJson["quoteSummary"]["result"][
                                    0]["price"]
                                price = float(
                                    ShitJson["regularMarketPrice"]["raw"])
                                if isinstance(session.state["nums"], int):
                                    if money < session.state["nums"] * price:
                                        fail.append((item, "余额不足"))
                                    else:
                                        tot += session.state["nums"] * price
                                        success.append((
                                            item,
                                            price,
                                            session.state["nums"],
                                            price * session.state["nums"],
                                        ))
                                else:
                                    nums = int(money / price)
                                    tot += price * nums
                                    if nums == 0:
                                        fail.append(
                                            (item, f"当前余额不足以购买一支「{item}」股票"))
                                    else:
                                        success.append(
                                            (item, price, nums, price * nums))
                session.state["trade"] = (success, fail)
                await session.send("以下是本次交易信息:")
                if len(success) > 0:
                    await session.send("可以完成的操作:")
                    for i in success:
                        await session.send(
                            "股票代码:{}\n股票单价:{}\n购买支数:{}\n合计金额:{}".format(
                                i[0], i[1], i[2], i[3]))
                if len(fail) > 0:
                    await session.send("无法完成的操作:")
                    for i in fail:
                        await session.send("股票代码:{}\n原因:{}".format(i[0], i[1]))
                await session.send(
                    f"交易前余额:「{money}」USD。交易后余额:「{money-tot}」USD。")
                if len(success) == 0:
                    session.finish("无可交易操作,交易终止。")
            confirm = session.get("confirm",
                                  prompt="请确认这笔交易!输入「确认」进行确认,输入其他任意值取消这笔交易。")
            if confirm == "确认":
                success, fail = session.state["trade"]
                async with db.pool.acquire() as conn:
                    for item in success:
                        async with conn.transaction():
                            values = await conn.fetch(
                                "select * from holds where qid={} and stk='{}'"
                                .format(session.event.user_id, item[0]))
                            if len(values) == 0:
                                await conn.execute(
                                    "insert into holds values({},'{}',{})".
                                    format(session.event.user_id, item[0],
                                           item[2]))
                            else:
                                await conn.execute(
                                    "update holds set nums = nums + {2} where qid = {0} and stk = '{1}'"
                                    .format(session.event.user_id, item[0],
                                            item[2]))
                            await conn.execute(
                                f"update acc set money = money - {item[3]} where qid={session.event.user_id};"
                            )
                await session.send("交易完成!")
            else:
                session.finish("交易取消")
        else:
            event = {
                "user_id": session.event.user_id,
                "message": session.event.message,
                "raw_message": session.event.raw_message,
                "post_type": "message",
                "message_type": "private",
                "sub_type": "friend",
            }
            await session.send(cq.at(session.event.user_id) + " 转进私聊中。。。")
            flg = await call_command(
                session.bot,
                aiocqhttp.Event(event),
                "stock",
                current_arg=session.current_arg,
            )
            if not flg:
                await session.send("转进失败,请尝试直接复制以下信息并发送以完成操作。",
                                   ensure_private=True)
                await session.send("stk " + session.current_arg,
                                   ensure_private=True)

    if "sell" in session.state:
        if session.event.detail_type == "private":
            if session.is_first_run:
                ls = session.state["sell"]
                fail = []
                success = []
                tot = 0
                async with db.pool.acquire() as conn:
                    values = await conn.fetch(
                        f"select money from acc where qid={session.event.user_id}"
                    )
                    if len(values) == 0:
                        session.finish("您尚未注册!")
                    money = values[0]["money"]
                    if len(ls) == 0:
                        values = await conn.fetch(
                            "select * from holds where qid = {}".format(
                                session.event.user_id))
                        ls = [i["stk"] for i in values if i["nums"] != 0]
                        if len(ls) == 0:
                            session.finish("您尚未有购买股票记录")
                    async with aiohttp.ClientSession() as sess:
                        for item in ls:
                            values = await conn.fetch(
                                "select nums from holds where qid={1} and stk ='{0}'"
                                .format(item, session.event.user_id))
                            if len(values) == 0:
                                fail.append((item, "您未购买该股票"))
                                continue
                            nums = values[0]["nums"]
                            async with sess.get(qurl + item,
                                                params=qdatas) as resp:
                                app = ""
                                if resp.status != 200:
                                    fail.append((item, "无法获取最新股票价格"))
                                else:
                                    ShitJson = await resp.json()
                                    ShitJson = ShitJson["quoteSummary"][
                                        "result"][0]["price"]
                                    price = float(
                                        ShitJson["regularMarketPrice"]["raw"])
                                    if isinstance(session.state["nums"], int):
                                        if nums < session.state["nums"]:
                                            fail.append(item, "出售支数大于拥有支数")
                                        else:
                                            tot += session.state["nums"] * price
                                            success.append((
                                                item,
                                                price,
                                                session.state["nums"],
                                                price * session.state["nums"],
                                            ))
                                    else:
                                        tot += price * nums
                                        success.append(
                                            (item, price, nums, price * nums))
                session.state["trade"] = (success, fail)
                await session.send("以下是本次交易信息:")
                if len(success) > 0:
                    await session.send("可以完成的操作:")
                    for i in success:
                        await session.send(
                            "股票代码:{}\n股票单价:{}\n出售支数:{}\n合计金额:{}".format(
                                i[0], i[1], i[2], i[3]))
                if len(fail) > 0:
                    await session.send("无法完成的操作:")
                    for i in fail:
                        await session.send("股票代码:{}\n原因:{}".format(i[0], i[1]))
                await session.send(
                    f"交易前余额:「{money}」USD。交易后余额:「{money+tot}」USD。")
                if len(success) == 0:
                    session.finish("无可交易操作,交易终止。")
            confirm = session.get("confirm",
                                  prompt="请确认这笔交易!输入「确认」进行确认,输入其他任意值取消这笔交易。")
            if confirm == "确认":
                success, fail = session.state["trade"]
                async with db.pool.acquire() as conn:
                    for item in success:
                        async with conn.transaction():
                            values = await conn.fetch(
                                "select * from holds where qid={} and stk='{}'"
                                .format(session.event.user_id, item[0]))
                            if len(values) == 0:
                                await conn.execute(
                                    "insert into holds values({},'{}',{})".
                                    format(session.event.user_id, item[0],
                                           item[2]))
                            else:
                                await conn.execute(
                                    "update holds set nums = nums - {2} where qid = {0} and stk = '{1}'"
                                    .format(session.event.user_id, item[0],
                                            item[2]))
                            await conn.execute(
                                f"update acc set money = money + {item[3]} where qid={session.event.user_id};"
                            )
                await session.send("交易完成!")
            else:
                session.finish("交易取消")
        else:
            event = {
                "user_id": session.event.user_id,
                "message": session.event.message,
                "post_type": "message",
                "message_type": "private",
                "raw_message": session.event.raw_message,
                "sub_type": "friend",
            }
            await session.send(cq.at(session.event.user_id) + " 转进私聊中。。。")
            flg = await call_command(
                session.bot,
                aiocqhttp.Event(event),
                "stock",
                current_arg=session.current_arg,
            )
            if not flg:
                await session.send("转进失败,请尝试直接复制以下信息并发送以完成操作。",
                                   ensure_private=True)
                await session.send("stk " + session.current_arg,
                                   ensure_private=True)
Exemplo n.º 8
0
async def hello(session: NoticeSession):
    await session.send(unescape(cq.at(session.event.user_id) + " 欢迎新人入群👏!"))
    await session.bot.send_private_msg(user_id=545870222,
                                       message=f"新入群 {session.event.group_id}")