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())
async def GMHandler(app: Mirai, message: GroupMessage): command, uid_list = Command.getCommand(message.toString()) if command: try: await command(app, message, *uid_list) except Exception as e: EventLogger.error(e) EventLogger.exception(e)
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())
async def GMHandler(app: Mirai, group: Group, message: MessageChain): command = Command.getCommand(message.toString()) if command: try: msg = await command(group, message.toString()) await app.sendGroupMessage(group, msg.strip()) except Exception as e: EventLogger.error(e) EventLogger.error(traceback.format_exc())
async def GMHandler(app: Mirai, message: GroupMessage): msgStr = message.toString() match = re.match(r'(?:.*?([\d一二两三四五六七八九十]*)张|来点)?(.{0,10}?)的?[色|涩]图$', msgStr) if match: number: int = shuzi2number(match[1]) if number > 10: number = 1 keyword = match[2] try: await setuExecutor(app, message, number, keyword) except Exception as e: import traceback EventLogger.error(e) EventLogger.error(traceback.format_exc())
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())
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))
async def throw_exception_event(self, event_context, queue, exception): if event_context.name != "UnexpectedException": #print("error: by pre:", event_context.name) await queue.put( InternalEvent(name="UnexpectedException", body=UnexpectedException(error=exception, event=event_context, session=self))) EventLogger.error( f"threw a exception by {event_context.name}, Exception: {exception}" ) traceback.print_exc() else: EventLogger.critical( f"threw a exception by {event_context.name}, Exception: {exception}, it's a exception handler." )
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
async def executor_with_middlewares(self, callable, raw_middlewares, event_context, lru_cache_sets=None ): middlewares = self.sort_middlewares(raw_middlewares) try: async with AsyncExitStack() as stack: for async_middleware in middlewares['async']: await stack.enter_async_context(async_middleware) for normal_middleware in middlewares['normal']: stack.enter_context(normal_middleware) result = await self.executor( ExecutorProtocol( callable=callable, dependencies=self.global_dependencies, middlewares=[] ), event_context, lru_cache_sets=lru_cache_sets ) if result is TRACEBACKED: return TRACEBACKED except exceptions.Cancelled: return TRACEBACKED except (NameError, TypeError): EventLogger.error( f"threw a exception by {event_context.name}, it's about Annotations Checker, please report to developer.") traceback.print_exc() except Exception as exception: if type(exception) not in self.listening_exceptions: EventLogger.error( f"threw a exception by {event_context.name} in a depend, and it's {exception}, body has been cancelled.") raise else: await self.put_exception( event_context, exception ) return TRACEBACKED
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
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
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))
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
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
async def put_exception(self, event_context, exception): from mirai.event.builtins import UnexpectedException if event_context.name != "UnexpectedException": if exception.__class__ in self.listening_exceptions: EventLogger.error( f"threw a exception by {event_context.name}, Exception: {exception.__class__.__name__}, and it has been catched.") else: EventLogger.error( f"threw a exception by {event_context.name}, Exception: {exception.__class__.__name__}, and it hasn't been catched!") traceback.print_exc() await self.queue.put(InternalEvent( name="UnexpectedException", body=UnexpectedException( error=exception, event=event_context, application=self ) )) else: EventLogger.critical( f"threw a exception in a exception handler by {event_context.name}, Exception: {exception.__class__.__name__}.")
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
async def main_entrance(self, run_body, event_context, queue): if isinstance(run_body, dict): callable_target = run_body['func'] for depend in run_body['dependencies']: if not inspect.isclass(depend.func): depend_func = depend.func elif hasattr(depend.func, "__call__"): depend_func = depend.func.__call__ else: raise TypeError("must be callable.") await self.main_entrance( { "func": depend_func, "middlewares": depend.middlewares, "dependencies": [] }, event_context, queue) else: if inspect.isclass(run_body): if hasattr(run_body, "__call__"): run_body = run_body.__call__ else: raise TypeError("must be callable.") else: callable_target = run_body translated_mapping = { **(await self.argument_compiler(callable_target, event_context)), **(await self.signature_checkout(callable_target, event_context, queue)) } try: if isinstance(run_body, dict): middlewares = run_body.get("middlewares") if middlewares: async_middlewares = [] normal_middlewares = [] for middleware in middlewares: if all([ hasattr(middleware, "__aenter__"), hasattr(middleware, "__aexit__") ]): async_middlewares.append(middleware) elif all([ hasattr(middleware, "__enter__"), hasattr(middleware, "__exit__") ]): normal_middlewares.append(middleware) else: SessionLogger.error( f"threw a exception by {event_context.name}, no currect context error." ) raise AttributeError( "no a currect context object.") async with contextlib.AsyncExitStack() as async_stack: for async_middleware in async_middlewares: SessionLogger.debug( f"a event called {event_context.name}, enter a currect async context." ) await async_stack.enter_async_context( async_middleware) with contextlib.ExitStack() as normal_stack: for normal_middleware in normal_middlewares: SessionLogger.debug( f"a event called {event_context.name}, enter a currect context." ) normal_stack.enter_context(normal_middleware) if inspect.iscoroutinefunction(callable_target): return await callable_target( **translated_mapping) else: return callable_target(**translated_mapping) else: if inspect.iscoroutinefunction(callable_target): return await callable_target(**translated_mapping) else: return callable_target(**translated_mapping) else: if inspect.iscoroutinefunction(callable_target): return await callable_target(**translated_mapping) else: return callable_target(**translated_mapping) except (NameError, TypeError) as e: EventLogger.error( f"threw a exception by {event_context.name}, it's about Annotations Checker, please report to developer." ) traceback.print_exc() except Exception as e: EventLogger.error( f"threw a exception by {event_context.name}, and it's {e}") await self.throw_exception_event(event_context, queue, e)