예제 #1
0
    async def get_review(group: Group, member: Member, review_type: str,
                         target: str) -> MessageItem:
        group_id = group.id
        member_id = member.id
        time = datetime.now()
        time_right = time.strftime("%Y-%m-%d %H:%M:%S")
        if review_type == "year":
            timep = time - relativedelta(years=1)
            time_left = (time -
                         relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S")
            tag = "年内"
        elif review_type == "month":
            timep = time - relativedelta(months=1)
            time_left = (time -
                         relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S")
            tag = "月内"
        else:
            return MessageItem(
                MessageChain.create(
                    [Plain(text="Error: review_type invalid!")]),
                QuoteSource(GroupStrategy()))

        sql = select(ChatRecord).where(
            ChatRecord.group_id == group_id,
            ChatRecord.member_id == member_id if target == "member" else True,
            ChatRecord.time < time, ChatRecord.time > timep)

        if not (res := list(orm.fetchall(sql))):
            return MessageItem(MessageChain.create([Plain(text="没有你的发言记录呐~")]),
                               QuoteSource(GroupStrategy()))
예제 #2
0
파일: utils.py 프로젝트: wingxia/sagiri-bot
async def get_admins(group: Group) -> list:
    admins_res = list(orm.fetchall(
        select(
            UserPermission.member_id
        ).where(
            UserPermission.group_id == group.id,
            UserPermission.level > 1
        )
    ))
    admins = [item[0] for item in admins_res]
    return admins
예제 #3
0
async def getStatus():
    return {
        "functionCalled":
        len(
            orm.fetchall(
                select(FunctionCalledRecord).where(
                    FunctionCalledRecord.time > datetime.date.today()))),
        "handlerCount":
        len(AppCore.get_core_instance().get_group_chain()),
        "sayaCount":
        len(AppCore.get_core_instance().get_saya_channels())
    }
예제 #4
0
 async def keyword_detect(keyword: str):
     if re.match(r"\[mirai:image:{.*}\..*]", keyword):
         keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword,
                              re.S)[0]
     if result := list(
             orm.fetchall(
                 select(KeywordReply.reply, KeywordReply.reply_type).where(
                     KeywordReply.keyword == keyword))):
         reply, reply_type = random.choice(result)
         return MessageItem(
             MessageChain.create([
                 Plain(text=reply) if reply_type == "text" else
                 Image.fromUnsafeBytes(base64.b64decode(reply))
             ]), Normal(GroupStrategy()))
예제 #5
0
 async def bot_launch_init(self):
     self.config_check()
     orm.session.query(Setting).update({"active": False})
     group_list = await self.__app.groupList()
     frequency_limit_dict = {}
     for group in group_list:
         frequency_limit_dict[group.id] = 0
         try:
             orm.update(Setting, {"group_id": group.id}, {
                 "group_id": group.id,
                 "group_name": group.name,
                 "active": True
             })
         except Exception:
             logger.error(traceback.format_exc())
             orm.session.rollback()
     results = orm.fetchall(select(Setting).where(Setting.active == True))
     logger.info("本次启动活动群组如下:")
     for result in results:
         logger.info(f"群ID: {str(result[0]).ljust(14)}群名: {result[1]}")
     for result in results:
         orm.update(UserPermission, {
             "member_id": self.__config["HostQQ"],
             "group_id": result[0]
         }, {
             "member_id": self.__config["HostQQ"],
             "group_id": result[0],
             "level": 4
         })
     self.__frequency_limit_instance = GlobalFrequencyLimitDict(
         frequency_limit_dict)
     threading.Thread(target=frequency_limit,
                      args=(self.__frequency_limit_instance, )).start()
     exception_resender_instance = ExceptionReSender(self.__app)
     listener = threading.Thread(target=exception_resender_listener,
                                 args=(self.__app,
                                       exception_resender_instance,
                                       self.__loop))
     listener.start()
예제 #6
0
    @staticmethod
    async def get_chat_session(group_id: int, member_id: int) -> str:
        if result := list(
            orm.fetchone(
                select(
                    ChatSession.member_session
                ).where(
                    ChatSession.group_id == group_id,
                    ChatSession.member_id == member_id
                )
            )
        ):
            return str(result[0][0])
        else:
            new_session = list(orm.fetchall(select(ChatSession.member_session).order_by(desc(ChatSession.member_session))))
            new_session = new_session[0][0] + 1 if new_session else 1
            logger.info(f"new_session for {group_id} -> {member_id}: {new_session}")
            try:
                orm.add(
                    ChatSession,
                    {
                        "group_id": group_id,
                        "member_id": member_id,
                        "member_session": new_session
                    }
                )
                return str(new_session)
            except Exception as e:
                logger.error(traceback.format_exc())
                orm.session.rollback()
예제 #7
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        message_serialization = message.asSerializationString().replace(
            "[mirai:source:" +
            re.findall(r'\[mirai:source:(.*?)]',
                       message.asSerializationString(), re.S)[0] + "]", "")

        if re.match(r"添加功能关键词#[\s\S]*#[\s\S]*", message_serialization):
            if await user_permission_require(group, member, 2):
                set_result(message, await
                           self.update_keyword(message_serialization))
            else:
                set_result(
                    message,
                    MessageItem(MessageChain.create([Plain(text="权限不足,爬")]),
                                QuoteSource(GroupStrategy())))

        elif re.match(r"删除功能关键词#[\s\S]*", message_serialization):
            if await user_permission_require(group, member, 2):
                set_result(
                    message, await self.delete_keyword(app, group, member,
                                                       message_serialization))
            else:
                set_result(
                    message,
                    MessageItem(MessageChain.create([Plain(text="权限不足,爬")]),
                                QuoteSource(GroupStrategy())))

        if re.match(r"\[mirai:image:{.*}\..*]", message_serialization):
            message_serialization = re.findall(r"\[mirai:image:{(.*?)}\..*]",
                                               message_serialization, re.S)[0]

        if resp_functions := list(
                orm.fetchall(
                    select(TriggerKeyword.function).where(
                        TriggerKeyword.keyword == message_serialization))):
            resp_functions = resp_functions[0]
            tfunc = None
            for function in resp_functions:
                if function in self.functions:
                    tfunc = function
                    break
            if not tfunc:
                return None
            else:
                await update_user_call_count_plus1(
                    group, member, user_called_column_index[tfunc],
                    user_called_name_index[tfunc])
                if tfunc == "setu":
                    if await get_setting(group.id, Setting.setu):
                        if await get_setting(group.id, Setting.r18):
                            set_result(
                                message, await
                                self.get_image_message(group, member,
                                                       "setu18"))
                        else:
                            set_result(
                                message, await
                                self.get_image_message(group, member, tfunc))
                    else:
                        set_result(
                            message,
                            MessageItem(
                                MessageChain.create(
                                    [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]),
                                Normal(GroupStrategy())))
                elif tfunc == "realHighq":
                    if await get_setting(
                            group.id, Setting.real) and await get_setting(
                                group.id, Setting.real_high_quality):
                        set_result(
                            message, await
                            self.get_image_message(group, member, tfunc))
                    else:
                        set_result(
                            message,
                            MessageItem(
                                MessageChain.create(
                                    [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]),
                                Normal(GroupStrategy())))
                else:
                    if await get_setting(group.id,
                                         setting_column_index[tfunc]):
                        set_result(
                            message, await
                            self.get_image_message(group, member, tfunc))
                    else:
                        set_result(
                            message,
                            MessageItem(
                                MessageChain.create(
                                    [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]),
                                Normal(GroupStrategy())))
예제 #8
0
    async def delete_keyword(app: GraiaMiraiApplication,
                             message_serialization: str, group: Group,
                             member: Member):
        try:
            _, keyword = message_serialization.split("#")
        except ValueError:
            return MessageItem(
                MessageChain.create([
                    Plain(text="设置格式:\n添加关键词#关键词/图片#回复文本/图片\n"),
                    Plain(text="注:目前不支持文本中含有#!")
                ]), QuoteSource(GroupStrategy()))
        keyword = keyword.strip()
        if re.match(r"\[mirai:image:{.*}\..*]", keyword):
            keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword,
                                 re.S)[0]

        if results := orm.fetchall(
                select(KeywordReply).where(KeywordReply.keyword == keyword)):
            replies = list()
            for result in results:
                content_type = result[1]
                content = result[2]
                content_md5 = result[3]
                replies.append([content_type, content, content_md5])

            msg = [Plain(text=f"关键词{keyword}目前有以下数据:\n")]
            for i in range(len(replies)):
                msg.append(Plain(text=f"{i + 1}. "))
                msg.append(
                    Plain(text=replies[i][1]) if replies[i][0] == "text" else
                    Image.fromUnsafeBytes(base64.b64decode(replies[i][1])))
                msg.append(Plain(text="\n"))
            msg.append(Plain(text="请发送你要删除的回复编号"))
            try:
                await app.sendGroupMessage(group, MessageChain.create(msg))
            except AccountMuted:
                return None

            inc = InterruptControl(AppCore.get_core_instance().get_bcc())

            @Waiter.create_using_function([GroupMessage])
            def number_waiter(waiter_group: Group, waiter_member: Member,
                              waiter_message: MessageChain):
                if all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id,
                        waiter_message.asDisplay().isnumeric()
                        and 0 < int(waiter_message.asDisplay()) <= len(replies)
                ]):
                    return int(waiter_message.asDisplay())
                elif all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id
                ]):
                    return -1

            number = await inc.wait(number_waiter)
            if number == -1:
                return MessageItem(
                    MessageChain.create([Plain(text="非预期回复,进程退出")]),
                    Normal(GroupStrategy()))
            elif 1 <= number <= len(replies):
                try:
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            Plain(text="你确定要删除下列回复吗(是/否):\n"),
                            Plain(text=keyword),
                            Plain(text="\n->\n"),
                            Plain(text=replies[number -
                                               1][1]) if replies[number - 1][0]
                            == "text" else Image.fromUnsafeBytes(
                                base64.b64decode(replies[number - 1][1]))
                        ]))
                except AccountMuted:
                    return None

            @Waiter.create_using_function([GroupMessage])
            def confirm_waiter(waiter_group: Group, waiter_member: Member,
                               waiter_message: MessageChain):
                if all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id
                ]):
                    if re.match(r"[是否]", waiter_message.asDisplay()):
                        return waiter_message.asDisplay()
                    else:
                        return ""

            result = await inc.wait(confirm_waiter)
            if not result:
                return MessageItem(
                    MessageChain.create([Plain(text="非预期回复,进程退出")]),
                    Normal(GroupStrategy()))
            elif result == "是":
                try:
                    orm.delete(
                        KeywordReply, {
                            "keyword": keyword,
                            "reply_md5": replies[number - 1][2],
                            "reply_type": replies[number - 1][0]
                        })
                    return MessageItem(
                        MessageChain.create([Plain(text=f"删除成功")]),
                        Normal(GroupStrategy()))
                except Exception as e:
                    logger.error(traceback.format_exc())
                    orm.session.rollback()
                    return MessageItem(
                        MessageChain.create([Plain(text=str(e))]),
                        Normal(GroupStrategy()))
            else:
                return MessageItem(MessageChain.create([Plain(text="进程退出")]),
                                   Normal(GroupStrategy()))
예제 #9
0
async def getGroups():
    groups = orm.fetchall(
        select(Setting.group_id,
               Setting.group_name).where(Setting.active == True))
    return [{"value": group[0], "label": group[1]} for group in groups]