def __init__(self, chain: list):
     self.__chain = chain
     head = HeadHandler()
     self.__head_handler = head
     node = head
     for handler in chain:
         node = node.set_next(handler)
         self.__chain_names.append(handler.__name__)
     AppCore.get_core_instance().set_group_chain(self.__chain)
     logger.success("\n----------------------------------------------\n职责链加载成功,目前链序:\n" + "\n".join([f"{handler.__name__.ljust(40) + handler.__description__}" for handler in self.__chain]) + "\n----------------------------------------------")
Exemple #2
0
async def getStatus():
    return {
        "functionCalled":
        len(await orm.fetchall(
            select(FunctionCalledRecord).where(
                FunctionCalledRecord.time >= datetime.date.today()))),
        "handlerCount":
        len(AppCore.get_core_instance().get_group_chains()),
        "sayaCount":
        len(AppCore.get_core_instance().get_saya_channels())
    }
Exemple #3
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     message_text = message.asDisplay()
     if message_text == "/chains":
         app_core = AppCore.get_core_instance()
         return MessageItem(
             MessageChain.create([
                 Plain(text="目前链序:\n    " + "\n    ".join([
                     handler.__name__
                     for handler in app_core.get_group_chain()
                 ]))
             ]), Normal(GroupStrategy()))
     elif message_text == "/help":
         return MessageItem(
             MessageChain.create([
                 Plain(
                     text=
                     "SAGIRI-BOT文档地址:http://doc.sagiri-web.com/web/#/51?page_id=284"
                 )
             ]), QuoteSource(GroupStrategy()))
     elif message_text == "!help":
         app_core = AppCore.get_core_instance()
         content = "目前已加载Handler:\n"
         index = 0
         for handler in app_core.get_group_chains():
             index = index + 1
             content += f"{index}. {handler.__name__}\n"
         content += "请回复 /help 序号来查看Handler描述"
         return MessageItem(MessageChain.create([Plain(text=content)]),
                            QuoteSource(GroupStrategy()))
     elif re.match(r"!help [0-9]+", message_text):
         chains = AppCore.get_core_instance().get_group_chains()
         length = len(chains)
         index = int(message_text[6:])
         if index > length:
             return MessageItem(
                 MessageChain.create([Plain(text="非法编号!请检查发送的信息!")]),
                 QuoteSource(GroupStrategy()))
         else:
             content = "Handler详情:\n"
             handler = chains[index - 1]
             content += f"名称:{handler.__name__}\n"
             content += f"描述:{handler.__description__}\n"
             content += f"使用方法:{handler.__usage__}"
             return MessageItem(MessageChain.create([Plain(text=content)]),
                                QuoteSource(GroupStrategy()))
     else:
         return None
Exemple #4
0
    async def handle(app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        if message.asDisplay() == "搜番":
            await update_user_call_count_plus1(group, member,
                                               UserCalledCount.search,
                                               "search")
            if not await get_setting(group.id, Setting.bangumi_search):
                return MessageItem(
                    MessageChain.create([Plain(text="搜番功能未开启呐~请联系管理员哦~")]),
                    Normal(GroupStrategy()))
            try:
                await app.sendGroupMessage(
                    group,
                    MessageChain.create(
                        [At(member.id),
                         Plain("请在30秒内发送要搜索的图片呐~")]))
            except AccountMuted:
                logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!")
                return None

            image_get = None
            message_received = None

            @Waiter.create_using_function([GroupMessage])
            def waiter(event: GroupMessage, waiter_group: Group,
                       waiter_member: Member, waiter_message: MessageChain):
                nonlocal image_get
                nonlocal message_received
                if time.time() - start_time < 30:
                    if all([
                            waiter_group.id == group.id,
                            waiter_member.id == member.id,
                            len(waiter_message[Image]) == len(
                                waiter_message.__root__) - 1
                    ]):
                        image_get = True
                        message_received = waiter_message
                        return event
                else:
                    logger.warning("等待用户超时!BangumiSearchHandler进程推出!")
                    return event

            bcc = AppCore.get_core_instance().get_bcc()
            inc = InterruptControl(bcc)
            start_time = time.time()
            await inc.wait(waiter)
            if image_get:
                logger.success("收到用户图片,启动搜索进程!")
                try:
                    await app.sendGroupMessage(
                        group,
                        await BangumiSearchHandler.search_bangumi(
                            message_received[Image][0]),
                        quote=message_received[Source][0])
                except AccountMuted:
                    logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!")
                    pass
            return None
        else:
            return None
Exemple #5
0
    def __init__(self, chain: list):
        self.__chain = chain
        # head = HeadHandler()
        # self.__head_handler = head
        for handler in chain:
            self.__handlers.append(handler.handle)
            self.__chain_names.append(handler.__name__)
            if isinstance(handler, ChatRecordHandler):
                self.__chat_record_handler = handler
            if isinstance(handler, RepeaterHandler):
                self.__repeat_handler = handler
            else:
                self.__other_handlers.append(handler.handle)

        AppCore.get_core_instance().set_group_chain(self.__handlers)
        logger.success(
            "\n----------------------------------------------\n加载成功,目前加载Handler:\n"
            + "\n".join([
                f"{handler.__name__.ljust(40) + handler.__description__}"
                for handler in self.__chain
            ]) + "\n----------------------------------------------")
    async def delete_keyword(app: GraiaMiraiApplication, group: Group,
                             member: Member,
                             message_serialization: str) -> MessageItem:
        _, keyword = message_serialization.split("#")
        if re.match(r"\[mirai:image:{.*}\..*]", keyword):
            keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword,
                                 re.S)[0]
        if record := await orm.fetchone(
                select(TriggerKeyword.function).where(
                    TriggerKeyword.keyword == keyword)):
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Plain(
                        text=f"查找到以下信息:\n{keyword} -> {record[0]}\n是否删除?(是/否)")
                ]))
            inc = InterruptControl(AppCore.get_core_instance().get_bcc())

            @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:
                    await orm.delete(TriggerKeyword,
                                     [TriggerKeyword.keyword == keyword])
                except:
                    logger.error(traceback.format_exc())
                    return MessageItem(
                        MessageChain.create([Plain(text="发生错误!请查看日志!")]),
                        QuoteSource(GroupStrategy()))
                return MessageItem(
                    MessageChain.create([Plain(text=f"关键词 {keyword} 删除成功")]),
                    Normal(GroupStrategy()))
            else:
                return MessageItem(MessageChain.create([Plain(text="进程退出")]),
                                   Normal(GroupStrategy()))
Exemple #7
0
from SAGIRIBOT.frequency_limit_module import GlobalFrequencyLimitDict

with open('config.yaml', 'r', encoding='utf-8') as f:
    configs = yaml.load(f.read())

logger.add(f"{os.getcwd()}/log/common.log",
           level="INFO",
           retention=f"{configs['commonRetention']} days",
           encoding="utf-8")
logger.add(f"{os.getcwd()}/log/error.log",
           level="ERROR",
           retention=f"{configs['errorRetention']} days",
           encoding="utf-8")
logger.add(set_log)

core = AppCore(configs)

app = core.get_app()
bcc = core.get_bcc()
saya = core.get_saya()

ignore = ["__init__", "__pycache__"]
with saya.module_context():
    for module in os.listdir("SAGIRIBOT/Handler/Handlers"):
        if module in ignore:
            continue
        try:
            if os.path.isdir(module):
                saya.require(f"SAGIRIBOT.Handler.Handlers.{module}")
            else:
                saya.require(
from graia.application.event.mirai import *
from graia.application.event.messages import Group
from graia.application import GraiaMiraiApplication
from graia.application.message.elements.internal import *
from graia.application.exceptions import AccountMuted, UnknownTarget

from SAGIRIBOT.Core.AppCore import AppCore
from SAGIRIBOT.ORM.AsyncORM import Setting
from SAGIRIBOT.utils import get_config, get_setting

core: AppCore = AppCore.get_core_instance()
bcc = core.get_bcc()
app = core.get_app()


@bcc.receiver("MemberJoinEvent")
async def member_join(app: GraiaMiraiApplication, event: MemberJoinEvent):
    try:
        await app.sendGroupMessage(
            event.member.group.id,
            MessageChain.create([
                At(target=event.member.id),
                Plain(text="我是本群小可爱纱雾哟~欢迎呐~一起快活鸭~")
            ]))
    except AccountMuted:
        pass


@bcc.receiver("MemberLeaveEventQuit")
async def member_leave(app: GraiaMiraiApplication,
                       event: MemberLeaveEventQuit):
Exemple #9
0
from graia.application.event.messages import Group, Member
from graia.application.event.messages import GroupMessage
from graia.application.message.elements.internal import *
from graia.application import GraiaMiraiApplication
from graia.application.event.lifecycle import ApplicationLaunched

from SAGIRIBOT.Handler.MessageHandler import GroupMessageHandler
from SAGIRIBOT.MessageSender.MessageSender import GroupMessageSender
from SAGIRIBOT.Handler.Handlers import *
from SAGIRIBOT.Core.AppCore import AppCore

with open('config.yaml', 'r', encoding='utf-8') as f:
    configs = yaml.load(f.read())

core = AppCore(configs)

app = core.get_app()
bcc = core.get_bcc()
"""
职责链模式,可自行调整Handler顺序,顺序执行
其中
    ChatRecordHandler 建议放在第一个,不会中途跳出,处理后继续向下
    RepeaterHandler 建议放在最后一个,防止复读其他Handler的指令
可自由增减Handler
"""
g_handler: GroupMessageHandler = GroupMessageHandler([
    ChatRecordHandler(),
    BotManagementHandler(),
    StatusPresenterHandler(),
    ImageSenderHandler(),
Exemple #10
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()))
Exemple #11
0
def single_task(handle_func, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member):
    asyncio.run_coroutine_threadsafe(handle_func(app, message, group, member), AppCore.get_core_instance().get_loop())