Ejemplo n.º 1
0
async def test_query_with_abort_on_idx(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config_manager import group_manage_matcher

    async with app.test_matcher(group_manage_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_private_message_event(
            message=Message("群管理"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_call_api(
            "get_group_list", {}, [{"group_id": 101, "group_name": "test group"}]
        )
        ctx.should_call_send(
            event,
            Message("请选择需要管理的群:\n1. 101 - test group\n请输入左侧序号\n中止操作请输入'取消'"),
            True,
        )
        event_abort = fake_private_message_event(
            message=Message("取消"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event_abort)
        ctx.should_call_send(event_abort, "已取消", True)
        ctx.should_finished()
Ejemplo n.º 2
0
async def test_send_merge2_no_queue(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message, MessageSegment
    from nonebot_bison.plugin_config import plugin_config
    from nonebot_bison.send import send_msgs

    plugin_config.bison_use_pic_merge = 2
    plugin_config.bison_use_queue = False

    async with app.test_api() as ctx:
        bot = ctx.create_bot(base=Bot, self_id="8888")
        assert isinstance(bot, Bot)
        message = [
            Message(MessageSegment.text("test msg")),
            Message(MessageSegment.image("https://picsum.photos/200/300")),
            Message(MessageSegment.image("https://picsum.photos/200/300")),
        ]
        ctx.should_call_api(
            "get_group_member_info",
            {"group_id": 633, "user_id": 8888, "no_cache": True},
            {"user_id": 8888, "card": "admin", "nickname": "adminuser"},
        )
        merged_message = _merge_messge(
            [
                gen_node(8888, "admin", message[0]),
                gen_node(8888, "admin", message[1]),
                gen_node(8888, "admin", message[2]),
            ]
        )
        ctx.should_call_api(
            "send_group_forward_msg",
            {"group_id": 633, "messages": merged_message},
            None,
        )
        await send_msgs(bot, 633, "group", message)
async def test_platform_name_err(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager

    config = Config()
    config.user_target.truncate()
    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(BotReply.add_reply_on_platform(platform_manager, common_platform)),
            True,
        )
        event_2 = fake_group_message_event(
            message=Message("error"),
            sender=Sender(card="", nickname="test", role="admin"),
        )
        ctx.receive_event(bot, event_2)
        ctx.should_rejected()
        ctx.should_call_send(
            event_2,
            BotReply.add_reply_on_platform_input_error,
            True,
        )
async def test_query_sub(app: App):
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import query_sub_matcher
    from nonebot_bison.platform import platform_manager

    config = Config()
    config.user_target.truncate()
    config.add_subscribe(
        10000,
        "group",
        "6279793937",
        "明日方舟Arknights",
        "weibo",
        [platform_manager["weibo"].reverse_category["图文"]],
        ["明日方舟"],
    )
    async with app.test_matcher(query_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event = fake_group_message_event(message=Message("查询订阅"), to_me=True)
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_call_send(
            event, Message("订阅的帐号为:\nweibo 明日方舟Arknights 6279793937 [图文] 明日方舟\n"), True
        )
Ejemplo n.º 5
0
 async def generate_messages(self) -> list[Message]:
     if self._message is None:
         await self._pic_merge()
         msg_segments: list[MessageSegment] = []
         text = ""
         if self.text:
             if self._use_pic():
                 text += "{}".format(self.text)
             else:
                 text += "{}".format(
                     self.text if len(self.text) < 500 else self.text[:500] + "..."
                 )
         text += "\n来源: {}".format(self.target_type)
         if self.target_name:
             text += " {}".format(self.target_name)
         if self._use_pic():
             msg_segments.append(await parse_text(text))
             if not self.target_type == "rss" and self.url:
                 msg_segments.append(MessageSegment.text(self.url))
         else:
             if self.url:
                 text += " \n详情: {}".format(self.url)
             msg_segments.append(MessageSegment.text(text))
         for pic in self.pics:
             msg_segments.append(MessageSegment.image(pic))
         if self.compress:
             msgs = [reduce(lambda x, y: x.append(y), msg_segments, Message())]
         else:
             msgs = list(
                 map(lambda msg_segment: Message([msg_segment]), msg_segments)
             )
         msgs.extend(self.extra_msg)
         self._message = msgs
     assert len(self._message) > 0, f"message list empty, {self}"
     return self._message
async def test_add_with_target_no_cat(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.platform.ncm_artist import NcmArtist

    config = Config()
    config.user_target.truncate()

    ncm_router = respx.get("https://music.163.com/api/artist/albums/32540734")
    ncm_router.mock(return_value=Response(200, json=get_json("ncm_siren.json")))

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(BotReply.add_reply_on_platform(platform_manager, common_platform)),
            True,
        )
        event_3 = fake_group_message_event(
            message=Message("ncm-artist"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_3)
        ctx.should_call_send(
            event_3,
            Message(BotReply.add_reply_on_id(NcmArtist)),
            True,
        )
        event_4_ok = fake_group_message_event(
            message=Message("32540734"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_4_ok)
        ctx.should_call_send(
            event_4_ok,
            BotReply.add_reply_on_target_confirm("ncm-artist", "塞壬唱片-MSR", "32540734"),
            True,
        )
        ctx.should_call_send(
            event_4_ok, BotReply.add_reply_subscribe_success("塞壬唱片-MSR"), True
        )
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 1
    sub = subs[0]
    assert sub["target"] == "32540734"
    assert sub["tags"] == []
    assert sub["cats"] == []
    assert sub["target_type"] == "ncm-artist"
    assert sub["target_name"] == "塞壬唱片-MSR"
async def test_abort_add_on_id(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.platform.weibo import Weibo

    config = Config()
    config.user_target.truncate()

    ak_list_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=1005056279793937"
    )
    ak_list_router.mock(
        return_value=Response(200, json=get_json("weibo_ak_profile.json")))
    ak_list_bad_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=100505000")
    ak_list_bad_router.mock(
        return_value=Response(200, json=get_json("weibo_err_profile.json")))
    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(
                BotReply.add_reply_on_platform(platform_manager,
                                               common_platform)),
            True,
        )
        event_2 = fake_group_message_event(message=Message("weibo"),
                                           sender=fake_admin_user)
        ctx.receive_event(bot, event_2)
        ctx.should_call_send(
            event_2,
            Message(BotReply.add_reply_on_id(Weibo)),
            True,
        )
        event_abort = fake_group_message_event(message=Message("取消"),
                                               sender=Sender(card="",
                                                             nickname="test",
                                                             role="admin"))
        ctx.receive_event(bot, event_abort)
        ctx.should_call_send(
            event_abort,
            BotReply.add_reply_abort,
            True,
        )
        ctx.should_finished()
async def test_add_no_target(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager

    config = Config()
    config.user_target.truncate()

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(BotReply.add_reply_on_platform(platform_manager, common_platform)),
            True,
        )
        event_3 = fake_group_message_event(
            message=Message("arknights"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_3)
        ctx.should_call_send(
            event_3,
            Message(BotReply.add_reply_on_cats(platform_manager, "arknights")),
            True,
        )
        event_4 = fake_group_message_event(
            message=Message("游戏公告"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_4)
        ctx.should_call_send(
            event_4, BotReply.add_reply_subscribe_success("明日方舟游戏信息"), True
        )
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 1
    sub = subs[0]
    assert sub["target"] == "default"
    assert sub["tags"] == []
    assert sub["cats"] == [platform_manager["arknights"].reverse_category["游戏公告"]]
    assert sub["target_type"] == "arknights"
    assert sub["target_name"] == "明日方舟游戏信息"
async def test_del_sub(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import del_sub_matcher
    from nonebot_bison.platform import platform_manager

    config = Config()
    config.user_target.truncate()
    config.add_subscribe(
        10000,
        "group",
        "6279793937",
        "明日方舟Arknights",
        "weibo",
        [platform_manager["weibo"].reverse_category["图文"]],
        ["明日方舟"],
    )
    async with app.test_matcher(del_sub_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        assert isinstance(bot, Bot)
        event = fake_group_message_event(
            message=Message("删除订阅"), to_me=True, sender=fake_admin_user
        )
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_call_send(
            event,
            Message(
                "订阅的帐号为:\n1 weibo 明日方舟Arknights 6279793937\n [图文] 明日方舟\n请输入要删除的订阅的序号\n输入'取消'中止"
            ),
            True,
        )
        event_1_err = fake_group_message_event(
            message=Message("2"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_1_err)
        ctx.should_call_send(event_1_err, "删除错误", True)
        ctx.should_rejected()
        event_1_ok = fake_group_message_event(
            message=Message("1"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_1_ok)
        ctx.should_call_send(event_1_ok, "删除成功", True)
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 0
Ejemplo n.º 10
0
async def test_send_queue(app: App):
    import nonebot
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison import send
    from nonebot_bison.plugin_config import plugin_config
    from nonebot_bison.send import do_send_msgs, send_msgs

    async with app.test_api() as ctx:
        new_bot = ctx.create_bot(base=Bot)
        app.monkeypatch.setattr(nonebot, "get_bot", lambda: new_bot, True)
        app.monkeypatch.setattr(plugin_config, "bison_use_queue", True, True)
        bot = nonebot.get_bot()
        assert isinstance(bot, Bot)
        assert bot == new_bot
        ctx.should_call_api(
            "send_group_msg", {"group_id": "1233", "message": "test msg"}, True
        )
        await bot.call_api("send_group_msg", group_id="1233", message="test msg")
        await send_msgs(bot, "1233", "group", [Message("msg")])
        ctx.should_call_api(
            "send_group_msg", {"group_id": "1233", "message": "msg"}, True
        )
        await do_send_msgs()
        assert not ctx.wait_list.empty()
        app.monkeypatch.setattr(send, "LAST_SEND_TIME", 0, True)
        await do_send_msgs()
        assert ctx.wait_list.empty()
Ejemplo n.º 11
0
 async def send_list(bot: Bot, event: Event, state: T_State):
     config: Config = Config()
     user_info = state["target_user_info"]
     assert isinstance(user_info, User)
     try:
         sub_list = config.list_subscribe(
             # state.get("_user_id") or event.group_id, "group"
             user_info.user,
             user_info.user_type,
         )
         assert sub_list
     except AssertionError:
         await del_sub.finish("暂无已订阅账号\n请使用“添加订阅”命令添加订阅")
     else:
         res = "订阅的帐号为:\n"
         state["sub_table"] = {}
         for index, sub in enumerate(sub_list, 1):
             state["sub_table"][index] = {
                 "target_type": sub["target_type"],
                 "target": sub["target"],
             }
             res += "{} {} {} {}\n".format(index, sub["target_type"],
                                           sub["target_name"],
                                           sub["target"])
             platform = platform_manager[sub["target_type"]]
             if platform.categories:
                 res += " [{}]".format(", ".join(
                     map(lambda x: platform.categories[Category(x)],
                         sub["cats"])))
             if platform.enable_tag:
                 res += " {}".format(", ".join(sub["tags"]))
             res += "\n"
         res += "请输入要删除的订阅的序号\n输入'取消'中止"
         await bot.send(event=event, message=Message(await parse_text(res)))
Ejemplo n.º 12
0
 async def parse_id(event: MessageEvent, state: T_State):
     if not isinstance(state["id"], Message):
         return
     target = str(event.get_message()).strip()
     try:
         if target == "查询":
             raise LookupError
         if target == "取消":
             raise KeyboardInterrupt
         platform = platform_manager[state["platform"]]
         target = await platform.parse_target(target)
         name = await check_sub_target(state["platform"], target)
         if not name:
             raise ValueError
         state["id"] = target
         state["name"] = name
     except (LookupError):
         url = "https://nonebot-bison.vercel.app/usage/#%E6%89%80%E6%94%AF%E6%8C%81%E5%B9%B3%E5%8F%B0%E7%9A%84-uid"
         title = "Bison所支持的平台UID"
         content = "查询相关平台的uid格式或获取方式"
         image = "https://s3.bmp.ovh/imgs/2022/03/ab3cc45d83bd3dd3.jpg"
         getId_share = f"[CQ:share,url={url},title={title},content={content},image={image}]"  # 缩短字符串格式长度,以及方便后续修改为消息段格式
         await add_sub.reject(Message(getId_share))
     except (KeyboardInterrupt):
         await add_sub.finish("已中止订阅")
     except (ValueError):
         await add_sub.reject("id输入错误")
     except (Platform.ParseTargetException):
         await add_sub.reject("不能从你的输入中提取出id,请检查你输入的内容是否符合预期")
     else:
         await add_sub.send("即将订阅的用户为:{} {} {}\n如有错误请输入“取消”重新订阅".format(
             state["platform"], state["name"], state["id"]))
Ejemplo n.º 13
0
async def test_query_with_superuser_group_tome(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config_manager import group_manage_matcher

    async with app.test_matcher(group_manage_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_group_message_event(
            message=Message("群管理"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_call_send(event, Message("该功能只支持私聊使用,请私聊Bot"), True)
Ejemplo n.º 14
0
async def _(bot: Bot, event: GroupRecallNoticeEvent):
    switch_map = cfg.check_switcher(event.group_id, '防撤回')
    if len(switch_map) == 0:
        return
    mid = event.message_id
    msg = await bot.get_msg(message_id=mid)
    if event.user_id != event.self_id and ',type=flash' not in msg['message']:
        re = '刚刚说了:\n' + msg['message']
        await recall.finish(message=Message(re), at_sender=True)
Ejemplo n.º 15
0
async def _(bot: Bot, event: GroupMessageEvent):
    switch_map = cfg.check_switcher(event.group_id, '偷闪照')
    if len(switch_map) == 0:
        return
    msg = str(event.get_message())
    if ',type=flash' in msg:
        msg = msg.replace(',type=flash', '')
        await flashimg.finish(message=Message('不要发闪照,好东西就要大家一起分享。' + msg),
                              at_sender=True)
async def test_configurable_at_me_false(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.plugin_config import plugin_config

    plugin_config.bison_to_me = False
    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_group_message_event(
            message=Message("添加订阅"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event)
        ctx.should_call_send(
            event,
            Message(BotReply.add_reply_on_platform(platform_manager, common_platform)),
            True,
        )
        ctx.should_pass_rule()
        ctx.should_pass_permission()
Ejemplo n.º 17
0
async def test_query_with_superuser_private(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config_manager import group_manage_matcher

    async with app.test_matcher(group_manage_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_private_message_event(
            message=Message("群管理"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_call_api(
            "get_group_list", {}, [{"group_id": 101, "group_name": "test group"}]
        )
        ctx.should_call_send(
            event,
            Message("请选择需要管理的群:\n1. 101 - test group\n请输入左侧序号\n中止操作请输入'取消'"),
            True,
        )
        event_1_err = fake_private_message_event(
            message=Message("0"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event_1_err)
        ctx.should_call_send(event_1_err, "请输入正确序号", True)
        ctx.should_rejected()
        event_1_ok = fake_private_message_event(
            message=Message("1"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event_1_ok)
        ctx.should_call_send(event_1_ok, "请输入需要使用的命令:添加订阅,查询订阅,删除订阅,取消", True)
        event_2_err = fake_private_message_event(
            message=Message("222"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event_2_err)
        ctx.should_call_send(event_2_err, "请输入正确的命令", True)
        ctx.should_rejected()
        event_2_ok = fake_private_message_event(
            message=Message("查询订阅"),
            sender=fake_superuser,
            to_me=True,
            user_id=fake_superuser.user_id,
        )
        ctx.receive_event(bot, event_2_ok)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
async def test_configurable_at_me_true_failed(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config_manager import add_sub_matcher
    from nonebot_bison.plugin_config import plugin_config

    plugin_config.bison_to_me = True
    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_group_message_event(
            message=Message("添加订阅"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event)
        ctx.should_not_pass_rule()
        ctx.should_pass_permission()

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        event = fake_group_message_event(message=Message("添加订阅"), to_me=True)
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_not_pass_permission()
Ejemplo n.º 19
0
async def _(event: GroupMessageEvent, state: T_State):
    config: Config = Config()
    sub_list = config.list_subscribe(
        state.get("_user_id") or event.group_id, "group")
    res = ["订阅的帐号为:"]
    for sub in sub_list:
        temp = "{} {} {}".format(sub["target_type"], sub["target_name"],
                                 sub["target"])
        platform = platform_manager[sub["target_type"]]
        if platform.categories:
            temp += " [{}]".format(", ".join(
                map(lambda x: platform.categories[x], sub["cats"])))
        if platform.enable_tag:
            temp += " {}".format(", ".join(sub["tags"]))
        res.append(temp)
    if len(res) == 1:
        res = "当前无订阅"
    else:
        res = "\n".join(res)
    await query_sub_cmd.finish(Message(await parse_text(res)))
Ejemplo n.º 20
0
 async def _(state: T_State):
     config: Config = Config()
     user_info = state["target_user_info"]
     assert isinstance(user_info, User)
     sub_list = config.list_subscribe(
         # state.get("_user_id") or event.group_id, "group"
         user_info.user,
         user_info.user_type,
     )
     res = "订阅的帐号为:\n"
     for sub in sub_list:
         res += "{} {} {}".format(sub["target_type"], sub["target_name"],
                                  sub["target"])
         platform = platform_manager[sub["target_type"]]
         if platform.categories:
             res += " [{}]".format(", ".join(
                 map(lambda x: platform.categories[Category(x)],
                     sub["cats"])))
         if platform.enable_tag:
             res += " {}".format(", ".join(sub["tags"]))
         res += "\n"
     await query_sub.finish(Message(await parse_text(res)))
Ejemplo n.º 21
0
async def send_list(bot: Bot, event: GroupMessageEvent, state: T_State):
    config: Config = Config()
    sub_list = config.list_subscribe(event.group_id, "group")
    res = "订阅的帐号为:\n"
    state["sub_table"] = {}
    if not sub_list:
        await del_sub_cmd.finish("当前无订阅")
    for index, sub in enumerate(sub_list, 1):
        state["sub_table"][index] = {
            "target_type": sub["target_type"],
            "target": sub["target"],
        }
        res += "{} {} {} {}".format(index, sub["target_type"],
                                    sub["target_name"], sub["target"])
        platform = platform_manager[sub["target_type"]]
        if platform.categories:
            res += " [{}]".format(", ".join(
                map(lambda x: platform.categories[x], sub["cats"])))
        if platform.enable_tag:
            res += " {}".format(", ".join(sub["tags"]))
        res += "\n"
    res += "请输入要删除的订阅的序号"
    await bot.send(event=event, message=Message(await parse_text(res)))
async def test_del_empty_sub(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import del_sub_matcher
    from nonebot_bison.platform import platform_manager

    config = Config()
    config.user_target.truncate()
    async with app.test_matcher(del_sub_matcher) as ctx:
        bot = ctx.create_bot(base=Bot)
        assert isinstance(bot, Bot)
        event = fake_group_message_event(
            message=Message("删除订阅"), to_me=True, sender=fake_admin_user
        )
        ctx.receive_event(bot, event)
        ctx.should_pass_rule()
        ctx.should_pass_permission()
        ctx.should_finished()
        ctx.should_call_send(
            event,
            "暂无已订阅账号\n请使用“添加订阅”命令添加订阅",
            True,
        )
Ejemplo n.º 23
0
async def test_send_no_queue(app: App):
    from nonebot.adapters.onebot.v11.bot import Bot
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.plugin_config import plugin_config
    from nonebot_bison.send import send_msgs

    async with app.test_api() as ctx:
        app.monkeypatch.setattr(plugin_config, "bison_use_queue", False, True)
        bot = ctx.create_bot(base=Bot)
        assert isinstance(bot, Bot)
        ctx.should_call_api(
            "send_group_msg", {"group_id": "1233", "message": Message("msg1")}, True
        )
        ctx.should_call_api(
            "send_group_msg", {"group_id": "1233", "message": Message("msg2")}, True
        )
        ctx.should_call_api(
            "send_private_msg", {"user_id": "666", "message": Message("priv")}, True
        )
        await send_msgs(bot, "1233", "group", [Message("msg1"), Message("msg2")])
        await send_msgs(bot, "666", "private", [Message("priv")])
        assert ctx.wait_list.empty()
async def test_add_with_get_id(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message, MessageSegment
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.platform.weibo import Weibo

    config = Config()
    config.user_target.truncate()

    ak_list_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=1005056279793937"
    )
    ak_list_router.mock(
        return_value=Response(200, json=get_json("weibo_ak_profile.json"))
    )
    ak_list_bad_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=100505000"
    )
    ak_list_bad_router.mock(
        return_value=Response(200, json=get_json("weibo_err_profile.json"))
    )

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(
                BotReply.add_reply_on_platform(
                    platform_manager=platform_manager, common_platform=common_platform
                )
            ),
            True,
        )
        event_3 = fake_group_message_event(
            message=Message("weibo"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_3)
        ctx.should_call_send(
            event_3,
            Message(BotReply.add_reply_on_id(Weibo)),
            True,
        )
        event_4_query = fake_group_message_event(
            message=Message("查询"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_4_query)
        ctx.should_rejected()
        ctx.should_call_send(
            event_4_query,
            Message([MessageSegment(*BotReply.add_reply_on_id_input_search())]),
            True,
        )
        """
        关于:Message([MessageSegment(*BotReply.add_reply_on_id_input_search())])
        鬼知道为什么要在这里这样写,
        没有[]的话assert不了(should_call_send使用[MessageSegment(...)]的格式进行比较)
        不在这里MessageSegment()的话也assert不了(指不能让add_reply_on_id_input_search直接返回一个MessageSegment对象)
        amen
        """
        event_abort = fake_group_message_event(
            message=Message("取消"), sender=Sender(card="", nickname="test", role="admin")
        )
        ctx.receive_event(bot, event_abort)
        ctx.should_call_send(
            event_abort,
            BotReply.add_reply_abort,
            True,
        )
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 0
Ejemplo n.º 25
0
async def _(bot: Bot, event: FriendRecallNoticeEvent):
    mid = event.message_id
    msg = await bot.get_msg(message_id=mid)
    if event.user_id != event.self_id and 'type=flash,' not in msg['message']:
        re = '刚刚说了:' + msg['message']
        await recall.finish(message=Message(re))
async def test_add_with_bilibili_target_parser(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.platform.bilibili import Bilibili

    config = Config()
    config.user_target.truncate()

    ak_list_router = respx.get(
        "https://api.bilibili.com/x/space/acc/info?mid=161775300"
    )
    ak_list_router.mock(
        return_value=Response(200, json=get_json("bilibili_arknights_profile.json"))
    )

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(
                BotReply.add_reply_on_platform(
                    platform_manager=platform_manager, common_platform=common_platform
                )
            ),
            True,
        )
        event_2 = fake_group_message_event(
            message=Message("全部"), sender=Sender(card="", nickname="test", role="admin")
        )
        ctx.receive_event(bot, event_2)
        ctx.should_rejected()
        ctx.should_call_send(
            event_2,
            BotReply.add_reply_on_platform_input_allplatform(platform_manager),
            True,
        )
        event_3 = fake_group_message_event(
            message=Message("bilibili"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_3)
        assert Bilibili.parse_target_promot
        ctx.should_call_send(
            event_3,
            Message(BotReply.add_reply_on_id(Bilibili)),
            True,
        )
        event_4_err1 = fake_group_message_event(
            message=Message(
                "https://live.bilibili.com/5555734?broadcast_type=0&is_room_feed=1&spm_id_from=333.999.0.0"
            ),
            sender=fake_admin_user,
        )
        ctx.receive_event(bot, event_4_err1)
        ctx.should_call_send(
            event_4_err1, BotReply.add_reply_on_target_parse_input_error, True
        )
        ctx.should_rejected()

        event_4_err1 = fake_group_message_event(
            message=Message(
                "https://space.bilibili.com/ark161775300?from=search&seid=13051774060625135297&spm_id_from=333.337.0.0"
            ),
            sender=fake_admin_user,
        )
        ctx.receive_event(bot, event_4_err1)
        ctx.should_call_send(
            event_4_err1, BotReply.add_reply_on_target_parse_input_error, True
        )
        ctx.should_rejected()

        event_4_ok = fake_group_message_event(
            message=Message(
                "https://space.bilibili.com/161775300?from=search&seid=13051774060625135297&spm_id_from=333.337.0.0"
            ),
            sender=fake_admin_user,
        )
        ctx.receive_event(bot, event_4_ok)
        ctx.should_call_send(
            event_4_ok,
            BotReply.add_reply_on_target_confirm("bilibili", "明日方舟", "161775300"),
            True,
        )
        ctx.should_call_send(
            event_4_ok,
            Message(BotReply.add_reply_on_cats(platform_manager, "bilibili")),
            True,
        )
        event_5_ok = fake_group_message_event(
            message=Message("视频"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_5_ok)
        ctx.should_call_send(event_5_ok, Message(BotReply.add_reply_on_tags), True)
        event_6 = fake_group_message_event(
            message=Message("全部标签"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_6)
        ctx.should_call_send(
            event_6, BotReply.add_reply_subscribe_success("明日方舟"), True
        )
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 1
    sub = subs[0]
    assert sub["target"] == "161775300"
    assert sub["tags"] == []
    assert sub["cats"] == [platform_manager["bilibili"].reverse_category["视频"]]
    assert sub["target_type"] == "bilibili"
    assert sub["target_name"] == "明日方舟"
Ejemplo n.º 27
0
def _gen_prompt_template(prompt: str):
    if hasattr(Message, "template"):
        return Message.template(prompt)
    return prompt
Ejemplo n.º 28
0
async def send_group_list_private(bot: Bot, event: GroupMessageEvent,
                                  state: T_State):
    await group_manage_matcher.finish(Message("该功能只支持私聊使用,请私聊Bot"))
async def test_add_with_target(app: App):
    from nonebot.adapters.onebot.v11.event import Sender
    from nonebot.adapters.onebot.v11.message import Message
    from nonebot_bison.config import Config
    from nonebot_bison.config_manager import add_sub_matcher, common_platform
    from nonebot_bison.platform import platform_manager
    from nonebot_bison.platform.weibo import Weibo

    config = Config()
    config.user_target.truncate()

    ak_list_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=1005056279793937"
    )
    ak_list_router.mock(
        return_value=Response(200, json=get_json("weibo_ak_profile.json"))
    )
    ak_list_bad_router = respx.get(
        "https://m.weibo.cn/api/container/getIndex?containerid=100505000"
    )
    ak_list_bad_router.mock(
        return_value=Response(200, json=get_json("weibo_err_profile.json"))
    )

    async with app.test_matcher(add_sub_matcher) as ctx:
        bot = ctx.create_bot()
        event_1 = fake_group_message_event(
            message=Message("添加订阅"),
            sender=Sender(card="", nickname="test", role="admin"),
            to_me=True,
        )
        ctx.receive_event(bot, event_1)
        ctx.should_pass_rule()
        ctx.should_call_send(
            event_1,
            Message(
                BotReply.add_reply_on_platform(
                    platform_manager=platform_manager, common_platform=common_platform
                )
            ),
            True,
        )
        event_2 = fake_group_message_event(
            message=Message("全部"), sender=Sender(card="", nickname="test", role="admin")
        )
        ctx.receive_event(bot, event_2)
        ctx.should_rejected()
        ctx.should_call_send(
            event_2,
            BotReply.add_reply_on_platform_input_allplatform(platform_manager),
            True,
        )
        event_3 = fake_group_message_event(
            message=Message("weibo"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_3)
        ctx.should_call_send(
            event_3,
            Message(BotReply.add_reply_on_id(Weibo)),
            True,
        )
        event_4_err = fake_group_message_event(
            message=Message("000"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_4_err)
        ctx.should_call_send(event_4_err, BotReply.add_reply_on_id_input_error, True)
        ctx.should_rejected()
        event_4_ok = fake_group_message_event(
            message=Message("6279793937"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_4_ok)
        ctx.should_call_send(
            event_4_ok,
            BotReply.add_reply_on_target_confirm(
                "weibo", "明日方舟Arknights", "6279793937"
            ),
            True,
        )
        ctx.should_call_send(
            event_4_ok,
            Message(BotReply.add_reply_on_cats(platform_manager, "weibo")),
            True,
        )
        event_5_err = fake_group_message_event(
            message=Message("图文 文字 err"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_5_err)
        ctx.should_call_send(
            event_5_err, BotReply.add_reply_on_cats_input_error("err"), True
        )
        ctx.should_rejected()
        event_5_ok = fake_group_message_event(
            message=Message("图文 文字"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_5_ok)
        ctx.should_call_send(event_5_ok, Message(BotReply.add_reply_on_tags), True)
        event_6 = fake_group_message_event(
            message=Message("全部标签"), sender=fake_admin_user
        )
        ctx.receive_event(bot, event_6)
        ctx.should_call_send(
            event_6, BotReply.add_reply_subscribe_success("明日方舟Arknights"), True
        )
        ctx.should_finished()
    subs = config.list_subscribe(10000, "group")
    assert len(subs) == 1
    sub = subs[0]
    assert sub["target"] == "6279793937"
    assert sub["tags"] == []
    assert sub["cats"] == [platform_manager["weibo"].reverse_category["图文"]] + [
        platform_manager["weibo"].reverse_category["文字"]
    ]
    assert sub["target_type"] == "weibo"
    assert sub["target_name"] == "明日方舟Arknights"
Ejemplo n.º 30
0
async def parse_platform(event: GroupMessageEvent, state: T_State) -> None:
    platform = event.get_plaintext().strip()
    if platform == "全部":
        message = "全部平台\n" + "\n".join([
            "{}:{}".format(platform_name, platform.name)
            for platform_name, platform in platform_manager.items()
        ])
        await add_sub_cmd.reject(message)
    elif platform in platform_manager:
        state["platform"] = platform
    else:
        await add_sub_cmd.reject("平台输入错误")


@add_sub_cmd.got("platform", Message.template("{_prompt}"),
                 [Depends(parse_platform)])
async def init_id(state: T_State, platform: str = Arg()):
    if platform_manager[platform].has_target:  # type: ignore
        state["_prompt"] = "请输入订阅用户的 ID"
    else:
        state["id"] = "default"
        state["name"] = await platform_manager[platform].get_target_name(
            Target(""))


async def parse_id(event: GroupMessageEvent, state: T_State):
    target = str(event.get_message()).strip()
    try:
        name = await check_sub_target(state["platform"], target)
        if not name: