Пример #1
0
async def execute(app: Mirai) -> None:
    delay = 10
    while True:
        targets = Database.load().__root__
        if not targets:
            await asyncio.sleep(delay)
            continue
        for target in targets:
            if target.groups:
                try:
                    await asyncio.sleep(delay)
                    resp = await getDynamicStatus(target.uid)
                    if resp:
                        footer = f"\n\n动态地址: https://t.bilibili.com/{resp.dynamic_id}"
                        EventLogger.info(
                            f'{target.name}动态更新:https://t.bilibili.com/{resp.dynamic_id}'
                        )
                        # noinspection PyTypeChecker,PydanticTypeChecker
                        components = [Plain(resp.msg)] + \
                                     [await app.uploadImage(
                                         'group', await Image.fromRemote(url)
                                     ) for url in resp.imgs] + \
                                     [Plain(footer)]
                        [
                            asyncio.create_task(
                                app.sendGroupMessage(group=group_id,
                                                     message=components))
                            for group_id in target.groups
                        ]
                except Exception as e:
                    EventLogger.error(f'动态检查出错:{target.name} {e}')
                    EventLogger.error(traceback.format_exc())
                    continue
Пример #2
0
 async def remove(app: Mirai, message: GroupMessage, *uid_list: int):
     group_id = message.sender.group.id
     names = Database.remove(*[await Target.init(uid, Platform.bili_dynamic, group_id) for uid in uid_list])
     EventLogger.info(f'群「{message.sender.group.name}」移除动态监控:{",".join(names)}')
     await app.sendGroupMessage(group=message.sender.group,
                                message=f'移除动态监控:{",".join(names)}',
                                quoteSource=message.messageChain.getSource())
Пример #3
0
async def execute(app: Mirai, monitor: Monitor) -> None:
    # noinspection PyBroadException
    try:
        resp, groups = await monitor.run()
        if resp:
            EventLogger.info(f'{resp.name}直播:{resp.url}')

            if resp.cover:
                cover: Image = await app.uploadImage("group", await Image.fromRemote(resp.cover))
                components = [Plain(f'(直播){resp.name}: {resp.title}\n{resp.url}\n'), cover]
            else:
                components = [Plain(f'(直播){resp.name}: {resp.title}\n{resp.url}')]

            tasks = [asyncio.create_task(
                app.sendGroupMessage(group=group_id, message=components)
            ) for group_id in groups]

            done, pending = await asyncio.wait(tasks)
            for task in done:
                if e := task.exception():
                    EventLogger.error(e)

    except ChannelResolveError as e:
        EventLogger.warning(e)
    except Exception:
        EventLogger.error(traceback.format_exc())
Пример #4
0
 async def show(app: Mirai, message: GroupMessage, *_: int):
     group_id = message.sender.group.id
     names = Database.show(group_id)
     msg = '动态监控列表:\n{}'.format('\n'.join(names)) if names else '动态监控列表为空'
     EventLogger.info(f'群「{message.sender.group.name}」{msg}')
     await app.sendGroupMessage(group=message.sender.group,
                                message=msg,
                                quoteSource=message.messageChain.getSource())
Пример #5
0
    async def event_runner(self):
        while True:
            try:
                event_context: NamedTuple[InternalEvent] = await asyncio.wait_for(self.queue.get(), 3)
            except asyncio.TimeoutError:
                continue

            if event_context.name in self.registeredEventNames:
                EventLogger.info(f"handling a event: {event_context.name}")
                for event_body in list(self.event.values()) \
                        [self.registeredEventNames.index(event_context.name)]:
                    if event_body:
                        running_loop = asyncio.get_running_loop()
                        running_loop.create_task(self.executor(event_body, event_context))
Пример #6
0
    async def send(prefix_: str, data_: SetuData):
        try:
            setu_b: bytes = await data_.get()
            EventLogger.info("已经下载成功,现在发送到qq群")
            await app.sendGroupMessage(group,
                                       [At(sender.id), Plain("欧尼酱~(^ω^)♪看看这是不是你想要的色图"),Plain(prefix_ + data_.purl + '\n'), Image.fromBytes(setu_b), Plain(f"性癖是:{','.join(data_.tags)}")])
            EventLogger.info(f"{prefix_}色图已发送,标签:{','.join(data_.tags)}")

        except asyncio.TimeoutError as e:
            EventLogger.warn('连接超时' + str(e))
            raise e
        except ValueError as e:
            EventLogger.warn('图片尺寸检查失败' + str(e))
            raise e
Пример #7
0
    async def get(self, check_size: bool = True) -> bytes:
        """从网络获取图像"""
        try:

            EventLogger.info(f"url:{self.urls.regular}")
            headers = {
                'Referer': 'https://www.pixiv.net/'
            } if 'i.pximg.net' in self.urls.regular else {}
            async with aiohttp.request(
                    'GET',
                    self.urls.regular,
                    headers=headers,
                    timeout=aiohttp.ClientTimeout(10)) as resp:
                EventLogger.info(f"url:{self.urls.regular} download success")
                img_bytes: bytes = await resp.read()
        except (asyncio.TimeoutError, ValueError) as e:
            raise e
        return img_bytes
Пример #8
0
async def GMHandler(app: Mirai, sender: "Sender", event_type: "Type",
                    message: MessageChain):
    app_reply = reply(app, sender, event_type)
    for tag, source in sources.items():
        keywords = source.keywords
        text = message.toString()
        if (text in keywords) or (at_me(app, message)
                                  and any(keyword in text
                                          for keyword in keywords)):
            EventLogger.info(f'随机图片{tag}:请求者{sender.id}')
            try:
                image_url = await source.get()
                await app_reply([await Image.fromRemote(image_url)],
                                at_sender=True)
            except asyncio.TimeoutError:
                await app_reply("请求超时", at_sender=True)
            except Exception as e:
                import traceback
                EventLogger.error(e)
                EventLogger.error(traceback.format_exc())
            break
Пример #9
0
    async def event_runner(self, exit_signal_status, queue: asyncio.Queue):
        while not exit_signal_status():
            event_context: InternalEvent
            try:
                event_context: T.NamedTuple[
                    InternalEvent] = await asyncio.wait_for(queue.get(), 3)
            except asyncio.TimeoutError:
                if exit_signal_status():
                    break
                else:
                    continue

            if event_context.name in self.registeredEventNames:
                for event_body in list(self.event.values())\
                      [self.registeredEventNames.index(event_context.name)]:
                    if event_body:
                        EventLogger.info(
                            f"handling a event: {event_context.name}")

                        asyncio.create_task(
                            self.main_entrance(event_body, event_context,
                                               queue))
Пример #10
0
 async def send(prefix_: str, data_: SetuData):
     try:
         setu_b: bytes = await data_.get(False)
         await app.sendGroupMessage(group, [
             At(sender.id),
             Plain(prefix_ + data_.purl + '\n'),
             Image.fromBytes(setu_b)
         ])
         EventLogger.info(f"{prefix_}色图已发送,标签:{','.join(data_.tags)}")
     except asyncio.TimeoutError as e:
         EventLogger.warn('连接超时' + str(e))
         # raise e
         try:
             await app.sendGroupMessage(group, [
                 At(sender.id),
                 Plain(prefix_ + data_.purl + '\n' + data_.url +
                       '\n自己动手,丰衣足食')
             ])
         except Exception as e:
             raise e
     except ValueError as e:
         EventLogger.warn('图片尺寸检查失败' + str(e))
         raise e
Пример #11
0
async def fudu(app: Mirai, group: Group, message: MessageChain):
    global last_message
    match = re.match(r'(?:.*?([\d一二两三四五六七八九十]*)张|来点)?(.{0,10}?)的?[色|涩]图$', message.toString())
    if match:
        return

    if last_message != None and last_message.toString() == message.toString():
        EventLogger.info(f"{message.toString()}消息已复读")
        replyArray = []
        for v in message:
            if type(v) == Image or type(v) == Plain or type(v) == At or type(v) == AtAll or type(v) == Face:
                replyArray.append(v)

        last_message = None
        await app.sendGroupMessage(group, replyArray)
    else:
        if last_message != None:
            EventLogger.info(f"last_message:{last_message.toString()}")
        EventLogger.info(f"{message.toString()}消息已缓存")
        last_message = message