예제 #1
0
async def main(kwargs: dict):
    message = kwargs['trigger_msg']
    message = message.split(' ')
    assets = os.path.abspath('assets/arcaea')
    if len(message) > 1:
        if message[1] == 'initialize':
            if database.check_superuser(kwargs):
                await arcb30init(kwargs)
            else:
                await sendMessage(kwargs, '权限不足')
                return
        else:
            if not os.path.exists(assets):
                msg = {
                    'text':
                    '未找到资源文件!请放置一枚arcaea的apk到机器人的assets目录并重命名为arc.apk后,使用~b30 initialize初始化资源。'
                }
            else:
                msg = await getb30(message[1])
    else:
        msg = {'text': '请输入好友码!~b30 <friendcode>'}

    if 'file' in msg:
        imgchain = MessageChain.create([Image.fromLocalFile(msg['file'])])
    else:
        imgchain = False
    msgchain = MessageChain.create([Plain(msg['text'])])
    if imgchain:
        msgchain = msgchain.plusWith(imgchain)
    await sendMessage(kwargs, msgchain)
예제 #2
0
async def set_start_wiki(kwargs: dict):
    if Group in kwargs:
        if check_permission(kwargs):
            command = kwargs['trigger_msg']
            command = re.sub(r'^wiki_start_site ', '', command)
            check = await check_wiki_available(command)
            if check:
                result = database.add_start_wiki('start_wiki_link_group',
                                                 kwargs[Group].id, check[0])
                await sendMessage(
                    kwargs, MessageChain.create([Plain(result + check[1])]))
            else:
                result = '错误:此Wiki不是一个有效的MediaWiki/尝试建立连接超时。'
                await sendMessage(kwargs, MessageChain.create([Plain(result)]))
        else:
            result = '你没有使用该命令的权限。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
    if Friend in kwargs:
        command = kwargs['trigger_msg']
        command = re.sub(r'^wiki_start_site ', '', command)
        check = await check_wiki_available(command)
        if check:
            result = database.add_start_wiki('start_wiki_link_self',
                                             kwargs[Friend].id, check[0])
            await sendMessage(kwargs,
                              MessageChain.create([Plain(result + check[1])]))
        else:
            result = '错误:此Wiki不是一个有效的MediaWiki/尝试建立连接超时。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
예제 #3
0
async def main(kwargs: dict):
    command = re.sub('^user ', '', kwargs['trigger_msg'])
    commandsplit = command.split(' ')
    mode = None
    metaurl = None
    username = None
    if Group in kwargs:
        id = kwargs[Group].id
    if Friend in kwargs:
        id = kwargs[Friend].id

    if '-r' in commandsplit:
        mode = '-r'
        commandsplit.remove('-r')
        command = ' '.join(commandsplit)
    if '-p' in commandsplit:
        mode = '-p'
        commandsplit.remove('-p')
        command = ' '.join(commandsplit)
    match_gpsite = re.match(r'~(.*?) (.*)', command)
    if match_gpsite:
        metaurl = f'https://{match_gpsite.group(1)}.gamepedia.com/api.php'
        username = match_gpsite.group(2)
    else:
        match_interwiki = re.match(r'(.*?):(.*)', command)
        if match_interwiki:
            if Group in kwargs:
                table = 'custom_interwiki_group'
            if Friend in kwargs:
                table = 'custon_interwiki_self'
            get_iw = get_custom_interwiki(table, id, match_interwiki.group(1))
            if get_iw:
                metaurl = get_iw
                username = match_interwiki.group(2)
        else:
            if Group in kwargs:
                table = 'start_wiki_link_group'
            if Friend in kwargs:
                table = 'start_wiki_link_self'
            get_url = get_start_wiki(table, id)
            if get_url:
                metaurl = get_url
                username = command
            else:
                await sendMessage(kwargs, '未设置起始Interwiki。')
    result = await GetUser(metaurl, username, mode)
    if result:
        matchimg = re.match('.*\[\[uimgc:(.*)]]', result)
        if matchimg:
            if Group in kwargs:
                mth = UploadMethods.Group
            if Friend in kwargs:
                mth = UploadMethods.Friend
            imgchain = MessageChain.create([Image.fromLocalFile(matchimg.group(1), method=mth)])
            result = re.sub('\[\[uimgc:.*]]', '', result)
            msgchain = MessageChain.create([Plain(result)])
            msgchain = msgchain.plusWith(imgchain)
        else:
            msgchain = MessageChain.create([Plain(result)])
        await sendMessage(kwargs, msgchain)
예제 #4
0
async def reFriend(app: GraiaMiraiApplication, sender: Friend, message: MessageChain):
    text = message.asDisplay().strip().replace('\r\n', '\n').replace('\r', '\n')
    keywords = ['个人课表', '个人课程表', 'selfcourse', 'owncourse', 'self course', 'own course', 'privatecourse']
    if any([text.lower().startswith(opt) for opt in ('.owncourse', '。owncourse', '.groupcourse', '。groupcourse')]):
        msg = await Command.parseCommand(text, qq=sender.id)
        if not msg:
            msg = '命令执行失败,请检查格式'
        await app.sendFriendMessage(sender, MessageChain.create([Plain(msg)]))
    elif (text.lower() in keywords) or at_me(app, message) and any(keyword in text.lower() for keyword in keywords):
        await app.sendFriendMessage(sender, MessageChain.create([await getCourseTable(f'qq{sender.id}')]))
예제 #5
0
async def interwiki(kwargs: dict):
    command = kwargs['trigger_msg']
    command = re.sub(r'^interwiki ', '', command)
    command = command.split(' ')
    print(command)
    if Group in kwargs:
        check = check_permission(kwargs)
        if not check:
            result = '你没有使用该命令的权限,请联系管理员进行操作。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
            return
    table = 'custom_interwiki_' + kwargs[Target].target_from
    htable = 'request_headers_' + kwargs[Target].target_from
    target = kwargs[Target].id
    if command[0] in ['add', 'set']:
        command = ' '.join(command[1:])
        command = re.sub(' ', '>', command)
        iw = command.split('>')
        if len(iw) == 1 or len(iw) > 2:
            await sendMessage(kwargs,
                              '错误:命令不合法:~wiki iw add <interwiki> <url>')
            return
        check = await wikilib.wikilib().check_wiki_available(
            iw[1], headers=WikiDB.config_headers('get', htable, target))
        if check[0]:
            result = WikiDB.config_custom_interwiki('add', table, target,
                                                    iw[0], check[0])
            await sendMessage(
                kwargs,
                MessageChain.create([Plain(result + f'{iw[0]} > {check[1]}')]))
        else:
            if check[1] == 'Timeout':
                result = '错误:尝试建立连接超时。'
            else:
                result = '错误:此站点也许不是一个有效的Mediawiki:' + check[1]
            link = re.match(r'^(https?://).*', iw[1])
            if not link:
                result = '错误:所给的链接没有指明协议头(链接应以http://或https://开头)。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
    elif command[0] == 'del':
        result = WikiDB.config_custom_interwiki('del', table, target,
                                                command[1])
        await sendMessage(kwargs, MessageChain.create([Plain(result)]))
    elif command[0] == 'list':
        query_database = WikiDB.get_custom_interwiki_list(table, target)
        if query_database:
            result = '当前设置了以下Interwiki:\n' + query_database
            await sendMessage(kwargs, result)
        else:
            await sendMessage(
                kwargs,
                '当前没有设置任何Interwiki,使用~wiki iw add <interwiki> <api_endpoint_link>添加一个。'
            )
    else:
        await sendMessage(kwargs, '命令不合法,参数应为add/del/list。')
예제 #6
0
async def sendMsg(app: GraiaMiraiApplication,
                  msg: MESSAGE_T,
                  qq: int = None,
                  group: int = None):
    if isinstance(msg, str):
        msg = MessageChain.create([Plain(msg)])
    if isinstance(msg, ExternalElement):
        msg = MessageChain.create([msg])
    msg = msg.asSendable()
    if qq:
        asyncio.create_task(app.sendFriendMessage(qq, msg))
    if group:
        asyncio.create_task(app.sendGroupMessage(group, msg))
예제 #7
0
 async def solve_receive_msg(self, message: MessageChain):
     plain = message.asDisplay()
     if re.search(EroImage.cmd_receive, plain):
         self.set_receive_flag(True)
         return self.msg_receive
     elif re.search(EroImage.cmd_receive_done, plain):
         self.set_receive_flag(False)
         return self.msg_receive_done
     if self.receive_flag:
         images = message.get(Image)
         if len(images) == 0:
             return False
         else:
             return await self.receive_image(images)
예제 #8
0
async def GroupMessageHandler(group: Group, member: Member, msgchain: MessageChain):
    Record.addMessage(ChatRecord(messagechain=msgchain, group=group, member=member))
    if msgchain.has(Plain):
        text = msgchain.get(Plain)[0].text
        if text == '#词云生成':
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Plain('生成中...')]
            ))
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Image.fromLocalFile(wordCloudGenerator(Record.getAGroupMessageList(group.id)))]
            ))
        elif text == '#今日消息图表':
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Plain('生成中...')]
            ))
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Image.fromLocalFile(summaryGraphGenerator("today", Record.getAGroupMessageList(group.id)))]
            ))
        elif text == '#总消息图表':
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Plain('生成中...')]
            ))
            await app.sendGroupMessage(group, MessageChain.create(
                [At(member.id),
                 Image.fromLocalFile(summaryGraphGenerator("total", Record.getAGroupMessageList(group.id)))]
            ))
예제 #9
0
파일: __init__.py 프로젝트: nyancatda/bot
async def search(kwargs: dict, cmd: list):
    try:
        obj = cmd[1]
        result = await query(
            'https://api.github.com/search/repositories?q=' + obj, 'json')
        items = result['items']
        item_count_expected = int(
            result['total_count']) if result['total_count'] < 5 else 5
        items_out = []
        for item in items:
            try:
                items_out.append(
                    str(item['full_name'] + ': ' + item['html_url']))
            except TypeError:
                continue
        footnotes = f"另有 {result['total_count'] - 5} 个结果未显示。" if item_count_expected == 5 else ''
        msg = f"搜索成功:共 {result['total_count']} 个结果。\n" + '\n'.join(
            items_out[0:item_count_expected]) + f'\n{footnotes}'

        is_dirty = await dirty_check(msg) or await darkCheck(msg)
        if is_dirty:
            msg = 'https://wdf.ink/6OUp'

        await sendMessage(kwargs, MessageChain.create([Plain(msg)]))
    except Exception as error:
        await sendMessage(kwargs, '发生错误:' + str(error))
        traceback.print_exc()
예제 #10
0
async def sendMessage(kwargs: dict, msgchain, Quote=True):
    """
    用于发送一条消息,兼容Group和Friend消息。
    :param kwargs: 函数传入的dict
    :param msgchain: 消息链,若传入str则自动创建一条带有Plain元素的消息链
    :param Quote: 是否引用传入dict中的消息(仅对Group消息有效)
    :return: 被发送的消息链
    """
    if isinstance(msgchain, str):
        if msgchain == '':
            msgchain = '发生错误:机器人尝试发送空文本消息,请联系机器人开发者解决问题。'
        msgchain = MessageChain.create([Plain(msgchain)])
    QuoteTarget = None
    if 'TEST' not in kwargs:
        if Quote:
            QuoteTarget = kwargs[MessageChain][Source][0].id
    if Group in kwargs:
        send = await app.sendGroupMessage(kwargs[Group],
                                          msgchain,
                                          quote=QuoteTarget)
        return send
    if Friend in kwargs:
        send = await app.sendFriendMessage(kwargs[Friend], msgchain)
        return send
    if 'From' in kwargs:
        if kwargs['From'] == 'Group':
            send = await app.sendGroupMessage(kwargs['ID'], msgchain)
            return send
        if kwargs['From'] == 'Friend':
            send = await app.sendFriendMessage(kwargs['ID'], msgchain)
            return send
    if 'TEST' in kwargs:
        print(msgchain.asDisplay())
예제 #11
0
파일: __init__.py 프로젝트: nyancatda/bot
 async def bedrock_dungeons():
     url = 'https://bugs.mojang.com/rest/api/2/project/11901/versions'
     try:
         version_file = os.path.abspath(
             './assets/mcversion_jira-dungeons.txt')
         logger_info('Checking Jira mcv-bedrock...')
         verlist = getfileversions(version_file)
         file = await get_data(url, 'json')
         release = []
         for v in file:
             if not v['archived']:
                 release.append(v['name'])
         for x in release:
             if x not in verlist:
                 logger_info(f'huh, we find {x}.')
                 for qqgroup in check_enable_modules_all(
                         'group_permission', 'mcv_jira_rss'):
                     try:
                         await app.sendGroupMessage(
                             int(qqgroup),
                             MessageChain.create([
                                 Plain(
                                     f'Jira已更新Dungeons {x}。\n(Jira上的信息仅作版本号预览用,不代表商店已更新此版本)'
                                 )
                             ]))
                         await asyncio.sleep(0.5)
                     except Exception:
                         traceback.print_exc()
                 for qqfriend in check_enable_modules_all(
                         'friend_permission', 'mcv_jira_rss'):
                     try:
                         await app.sendFriendMessage(
                             int(qqfriend),
                             MessageChain.create([
                                 Plain(
                                     f'Jira已更新Dungeons {x}。\n(Jira上的信息仅作版本号预览用,不代表启动器已更新此版本)'
                                 )
                             ]))
                         await asyncio.sleep(0.5)
                     except Exception:
                         traceback.print_exc()
                 addversion = open(version_file, 'a')
                 addversion.write('\n' + x)
                 addversion.close()
         logger_info('jira mcv-dungeons checked.')
     except Exception:
         traceback.print_exc()
예제 #12
0
 def waiter(waiter_friend: Friend, waiter_message: MessageChain):
     if all([
             waiter_friend.id == kwargs[Friend].id,
     ]):
         if waiter_message.asDisplay() in confirm_command:
             return True
         else:
             return False
async def newbie(app):
    logger_info('Subbot newbie launched')
    url = 'https://minecraft-zh.gamepedia.com/api.php?action=query&list=logevents&letype=newusers&format=json'
    while True:
        try:
            file = await get_data(url, 'json')
            qq = []
            for x in file['query']['logevents'][:]:
                qq.append(x['title'])
            while True:
                c = 'f'
                try:
                    qqqq = await get_data(url, 'json')
                    for xz in qqqq['query']['logevents'][:]:
                        if xz['title'] in qq:
                            pass
                        else:
                            s = await check([
                                UTC8(xz['timestamp'], 'onlytime') + '新增新人:' +
                                xz['title']
                            ])
                            if s.find("<吃掉了>") != -1 or s.find(
                                    "<全部吃掉了>") != -1:
                                await app.sendGroupMessage(
                                    731397727,
                                    MessageChain.create([
                                        Plain(
                                            s +
                                            '\n检测到外来信息介入,请前往日志查看所有消息。Special:日志?type=newusers'
                                        )
                                    ]).asSendable())
                            else:
                                await app.sendGroupMessage(
                                    731397727,
                                    MessageChain.create([Plain(s)
                                                         ]).asSendable())
                            c = 't'
                except Exception:
                    pass
                if c == 't':
                    break
                else:
                    await asyncio.sleep(10)
            await asyncio.sleep(5)
        except Exception:
            traceback.print_exc()
예제 #14
0
async def bugtracker(kwargs: dict):
    msg = kwargs['trigger_msg']
    msg = re.sub('bug ', '', msg)
    q = re.match(r'(.*)-(.*)', msg)
    if q:
        result = await bugtracker_get(q.group(1) + '-' + q.group(2))
        msgchain = MessageChain.create([Plain(result)])
        await sendMessage(kwargs, msgchain)
예제 #15
0
 def waiter(waiter_group: Group, waiter_member: Member,
            waiter_message: MessageChain):
     if all([
             waiter_group.id == kwargs[Group].id,
             waiter_member.id == kwargs[Member].id,
     ]):
         if waiter_message.asDisplay() in confirm_command:
             return True
         else:
             return False
예제 #16
0
파일: __init__.py 프로젝트: nyancatda/bot
async def main(kwargs: dict):
    command = re.sub('^user ', '', kwargs['trigger_msg'])
    commandsplit = command.split(' ')
    mode = None
    metaurl = None
    username = None
    id = kwargs[Target].id

    if '-r' in commandsplit:
        mode = '-r'
        commandsplit.remove('-r')
        command = ' '.join(commandsplit)
    if '-p' in commandsplit:
        mode = '-p'
        commandsplit.remove('-p')
        command = ' '.join(commandsplit)
    table = 'start_wiki_link_' + kwargs[Target].target_from
    get_url = WikiDB.get_start_wiki(table, id)
    if get_url:
        metaurl = get_url
        username = command
    else:
        await sendMessage(kwargs, '未设置起始wiki。')
    match_interwiki = re.match(r'(.*?):(.*)', command)
    if match_interwiki:
        table = 'custom_interwiki_' + kwargs[Target].target_from
        get_iw = WikiDB.get_custom_interwiki(table, id,
                                             match_interwiki.group(1))
        if get_iw:
            metaurl = get_iw
            username = match_interwiki.group(2)
    result = await GetUser(metaurl, username, mode)
    if result:
        matchimg = re.match('.*\[\[uimgc:(.*)]]', result)
        if matchimg:
            imgchain = MessageChain.create(
                [Image.fromLocalFile(matchimg.group(1))])
            result = re.sub('\[\[uimgc:.*]]', '', result)
            msgchain = MessageChain.create([Plain(result)])
            msgchain = msgchain.plusWith(imgchain)
        else:
            msgchain = MessageChain.create([Plain(result)])
        await sendMessage(kwargs, msgchain)
예제 #17
0
    async def handle_manager_msg(self, message: MessageChain, sender, friend):
        reply = await self.ero_image.solve_receive_msg(message)
        if reply is not None:
            await sender(Plain(reply))
            return

        if config.SERVER_FLAG:
            for cmd in Arknights.cmd:
                if re.search(cmd, message.asDisplay()):
                    await Arknights().run(sender)
                    return
예제 #18
0
def at_me(app: GraiaMiraiApplication, message: MessageChain):
    try:
        at: T.Optional[T.Union[At, Element]] = message.getFirst(At)
    except IndexError:
        return False
    except:
        raise
    if at:
        return at.target == app.connect_info.account
    else:
        return False
예제 #19
0
 async def wrapper(message: MESSAGE_T, *, at_sender: bool = False):
     if isinstance(message, ExternalElement):
         message = MessageChain.create([message])
     if isinstance(message, str):
         message = MessageChain.create([Plain(message)])
     if at_sender:
         if isinstance(message, MessageChain):
             message = MessageChain.join(
                 MessageChain.create([At(Sender.id)]), message)
         else:
             raise TypeError(
                 f"not supported type for reply: {message.__class__.__name__}"
             )
     message = message.asSendable()
     if event_type == "GroupMessage":
         await app.sendGroupMessage(sender.group, message)
     elif event_type == "FriendMessage":
         await app.sendFriendMessage(sender, message)
     else:
         raise ValueError("Not supported event type")
예제 #20
0
async def make_illust_message(illust: dict) -> MessageChain:
    """
    将给定illust按照模板转换为message
    :param illust: 给定illust
    :return: 转换后的message
    """
    msg = Template(reply_pattern).render(
        title=Plain(illust["title"]),
        author=Plain(illust["user"]["name"]),
        author_id=Plain(illust["user"]["id"]),
        caption=Plain(illust["caption"]),
        tags=Plain(" ".join(map(lambda x: x["name"], illust["tags"]))),
        id=Plain(str(illust["id"]))
    )

    illegal_tags = []
    for tag in block_tags:
        if has_tag(illust, tag):
            illegal_tags.append(tag)

    if len(illegal_tags) > 0:
        block_msg = Template(block_message).render(
            tag=Plain(' '.join(illegal_tags))
        )
        if block_mode == "escape_img":
            return msg.plusWith(block_msg)
        elif block_mode == "fully_block":
            return block_msg
        else:
            raise ValueError("illegal block_mode value: " + block_mode)

    try:
        b = await cache_illust(illust)
        img_msg = MessageChain.create([Image.fromUnsafeBytes(b)])
    except asyncio.TimeoutError:
        img_msg = MessageChain.create([Plain(download_timeout_message)])
    except Exception as e:
        img_msg = MessageChain.create([Plain(f"{type(e)} {str(e)}")])
    msg.plus(img_msg)

    return msg
예제 #21
0
파일: __init__.py 프로젝트: nyancatda/bot
async def set_start_wiki(kwargs: dict):
    command = kwargs['trigger_msg']
    command = re.sub(r'^wiki_start_site ', '', command)
    if Group in kwargs:
        if not check_permission(kwargs):
            result = '你没有在群内使用该命令的权限,请联系管理员进行操作。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
            return
    check = await wikilib.wikilib().check_wiki_available(command)
    if check[0]:
        result = WikiDB.add_start_wiki('start_wiki_link_' + kwargs[Target].target_from, kwargs[Target].id, check[0])
        await sendMessage(kwargs, MessageChain.create([Plain(result + check[1])]))
    else:
        if check[1] == 'Timeout':
            result = '错误:尝试建立连接超时。'
        else:
            result = '错误:此站点也许不是一个有效的Mediawiki:' + check[1]
        link = re.match(r'^(https?://).*', command)
        if not link:
            result = '错误:所给的链接没有指明协议头(链接应以http://或https://开头)。'
        await sendMessage(kwargs, MessageChain.create([Plain(result)]))
예제 #22
0
    async def __on_receive(self, app: GraiaMiraiApplication,
                           subject: T.Union[Group, Friend],
                           message: MessageChain) -> T.NoReturn:
        src = message.get(Source)
        if len(src) == 0:
            src = None
        else:
            src = src[0]

        channel = asyncio.Queue(1)

        async def consumer(channel: asyncio.Queue):
            while True:
                try:
                    msg = await channel.get()
                    # logger.info("我摸到了!")
                    await reply(app, subject, msg, src)
                    # logger.info("我发完了!")
                    channel.task_done()
                except asyncio.CancelledError as exc:
                    # logger.info("我溜了!")
                    break
                except Exception as exc:
                    logger.exception(exc)
                    channel.task_done()

        consumer_task = asyncio.create_task(consumer(channel))

        try:
            for h in self.handlers:
                handler: AbstractMessageHandler = h["handler"]
                allow_group: T.Optional[T.Sequence[int]] = h["allow_group"]
                allow_friend: T.Optional[T.Sequence[int]] = h["allow_friend"]

                # 检查发送者是否有权限
                if isinstance(subject, Group):
                    if (allow_group is not None) and (subject.id not in allow_group):
                        continue
                elif isinstance(subject, Friend):
                    if (allow_friend is not None) and (subject.id not in allow_friend):
                        continue

                # 若handler拦截了这条消息
                try:
                    if await handler.handle(app, subject, message, channel):
                        break
                except Exception as exc:
                    logger.exception(exc)
                    pass
        finally:
            await channel.join()
            consumer_task.cancel()
예제 #23
0
    async def generate_reply(
        self, app: GraiaMiraiApplication, subject: T.Union[Group, Friend],
        message: MessageChain
    ) -> T.AsyncGenerator[T.Union[str, MessageChain], None]:
        mode = self.__find_ranking_mode(message)
        if mode is None:
            return

        begin, end = self.__find_ranges(message)
        logger.info(f"{self.tag}: [{mode}] [{begin}-{end}]")

        illusts = await get_illusts(search_func=papi.illust_ranking,
                                    mode=mode,
                                    search_item_limit=end)

        if isinstance(subject, Group):
            item_per_msg = self.item_per_group_message
        elif isinstance(subject, Friend):
            item_per_msg = self.item_per_friend_message
        else:
            raise TypeError(
                f"type(subject) expect Group or Friend, got {type(subject)}.")

        msg = MessageChain.create([])
        item_cur_msg = 0
        rank = begin
        for illust in illusts[begin - 1:]:
            msg.plus(self.__make_msg(rank, illust))
            item_cur_msg = item_cur_msg + 1
            if item_cur_msg == item_per_msg:
                yield msg
                msg = MessageChain.create([])
                item_cur_msg = 0
            rank = rank + 1

        if item_cur_msg > 0:
            yield msg

        logger.info(f"{self.tag}: [{mode}] [{begin}-{end}] ok")
예제 #24
0
    async def handle(self, app: GraiaMiraiApplication,
                     subject: T.Union[Group, Friend],
                     message: MessageChain,
                     channel: asyncio.Queue) -> bool:
        mode = self.__find_ranking_mode(message)
        if mode is None:
            return False

        begin, end = self.__find_ranges(message)
        logger.info(f"{self.tag}: [{mode}] [{begin}-{end}]")

        illusts = await get_illusts(search_func=papi.illust_ranking,
                                    mode=mode,
                                    search_item_limit=end)

        if isinstance(subject, Group):
            item_per_msg = self.item_per_group_message
        elif isinstance(subject, Friend):
            item_per_msg = self.item_per_friend_message
        else:
            raise TypeError(f"type(subject) expect Group or Friend, got {type(subject)}.")

        msg = MessageChain.create([])
        item_cur_msg = 0
        rank = begin
        for illust in illusts[begin - 1:]:
            msg.plus(self.__make_msg(rank, illust))
            item_cur_msg = item_cur_msg + 1
            if item_cur_msg == item_per_msg:
                await channel.put(msg)
                msg = MessageChain.create([])
                item_cur_msg = 0
            rank = rank + 1

        if item_cur_msg > 0:
            await channel.put(msg)

        logger.info(f"{self.tag}: [{mode}] [{begin}-{end}] ok")
        return True
예제 #25
0
    def __find_ranges(self, message: MessageChain) -> T.Tuple[int, int]:
        """
        找出消息中指定的排行范围
        :return: 排行范围的列表
        """
        content = message.asDisplay()

        regex = "[1-9][0-9]*-[1-9][0-9]*"
        res = re.search(regex, content)
        if res is None:
            res = re.search(regex, self.default_range)

        begin, end = res.group().split('-')
        return int(begin), int(end)
예제 #26
0
 def __find_ranking_mode(self, message: MessageChain) -> T.Optional[str]:
     """
     找出消息中所指定的排行榜种类
     :return: 排行榜种类,若没有则为None
     """
     content = message.asDisplay()
     for key in self.trigger:
         for x in self.trigger[key]:
             if x in content:
                 if key == "default":
                     return self.default_ranking_mode
                 else:
                     return key
     return None
예제 #27
0
async def rp(app: GraiaMiraiApplication, sender: T.Union[Member, Friend],
             event_type: "Type", message: MessageChain):
    text = formatMsg(message).strip().replace('\r', '\n')
    if text.startswith('.reply') or text.startswith('。reply'):
        app_reply = reply(app, sender, event_type)
        if event_type == 'FriendMessage':
            qq = sender.id
            group = None
        else:
            qq = None
            group = sender.group.id
        ret = Command.parseCommand(text, qq=qq, group=group)
        if ret:
            ret = MessageChain.fromSerializationString(ret)
            await app_reply(ret)
        else:
            await app_reply('添加失败,请检查语法')
    else:
        ret = Command.parse(text, sender=sender, event_type=event_type)
        if not ret: return
        ret = MessageChain.fromSerializationString(ret)
        app_reply = reply(app, sender, event_type)
        await app_reply(ret)
예제 #28
0
def repeater(runtime_var: dict, group_id: int,
             message: MessageChain) -> (bool, bool):
    """
    复读机.

    :param runtime_var: 运行时字典
    :param group_id: QQ群号
    :param message: 消息的MessageChain
    :return (bool: 是否复读, bool: 是否附带复读图片)
    """
    if not rc.hexists(group_id, "m_count"):
        rc.hset(group_id, "m_count", '0')
        rc.hset(group_id, "m_last_repeat", 'content')

    m_count = rc.hget(group_id, "m_count")
    excludeSourceMessage = re.sub(r"(?:\[mirai:source?:(.*?)?\])", "",
                                  message.asSerializationString())
    if m_count == '0':
        rc.hset(group_id, "m_cache_0", excludeSourceMessage)
        rc.hset(group_id, "m_count", '1')  # 消息计数+1
    if m_count == '1':
        rc.hset(group_id, "m_cache_1", excludeSourceMessage)
        rc.hset(group_id, "m_count", '2')
    if m_count == '2':
        rc.hset(group_id, "m_cache_0", rc.hget(group_id, "m_cache_1"))
        rc.hset(group_id, "m_cache_1", excludeSourceMessage)
    # 缓存消息 ===

    m_cache_0 = rc.hget(group_id, "m_cache_0")
    m_cache_1 = rc.hget(group_id, "m_cache_1")

    if not rc.hget(group_id, "m_last_repeat") == excludeSourceMessage:
        if m_cache_0 == m_cache_1:
            if not is_in_cd(runtime_var, group_id, "repeatCD"):
                if random_do(fetch_config(group_id, "repeatChance")):
                    logger.debug(f"[{group_id}] 命中复读条件且不在cd中且命中概率,需要复读")
                    rc.hset(group_id, "m_last_repeat", excludeSourceMessage)
                    if random_do(5):
                        return True, True
                    else:
                        return True, False
                else:
                    logger.debug(f"[{group_id}] 未命中复读概率")
            else:
                logger.debug(f"[{group_id}] 复读cd冷却中")
    return False, False
예제 #29
0
파일: __init__.py 프로젝트: nyancatda/bot
async def set_headers(kwargs: dict):
    command = kwargs['trigger_msg']
    command = command.split(' ')
    if Group in kwargs:
        check = check_permission(kwargs)
        if not check:
            result = '你没有使用该命令的权限,请联系管理员进行操作。'
            await sendMessage(kwargs, MessageChain.create([Plain(result)]))
            return
    table = 'request_headers_' + kwargs[Target].target_from
    id = kwargs[Target].id
    do = command[0]
    if do == 'show':
        headers = WikiDB.config_headers(do, table, id)
        msg = f'当前设置了以下标头:\n{headers}\n如需自定义,请使用~wiki headers <set> <headers>,不同标头之间使用换行隔开。'
    else:
        msg = WikiDB.config_headers(do, table, id, ' '.join(command[1:]))
    await sendMessage(kwargs, msg)
예제 #30
0
    async def handle(self, app: GraiaMiraiApplication,
                     subject: T.Union[Group, Friend], message: MessageChain,
                     channel: asyncio.Queue) -> bool:
        # 检测是否触发
        accept = False
        content = message.asDisplay()
        for x in self.trigger:
            if (self.trigger_mode == "match"
                    and x == content) or (self.trigger_mode == "search"
                                          and x in content):
                accept = True
                break

        if not accept:
            return False

        await channel.put(self.text)
        return True