id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
156,046
from typing import ( Any, Dict, List, Match, Tuple, Union, Literal, Callable, Optional, overload, ) from nonebot.typing import T_State from nonebot.matcher import Matcher from nonebot.internal.params import Arg as Arg from nonebot.internal.params import ArgStr as ArgStr from nonebot.internal.params import Depends as Depends from nonebot.internal.params import ArgParam as ArgParam from nonebot.internal.params import BotParam as BotParam from nonebot.adapters import Event, Message, MessageSegment from nonebot.internal.params import EventParam as EventParam from nonebot.internal.params import StateParam as StateParam from nonebot.internal.params import DependParam as DependParam from nonebot.internal.params import ArgPlainText as ArgPlainText from nonebot.internal.params import DefaultParam as DefaultParam from nonebot.internal.params import MatcherParam as MatcherParam from nonebot.internal.params import ExceptionParam as ExceptionParam from nonebot.consts import ( CMD_KEY, PREFIX_KEY, SHELL_ARGS, SHELL_ARGV, CMD_ARG_KEY, KEYWORD_KEY, RAW_CMD_KEY, ENDSWITH_KEY, CMD_START_KEY, FULLMATCH_KEY, REGEX_MATCHED, STARTSWITH_KEY, CMD_WHITESPACE_KEY, ) def Depends( dependency: Optional[T_Handler] = None, *, use_cache: bool = True, validate: Union[bool, PydanticFieldInfo] = False, ) -> Any: """子依赖装饰器 参数: dependency: 依赖函数。默认为参数的类型注释。 use_cache: 是否使用缓存。默认为 `True`。 validate: 是否使用 Pydantic 类型校验。默认为 `False`。 用法: ```python def depend_func() -> Any: return ... def depend_gen_func(): try: yield ... finally: ... async def handler( param_name: Any = Depends(depend_func), gen: Any = Depends(depend_gen_func), ): ... ``` """ return DependsInner(dependency, use_cache=use_cache, validate=validate) The provided code snippet includes necessary dependencies for implementing the `LastReceived` function. Write a Python function `def LastReceived(default: Any = None) -> Any` to solve the following problem: `last_receive` 事件参数 Here is the function: def LastReceived(default: Any = None) -> Any: """`last_receive` 事件参数""" def _last_received(matcher: "Matcher") -> Any: return matcher.get_last_receive(default) return Depends(_last_received, use_cache=False)
`last_receive` 事件参数
156,047
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) K = TypeVar("K") The provided code snippet includes necessary dependencies for implementing the `deep_update` function. Write a Python function `def deep_update( mapping: Dict[K, Any], *updating_mappings: Dict[K, Any] ) -> Dict[K, Any]` to solve the following problem: 深度更新合并字典 Here is the function: def deep_update( mapping: Dict[K, Any], *updating_mappings: Dict[K, Any] ) -> Dict[K, Any]: """深度更新合并字典""" updated_mapping = mapping.copy() for updating_mapping in updating_mappings: for k, v in updating_mapping.items(): if ( k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict) ): updated_mapping[k] = deep_update(updated_mapping[k], v) else: updated_mapping[k] = v return updated_mapping
深度更新合并字典
156,048
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) def origin_is_literal(origin: t.Optional[t.Type[t.Any]]) -> bool: """判断是否是 Literal 类型""" return origin is t.Literal or origin is t_ext.Literal def all_literal_values(type_: t.Type[t.Any]) -> t.List[t.Any]: """获取 Literal 类型包含的所有值""" if not origin_is_literal(get_origin(type_)): return [type_] return [x for value in _literal_values(type_) for x in all_literal_values(value)] def is_none_type(type_: t.Type[t.Any]) -> bool: """判断是否是 None 类型""" return type_ in NONE_TYPES The provided code snippet includes necessary dependencies for implementing the `generic_check_issubclass` function. Write a Python function `def generic_check_issubclass( cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]] ) -> bool` to solve the following problem: 检查 cls 是否是 class_or_tuple 中的一个类型子类。 特别的: - 如果 cls 是 `typing.Union` 或 `types.UnionType` 类型, 则会检查其中的所有类型是否是 class_or_tuple 中一个类型的子类或 None。 - 如果 cls 是 `typing.Literal` 类型, 则会检查其中的所有值是否是 class_or_tuple 中一个类型的实例。 - 如果 cls 是 `typing.TypeVar` 类型, 则会检查其 `__bound__` 或 `__constraints__` 是否是 class_or_tuple 中一个类型的子类或 None。 Here is the function: def generic_check_issubclass( cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]] ) -> bool: """检查 cls 是否是 class_or_tuple 中的一个类型子类。 特别的: - 如果 cls 是 `typing.Union` 或 `types.UnionType` 类型, 则会检查其中的所有类型是否是 class_or_tuple 中一个类型的子类或 None。 - 如果 cls 是 `typing.Literal` 类型, 则会检查其中的所有值是否是 class_or_tuple 中一个类型的实例。 - 如果 cls 是 `typing.TypeVar` 类型, 则会检查其 `__bound__` 或 `__constraints__` 是否是 class_or_tuple 中一个类型的子类或 None。 """ try: return issubclass(cls, class_or_tuple) except TypeError: origin = get_origin(cls) if origin_is_union(origin): return all( is_none_type(type_) or generic_check_issubclass(type_, class_or_tuple) for type_ in get_args(cls) ) elif origin_is_literal(origin): return all( is_none_type(value) or isinstance(value, class_or_tuple) for value in all_literal_values(cls) ) # ensure generic List, Dict can be checked elif origin: # avoid class check error (typing.Final, typing.ClassVar, etc...) try: return issubclass(origin, class_or_tuple) except TypeError: return False elif isinstance(cls, TypeVar): if cls.__constraints__: return all( is_none_type(type_) or generic_check_issubclass(type_, class_or_tuple) for type_ in cls.__constraints__ ) elif cls.__bound__: return generic_check_issubclass(cls.__bound__, class_or_tuple) return False
检查 cls 是否是 class_or_tuple 中的一个类型子类。 特别的: - 如果 cls 是 `typing.Union` 或 `types.UnionType` 类型, 则会检查其中的所有类型是否是 class_or_tuple 中一个类型的子类或 None。 - 如果 cls 是 `typing.Literal` 类型, 则会检查其中的所有值是否是 class_or_tuple 中一个类型的实例。 - 如果 cls 是 `typing.TypeVar` 类型, 则会检查其 `__bound__` 或 `__constraints__` 是否是 class_or_tuple 中一个类型的子类或 None。
156,049
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) def _type_is_complex_inner(type_: Optional[Type[Any]]) -> bool: if lenient_issubclass(type_, (str, bytes)): return False return lenient_issubclass( type_, (BaseModel, Mapping, Sequence, tuple, set, frozenset, deque) ) or dataclasses.is_dataclass(type_) The provided code snippet includes necessary dependencies for implementing the `type_is_complex` function. Write a Python function `def type_is_complex(type_: Type[Any]) -> bool` to solve the following problem: 检查 type_ 是否是复杂类型 Here is the function: def type_is_complex(type_: Type[Any]) -> bool: """检查 type_ 是否是复杂类型""" origin = get_origin(type_) return _type_is_complex_inner(type_) or _type_is_complex_inner(origin)
检查 type_ 是否是复杂类型
156,050
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) The provided code snippet includes necessary dependencies for implementing the `is_coroutine_callable` function. Write a Python function `def is_coroutine_callable(call: Callable[..., Any]) -> bool` to solve the following problem: 检查 call 是否是一个 callable 协程函数 Here is the function: def is_coroutine_callable(call: Callable[..., Any]) -> bool: """检查 call 是否是一个 callable 协程函数""" if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False func_ = getattr(call, "__call__", None) return inspect.iscoroutinefunction(func_)
检查 call 是否是一个 callable 协程函数
156,051
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) The provided code snippet includes necessary dependencies for implementing the `is_gen_callable` function. Write a Python function `def is_gen_callable(call: Callable[..., Any]) -> bool` to solve the following problem: 检查 call 是否是一个生成器函数 Here is the function: def is_gen_callable(call: Callable[..., Any]) -> bool: """检查 call 是否是一个生成器函数""" if inspect.isgeneratorfunction(call): return True func_ = getattr(call, "__call__", None) return inspect.isgeneratorfunction(func_)
检查 call 是否是一个生成器函数
156,052
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) The provided code snippet includes necessary dependencies for implementing the `is_async_gen_callable` function. Write a Python function `def is_async_gen_callable(call: Callable[..., Any]) -> bool` to solve the following problem: 检查 call 是否是一个异步生成器函数 Here is the function: def is_async_gen_callable(call: Callable[..., Any]) -> bool: """检查 call 是否是一个异步生成器函数""" if inspect.isasyncgenfunction(call): return True func_ = getattr(call, "__call__", None) return inspect.isasyncgenfunction(func_)
检查 call 是否是一个异步生成器函数
156,053
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) T = TypeVar("T") def run_sync(call: Callable[P, R]) -> Callable[P, Coroutine[None, None, R]]: """一个用于包装 sync function 为 async function 的装饰器 参数: call: 被装饰的同步函数 """ async def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R: loop = asyncio.get_running_loop() pfunc = partial(call, *args, **kwargs) context = copy_context() result = await loop.run_in_executor(None, partial(context.run, pfunc)) return result return _wrapper The provided code snippet includes necessary dependencies for implementing the `run_sync_ctx_manager` function. Write a Python function `async def run_sync_ctx_manager( cm: ContextManager[T], ) -> AsyncGenerator[T, None]` to solve the following problem: 一个用于包装 sync context manager 为 async context manager 的执行函数 Here is the function: async def run_sync_ctx_manager( cm: ContextManager[T], ) -> AsyncGenerator[T, None]: """一个用于包装 sync context manager 为 async context manager 的执行函数""" try: yield await run_sync(cm.__enter__)() except Exception as e: ok = await run_sync(cm.__exit__)(type(e), e, None) if not ok: raise e else: await run_sync(cm.__exit__)(None, None, None)
一个用于包装 sync context manager 为 async context manager 的执行函数
156,054
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) The provided code snippet includes necessary dependencies for implementing the `get_name` function. Write a Python function `def get_name(obj: Any) -> str` to solve the following problem: 获取对象的名称 Here is the function: def get_name(obj: Any) -> str: """获取对象的名称""" if inspect.isfunction(obj) or inspect.isclass(obj): return obj.__name__ return obj.__class__.__name__
获取对象的名称
156,055
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) The provided code snippet includes necessary dependencies for implementing the `resolve_dot_notation` function. Write a Python function `def resolve_dot_notation( obj_str: str, default_attr: str, default_prefix: Optional[str] = None ) -> Any` to solve the following problem: 解析并导入点分表示法的对象 Here is the function: def resolve_dot_notation( obj_str: str, default_attr: str, default_prefix: Optional[str] = None ) -> Any: """解析并导入点分表示法的对象""" modulename, _, cls = obj_str.partition(":") if default_prefix is not None and modulename.startswith("~"): modulename = default_prefix + modulename[1:] module = importlib.import_module(modulename) if not cls: return getattr(module, default_attr) instance = module for attr_str in cls.split("."): instance = getattr(instance, attr_str) return instance
解析并导入点分表示法的对象
156,056
import re import json import asyncio import inspect import importlib import dataclasses from pathlib import Path from collections import deque from contextvars import copy_context from functools import wraps, partial from contextlib import asynccontextmanager from typing_extensions import ParamSpec, get_args, override, get_origin from typing import ( Any, Dict, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, Coroutine, AsyncGenerator, ContextManager, overload, ) from pydantic import BaseModel from nonebot.log import logger from nonebot.typing import ( is_none_type, origin_is_union, origin_is_literal, all_literal_values, ) def escape_tag(s: str) -> str: """用于记录带颜色日志时转义 `<tag>` 类型特殊标签 参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color) 参数: s: 需要转义的字符串 """ return re.sub(r"</?((?:[fb]g\s)?[^<>\s]*)>", r"\\\g<0>", s) logger: "Logger" = loguru.logger The provided code snippet includes necessary dependencies for implementing the `logger_wrapper` function. Write a Python function `def logger_wrapper(logger_name: str)` to solve the following problem: 用于打印 adapter 的日志。 参数: logger_name: adapter 的名称 返回: 日志记录函数 日志记录函数的参数: - level: 日志等级 - message: 日志信息 - exception: 异常信息 Here is the function: def logger_wrapper(logger_name: str): """用于打印 adapter 的日志。 参数: logger_name: adapter 的名称 返回: 日志记录函数 日志记录函数的参数: - level: 日志等级 - message: 日志信息 - exception: 异常信息 """ def log(level: str, message: str, exception: Optional[Exception] = None): logger.opt(colors=True, exception=exception).log( level, f"<m>{escape_tag(logger_name)}</m> | {message}" ) return log
用于打印 adapter 的日志。 参数: logger_name: adapter 的名称 返回: 日志记录函数 日志记录函数的参数: - level: 日志等级 - message: 日志信息 - exception: 异常信息
156,057
import inspect from typing import Any, Dict, Callable, ForwardRef from loguru import logger from nonebot.exception import TypeMisMatch from nonebot.typing import evaluate_forwardref from nonebot.compat import DEFAULT_CONFIG, ModelField, model_field_validate def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: """获取参数的类型注解""" annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) try: annotation = evaluate_forwardref(annotation, globalns, globalns) except Exception as e: logger.opt(colors=True, exception=e).warning( f'Unknown ForwardRef["{param.annotation}"] for parameter {param.name}' ) return inspect.Parameter.empty return annotation The provided code snippet includes necessary dependencies for implementing the `get_typed_signature` function. Write a Python function `def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature` to solve the following problem: 获取可调用对象签名 Here is the function: def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: """获取可调用对象签名""" signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] return inspect.Signature(typed_params)
获取可调用对象签名
156,058
import inspect from typing import Any, Dict, Callable, ForwardRef from loguru import logger from nonebot.exception import TypeMisMatch from nonebot.typing import evaluate_forwardref from nonebot.compat import DEFAULT_CONFIG, ModelField, model_field_validate class TypeMisMatch(SkippedException): """当前 `Handler` 的参数类型不匹配。""" def __init__(self, param: ModelField, value: Any) -> None: self.param: ModelField = param self.value: Any = value def __repr__(self) -> str: return ( f"TypeMisMatch(param={self.param.name}, " f"type={self.param._type_display()}, value={self.value!r}>" ) The provided code snippet includes necessary dependencies for implementing the `check_field_type` function. Write a Python function `def check_field_type(field: ModelField, value: Any) -> Any` to solve the following problem: 检查字段类型是否匹配 Here is the function: def check_field_type(field: ModelField, value: Any) -> Any: """检查字段类型是否匹配""" try: return model_field_validate(field, value, DEFAULT_CONFIG) except ValueError: raise TypeMisMatch(field, value)
检查字段类型是否匹配
156,059
import re import shlex from argparse import Action from gettext import gettext from argparse import ArgumentError from contextvars import ContextVar from itertools import chain, product from argparse import Namespace as Namespace from argparse import ArgumentParser as ArgParser from typing import ( IO, TYPE_CHECKING, List, Type, Tuple, Union, TypeVar, Optional, Sequence, TypedDict, NamedTuple, cast, overload, ) from pygtrie import CharTrie from nonebot import get_driver from nonebot.log import logger from nonebot.typing import T_State from nonebot.exception import ParserExit from nonebot.internal.rule import Rule as Rule from nonebot.adapters import Bot, Event, Message, MessageSegment from nonebot.params import Command, EventToMe, CommandArg, CommandWhitespace from nonebot.consts import ( CMD_KEY, PREFIX_KEY, SHELL_ARGS, SHELL_ARGV, CMD_ARG_KEY, KEYWORD_KEY, RAW_CMD_KEY, ENDSWITH_KEY, CMD_START_KEY, FULLMATCH_KEY, REGEX_MATCHED, STARTSWITH_KEY, CMD_WHITESPACE_KEY, ) class ToMeRule: """检查事件是否与机器人有关。""" __slots__ = () def __repr__(self) -> str: return "ToMe()" def __eq__(self, other: object) -> bool: return isinstance(other, ToMeRule) def __hash__(self) -> int: return hash((self.__class__,)) async def __call__(self, to_me: bool = EventToMe()) -> bool: return to_me class Rule: """{ref}`nonebot.matcher.Matcher` 规则类。 当事件传递时,在 {ref}`nonebot.matcher.Matcher` 运行前进行检查。 参数: *checkers: RuleChecker 用法: ```python Rule(async_function) & sync_function # 等价于 Rule(async_function, sync_function) ``` """ __slots__ = ("checkers",) HANDLER_PARAM_TYPES: ClassVar[List[Type[Param]]] = [ DependParam, BotParam, EventParam, StateParam, DefaultParam, ] def __init__(self, *checkers: Union[T_RuleChecker, Dependent[bool]]) -> None: self.checkers: Set[Dependent[bool]] = { ( checker if isinstance(checker, Dependent) else Dependent[bool].parse( call=checker, allow_types=self.HANDLER_PARAM_TYPES ) ) for checker in checkers } """存储 `RuleChecker`""" def __repr__(self) -> str: return f"Rule({', '.join(repr(checker) for checker in self.checkers)})" async def __call__( self, bot: Bot, event: Event, state: T_State, stack: Optional[AsyncExitStack] = None, dependency_cache: Optional[T_DependencyCache] = None, ) -> bool: """检查是否符合所有规则 参数: bot: Bot 对象 event: Event 对象 state: 当前 State stack: 异步上下文栈 dependency_cache: 依赖缓存 """ if not self.checkers: return True try: results = await asyncio.gather( *( checker( bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ) for checker in self.checkers ) ) except SkippedException: return False return all(results) def __and__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule": if other is None: return self elif isinstance(other, Rule): return Rule(*self.checkers, *other.checkers) else: return Rule(*self.checkers, other) def __rand__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule": if other is None: return self elif isinstance(other, Rule): return Rule(*other.checkers, *self.checkers) else: return Rule(other, *self.checkers) def __or__(self, other: object) -> NoReturn: raise RuntimeError("Or operation between rules is not allowed.") The provided code snippet includes necessary dependencies for implementing the `to_me` function. Write a Python function `def to_me() -> Rule` to solve the following problem: 匹配与机器人有关的事件。 Here is the function: def to_me() -> Rule: """匹配与机器人有关的事件。""" return Rule(ToMeRule())
匹配与机器人有关的事件。
156,060
import sys import types import warnings import contextlib import typing as t import typing_extensions as t_ext from typing import TYPE_CHECKING, TypeVar from typing_extensions import ParamSpec, TypeAlias, get_args, override, get_origin The provided code snippet includes necessary dependencies for implementing the `overrides` function. Write a Python function `def overrides(InterfaceClass: object)` to solve the following problem: 标记一个方法为父类 interface 的 implement Here is the function: def overrides(InterfaceClass: object): """标记一个方法为父类 interface 的 implement""" warnings.warn( "overrides is deprecated and will be removed in a future version, " "use @typing_extensions.override instead. " "See [PEP 698](https://peps.python.org/pep-0698/) for more details.", DeprecationWarning, ) return override
标记一个方法为父类 interface 的 implement
156,061
import sys import types import warnings import contextlib import typing as t import typing_extensions as t_ext from typing import TYPE_CHECKING, TypeVar from typing_extensions import ParamSpec, TypeAlias, get_args, override, get_origin import typing as t from typing import TYPE_CHECKING, TypeVar The provided code snippet includes necessary dependencies for implementing the `origin_is_annotated` function. Write a Python function `def origin_is_annotated(origin: t.Optional[t.Type[t.Any]]) -> bool` to solve the following problem: 判断是否是 Annotated 类型 Here is the function: def origin_is_annotated(origin: t.Optional[t.Type[t.Any]]) -> bool: """判断是否是 Annotated 类型""" with contextlib.suppress(TypeError): return origin is not None and issubclass(origin, t_ext.Annotated) return False
判断是否是 Annotated 类型
156,062
import sys import types import warnings import contextlib import typing as t import typing_extensions as t_ext from typing import TYPE_CHECKING, TypeVar from typing_extensions import ParamSpec, TypeAlias, get_args, override, get_origin import typing as t from typing import TYPE_CHECKING, TypeVar def evaluate_forwardref( ref: t.ForwardRef, globalns: t.Dict[str, t.Any], localns: t.Dict[str, t.Any] ) -> t.Any: return ref._evaluate(globalns, localns)
null
156,063
import sys import types import warnings import contextlib import typing as t import typing_extensions as t_ext from typing import TYPE_CHECKING, TypeVar from typing_extensions import ParamSpec, TypeAlias, get_args, override, get_origin import typing as t from typing import TYPE_CHECKING, TypeVar def evaluate_forwardref( ref: t.ForwardRef, globalns: t.Dict[str, t.Any], localns: t.Dict[str, t.Any] ) -> t.Any: return ref._evaluate(globalns, localns, frozenset())
null
156,064
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def get_matcher_source(depth: int = 1) -> Optional[MatcherSource]: """获取事件响应器定义所在源码信息。 参数: depth: 调用栈深度 """ current_frame = inspect.currentframe() if current_frame is None: return None frame = inspect.getouterframes(current_frame)[depth + 1].frame module_name = (module := inspect.getmodule(frame)) and module.__name__ plugin: Optional["Plugin"] = None # matcher defined when plugin loading if plugin_chain := _current_plugin_chain.get(): plugin = plugin_chain[-1] # matcher defined when plugin running elif module_name: plugin = get_plugin_by_module_name(module_name) return MatcherSource( plugin_name=plugin and plugin.name, module_name=module_name, lineno=frame.f_lineno, ) class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None The provided code snippet includes necessary dependencies for implementing the `get_matcher_plugin` function. Write a Python function `def get_matcher_plugin(depth: int = 1) -> Optional[Plugin]` to solve the following problem: 获取事件响应器定义所在插件。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度 Here is the function: def get_matcher_plugin(depth: int = 1) -> Optional[Plugin]: # pragma: no cover """获取事件响应器定义所在插件。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度 """ warnings.warn( "`get_matcher_plugin` is deprecated, please use `get_matcher_source` instead", DeprecationWarning, ) return (source := get_matcher_source(depth + 1)) and source.plugin
获取事件响应器定义所在插件。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度
156,065
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def get_matcher_source(depth: int = 1) -> Optional[MatcherSource]: """获取事件响应器定义所在源码信息。 参数: depth: 调用栈深度 """ current_frame = inspect.currentframe() if current_frame is None: return None frame = inspect.getouterframes(current_frame)[depth + 1].frame module_name = (module := inspect.getmodule(frame)) and module.__name__ plugin: Optional["Plugin"] = None # matcher defined when plugin loading if plugin_chain := _current_plugin_chain.get(): plugin = plugin_chain[-1] # matcher defined when plugin running elif module_name: plugin = get_plugin_by_module_name(module_name) return MatcherSource( plugin_name=plugin and plugin.name, module_name=module_name, lineno=frame.f_lineno, ) The provided code snippet includes necessary dependencies for implementing the `get_matcher_module` function. Write a Python function `def get_matcher_module(depth: int = 1) -> Optional[ModuleType]` to solve the following problem: 获取事件响应器定义所在模块。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度 Here is the function: def get_matcher_module(depth: int = 1) -> Optional[ModuleType]: # pragma: no cover """获取事件响应器定义所在模块。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度 """ warnings.warn( "`get_matcher_module` is deprecated, please use `get_matcher_source` instead", DeprecationWarning, ) return (source := get_matcher_source(depth + 1)) and source.module
获取事件响应器定义所在模块。 **Deprecated**, 请使用 {ref}`nonebot.plugin.on.get_matcher_source` 获取信息。 参数: depth: 调用栈深度
156,066
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on( type: str = "", rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Union[Permission, T_PermissionChecker]] = None, *, handlers: Optional[List[Union[T_Handler, Dependent]]] = None, temp: bool = False, expire_time: Optional[Union[datetime, timedelta]] = None, priority: int = 1, block: bool = False, state: Optional[T_State] = None, _depth: int = 0, ) -> Type[Matcher]: """注册一个基础事件响应器,可自定义类型。 参数: type: 事件响应器类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ matcher = Matcher.new( type, Rule() & rule, Permission() | permission, temp=temp, expire_time=expire_time, priority=priority, block=block, handlers=handlers, source=get_matcher_source(_depth + 1), default_state=state, ) store_matcher(matcher) return matcher The provided code snippet includes necessary dependencies for implementing the `on_metaevent` function. Write a Python function `def on_metaevent(*args, _depth: int = 0, **kwargs) -> Type[Matcher]` to solve the following problem: 注册一个元事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_metaevent(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个元事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on("meta_event", *args, **kwargs, _depth=_depth + 1)
注册一个元事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,067
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on( type: str = "", rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Union[Permission, T_PermissionChecker]] = None, *, handlers: Optional[List[Union[T_Handler, Dependent]]] = None, temp: bool = False, expire_time: Optional[Union[datetime, timedelta]] = None, priority: int = 1, block: bool = False, state: Optional[T_State] = None, _depth: int = 0, ) -> Type[Matcher]: """注册一个基础事件响应器,可自定义类型。 参数: type: 事件响应器类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ matcher = Matcher.new( type, Rule() & rule, Permission() | permission, temp=temp, expire_time=expire_time, priority=priority, block=block, handlers=handlers, source=get_matcher_source(_depth + 1), default_state=state, ) store_matcher(matcher) return matcher The provided code snippet includes necessary dependencies for implementing the `on_notice` function. Write a Python function `def on_notice(*args, _depth: int = 0, **kwargs) -> Type[Matcher]` to solve the following problem: 注册一个通知事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_notice(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个通知事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on("notice", *args, **kwargs, _depth=_depth + 1)
注册一个通知事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,068
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on( type: str = "", rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Union[Permission, T_PermissionChecker]] = None, *, handlers: Optional[List[Union[T_Handler, Dependent]]] = None, temp: bool = False, expire_time: Optional[Union[datetime, timedelta]] = None, priority: int = 1, block: bool = False, state: Optional[T_State] = None, _depth: int = 0, ) -> Type[Matcher]: """注册一个基础事件响应器,可自定义类型。 参数: type: 事件响应器类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ matcher = Matcher.new( type, Rule() & rule, Permission() | permission, temp=temp, expire_time=expire_time, priority=priority, block=block, handlers=handlers, source=get_matcher_source(_depth + 1), default_state=state, ) store_matcher(matcher) return matcher The provided code snippet includes necessary dependencies for implementing the `on_request` function. Write a Python function `def on_request(*args, _depth: int = 0, **kwargs) -> Type[Matcher]` to solve the following problem: 注册一个请求事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_request(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个请求事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on("request", *args, **kwargs, _depth=_depth + 1)
注册一个请求事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,069
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def startswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule: """匹配消息纯文本开头。 参数: msg: 指定消息开头字符串元组 ignorecase: 是否忽略大小写 """ if isinstance(msg, str): msg = (msg,) return Rule(StartswithRule(msg, ignorecase)) The provided code snippet includes necessary dependencies for implementing the `on_startswith` function. Write a Python function `def on_startswith( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。 参数: msg: 指定消息开头内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_startswith( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。 参数: msg: 指定消息开头内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on_message(startswith(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。 参数: msg: 指定消息开头内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,070
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def endswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule: """匹配消息纯文本结尾。 参数: msg: 指定消息开头字符串元组 ignorecase: 是否忽略大小写 """ if isinstance(msg, str): msg = (msg,) return Rule(EndswithRule(msg, ignorecase)) The provided code snippet includes necessary dependencies for implementing the `on_endswith` function. Write a Python function `def on_endswith( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。 参数: msg: 指定消息结尾内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_endswith( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。 参数: msg: 指定消息结尾内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on_message(endswith(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。 参数: msg: 指定消息结尾内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,071
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def fullmatch(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule: """完全匹配消息。 参数: msg: 指定消息全匹配字符串元组 ignorecase: 是否忽略大小写 """ if isinstance(msg, str): msg = (msg,) return Rule(FullmatchRule(msg, ignorecase)) The provided code snippet includes necessary dependencies for implementing the `on_fullmatch` function. Write a Python function `def on_fullmatch( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。 参数: msg: 指定消息全匹配内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_fullmatch( msg: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, ignorecase: bool = False, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。 参数: msg: 指定消息全匹配内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on_message(fullmatch(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。 参数: msg: 指定消息全匹配内容 rule: 事件响应规则 ignorecase: 是否忽略大小写 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,072
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def keyword(*keywords: str) -> Rule: """匹配消息纯文本关键词。 参数: keywords: 指定关键字元组 """ return Rule(KeywordsRule(*keywords)) The provided code snippet includes necessary dependencies for implementing the `on_keyword` function. Write a Python function `def on_keyword( keywords: Set[str], rule: Optional[Union[Rule, T_RuleChecker]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 参数: keywords: 关键词列表 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_keyword( keywords: Set[str], rule: Optional[Union[Rule, T_RuleChecker]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 参数: keywords: 关键词列表 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on_message(keyword(*keywords) & rule, **kwargs, _depth=_depth + 1)
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 参数: keywords: 关键词列表 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,073
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def command( *cmds: Union[str, Tuple[str, ...]], force_whitespace: Optional[Union[str, bool]] = None, ) -> Rule: """匹配消息命令。 根据配置里提供的 {ref}``command_start` <nonebot.config.Config.command_start>`, {ref}``command_sep` <nonebot.config.Config.command_sep>` 判断消息是否为命令。 可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令(例: `("test",)`), 通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本(例: `"/test"`), 通过 {ref}`nonebot.params.CommandArg` 获取匹配成功的命令参数。 参数: cmds: 命令文本或命令元组 force_whitespace: 是否强制命令后必须有指定空白符 用法: 使用默认 `command_start`, `command_sep` 配置情况下: 命令 `("test",)` 可以匹配: `/test` 开头的消息 命令 `("test", "sub")` 可以匹配: `/test.sub` 开头的消息 :::tip 提示 命令内容与后续消息间无需空格! ::: """ config = get_driver().config command_start = config.command_start command_sep = config.command_sep commands: List[Tuple[str, ...]] = [] for command in cmds: if isinstance(command, str): command = (command,) commands.append(command) if len(command) == 1: for start in command_start: TrieRule.add_prefix(f"{start}{command[0]}", TRIE_VALUE(start, command)) else: for start, sep in product(command_start, command_sep): TrieRule.add_prefix( f"{start}{sep.join(command)}", TRIE_VALUE(start, command) ) return Rule(CommandRule(commands, force_whitespace)) The provided code snippet includes necessary dependencies for implementing the `on_command` function. Write a Python function `def on_command( cmd: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, force_whitespace: Optional[Union[str, bool]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`_ 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 force_whitespace: 是否强制命令后必须有指定空白符 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_command( cmd: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, force_whitespace: Optional[Union[str, bool]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息以指定命令开头时响应。 命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`_ 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 force_whitespace: 是否强制命令后必须有指定空白符 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ commands = {cmd} | (aliases or set()) kwargs.setdefault("block", False) return on_message( command(*commands, force_whitespace=force_whitespace) & rule, **kwargs, _depth=_depth + 1, )
注册一个消息事件响应器,并且当消息以指定命令开头时响应。 命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`_ 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 force_whitespace: 是否强制命令后必须有指定空白符 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,074
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] class ArgumentParser(ArgParser): """`shell_like` 命令参数解析器,解析出错时不会退出程序。 支持 {ref}`nonebot.adapters.Message` 富文本解析。 用法: 用法与 `argparse.ArgumentParser` 相同, 参考文档: [argparse](https://docs.python.org/3/library/argparse.html) """ if TYPE_CHECKING: def parse_known_args( self, args: Optional[Sequence[Union[str, MessageSegment]]] = None, namespace: None = None, ) -> Tuple[Namespace, List[Union[str, MessageSegment]]]: ... def parse_known_args( self, args: Optional[Sequence[Union[str, MessageSegment]]], namespace: T ) -> Tuple[T, List[Union[str, MessageSegment]]]: ... def parse_known_args( self, *, namespace: T ) -> Tuple[T, List[Union[str, MessageSegment]]]: ... def parse_known_args( self, args: Optional[Sequence[Union[str, MessageSegment]]] = None, namespace: Optional[T] = None, ) -> Tuple[Union[Namespace, T], List[Union[str, MessageSegment]]]: ... def parse_args( self, args: Optional[Sequence[Union[str, MessageSegment]]] = None, namespace: None = None, ) -> Namespace: ... def parse_args( self, args: Optional[Sequence[Union[str, MessageSegment]]], namespace: T ) -> T: ... def parse_args(self, *, namespace: T) -> T: ... def parse_args( self, args: Optional[Sequence[Union[str, MessageSegment]]] = None, namespace: Optional[T] = None, ) -> Union[Namespace, T]: result, argv = self.parse_known_args(args, namespace) if argv: msg = gettext("unrecognized arguments: %s") self.error(msg % " ".join(map(str, argv))) return cast(Union[Namespace, T], result) def _parse_optional( self, arg_string: Union[str, MessageSegment] ) -> Optional[Tuple[Optional[Action], str, Optional[str]]]: return ( super()._parse_optional(arg_string) if isinstance(arg_string, str) else None ) def _print_message(self, message: str, file: Optional[IO[str]] = None): if (msg := parser_message.get(None)) is not None: parser_message.set(msg + message) else: super()._print_message(message, file) def exit(self, status: int = 0, message: Optional[str] = None): if message: self._print_message(message) raise ParserExit(status=status, message=parser_message.get(None)) def shell_command( *cmds: Union[str, Tuple[str, ...]], parser: Optional[ArgumentParser] = None ) -> Rule: """匹配 `shell_like` 形式的消息命令。 根据配置里提供的 {ref}``command_start` <nonebot.config.Config.command_start>`, {ref}``command_sep` <nonebot.config.Config.command_sep>` 判断消息是否为命令。 可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令 (例: `("test",)`), 通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本 (例: `"/test"`), 通过 {ref}`nonebot.params.ShellCommandArgv` 获取解析前的参数列表 (例: `["arg", "-h"]`), 通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典 (例: `{"arg": "arg", "h": True}`)。 :::caution 警告 如果参数解析失败,则通过 {ref}`nonebot.params.ShellCommandArgs` 获取的将是 {ref}`nonebot.exception.ParserExit` 异常。 ::: 参数: cmds: 命令文本或命令元组 parser: {ref}`nonebot.rule.ArgumentParser` 对象 用法: 使用默认 `command_start`, `command_sep` 配置,更多示例参考 [argparse](https://docs.python.org/3/library/argparse.html) 标准库文档。 ```python from nonebot.rule import ArgumentParser parser = ArgumentParser() parser.add_argument("-a", action="store_true") rule = shell_command("ls", parser=parser) ``` :::tip 提示 命令内容与后续消息间无需空格! ::: """ if parser is not None and not isinstance(parser, ArgumentParser): raise TypeError("`parser` must be an instance of nonebot.rule.ArgumentParser") config = get_driver().config command_start = config.command_start command_sep = config.command_sep commands: List[Tuple[str, ...]] = [] for command in cmds: if isinstance(command, str): command = (command,) commands.append(command) if len(command) == 1: for start in command_start: TrieRule.add_prefix(f"{start}{command[0]}", TRIE_VALUE(start, command)) else: for start, sep in product(command_start, command_sep): TrieRule.add_prefix( f"{start}{sep.join(command)}", TRIE_VALUE(start, command) ) return Rule(ShellCommandRule(commands, parser)) The provided code snippet includes necessary dependencies for implementing the `on_shell_command` function. Write a Python function `def on_shell_command( cmd: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, parser: Optional[ArgumentParser] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 可以通过 {ref}`nonebot.params.ShellCommandArgv` 获取原始参数列表, 通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典。 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 parser: `nonebot.rule.ArgumentParser` 对象 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_shell_command( cmd: Union[str, Tuple[str, ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, parser: Optional[ArgumentParser] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 可以通过 {ref}`nonebot.params.ShellCommandArgv` 获取原始参数列表, 通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典。 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 parser: `nonebot.rule.ArgumentParser` 对象 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ commands = {cmd} | (aliases or set()) return on_message( shell_command(*commands, parser=parser) & rule, **kwargs, _depth=_depth + 1, )
注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 可以通过 {ref}`nonebot.params.ShellCommandArgv` 获取原始参数列表, 通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典。 参数: cmd: 指定命令内容 rule: 事件响应规则 aliases: 命令别名 parser: `nonebot.rule.ArgumentParser` 对象 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,075
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on_message(*args, _depth: int = 0, **kwargs) -> Type[Matcher]: """注册一个消息事件响应器。 参数: rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ kwargs.setdefault("block", True) return on("message", *args, **kwargs, _depth=_depth + 1) T_RuleChecker: TypeAlias = _DependentCallable[bool] def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: """匹配符合正则表达式的消息字符串。 可以通过 {ref}`nonebot.params.RegexStr` 获取匹配成功的字符串, 通过 {ref}`nonebot.params.RegexGroup` 获取匹配成功的 group 元组, 通过 {ref}`nonebot.params.RegexDict` 获取匹配成功的 group 字典。 参数: regex: 正则表达式 flags: 正则表达式标记 :::tip 提示 正则表达式匹配使用 search 而非 match,如需从头匹配请使用 `r"^xxx"` 来确保匹配开头 ::: :::tip 提示 正则表达式匹配使用 `EventMessage` 的 `str` 字符串, 而非 `EventMessage` 的 `PlainText` 纯文本字符串 ::: """ return Rule(RegexRule(regex, flags)) The provided code snippet includes necessary dependencies for implementing the `on_regex` function. Write a Python function `def on_regex( pattern: str, flags: Union[int, re.RegexFlag] = 0, rule: Optional[Union[Rule, T_RuleChecker]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`_ 参数: pattern: 正则表达式 flags: 正则匹配标志 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_regex( pattern: str, flags: Union[int, re.RegexFlag] = 0, rule: Optional[Union[Rule, T_RuleChecker]] = None, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`_ 参数: pattern: 正则表达式 flags: 正则匹配标志 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ return on_message(regex(pattern, flags) & rule, **kwargs, _depth=_depth + 1)
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`_ 参数: pattern: 正则表达式 flags: 正则匹配标志 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,076
import re import inspect import warnings from types import ModuleType from datetime import datetime, timedelta from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional from nonebot.adapters import Event from nonebot.permission import Permission from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, MatcherSource from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker from nonebot.rule import ( Rule, ArgumentParser, regex, command, is_type, keyword, endswith, fullmatch, startswith, shell_command, ) from .model import Plugin from . import get_plugin_by_module_name from .manager import _current_plugin_chain def on( type: str = "", rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Union[Permission, T_PermissionChecker]] = None, *, handlers: Optional[List[Union[T_Handler, Dependent]]] = None, temp: bool = False, expire_time: Optional[Union[datetime, timedelta]] = None, priority: int = 1, block: bool = False, state: Optional[T_State] = None, _depth: int = 0, ) -> Type[Matcher]: """注册一个基础事件响应器,可自定义类型。 参数: type: 事件响应器类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ matcher = Matcher.new( type, Rule() & rule, Permission() | permission, temp=temp, expire_time=expire_time, priority=priority, block=block, handlers=handlers, source=get_matcher_source(_depth + 1), default_state=state, ) store_matcher(matcher) return matcher T_RuleChecker: TypeAlias = _DependentCallable[bool] def is_type(*types: Type[Event]) -> Rule: """匹配事件类型。 参数: types: 事件类型 """ return Rule(IsTypeRule(*types)) The provided code snippet includes necessary dependencies for implementing the `on_type` function. Write a Python function `def on_type( types: Union[Type[Event], Tuple[Type[Event], ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, *, _depth: int = 0, **kwargs, ) -> Type[Matcher]` to solve the following problem: 注册一个事件响应器,并且当事件为指定类型时响应。 参数: types: 事件类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state Here is the function: def on_type( types: Union[Type[Event], Tuple[Type[Event], ...]], rule: Optional[Union[Rule, T_RuleChecker]] = None, *, _depth: int = 0, **kwargs, ) -> Type[Matcher]: """注册一个事件响应器,并且当事件为指定类型时响应。 参数: types: 事件类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state """ event_types = types if isinstance(types, tuple) else (types,) return on(rule=is_type(*event_types) & rule, **kwargs, _depth=_depth + 1)
注册一个事件响应器,并且当事件为指定类型时响应。 参数: types: 事件类型 rule: 事件响应规则 permission: 事件响应权限 handlers: 事件处理函数列表 temp: 是否为临时事件响应器(仅执行一次) expire_time: 事件响应器最终有效时间点,过时即被删除 priority: 事件响应器优先级 block: 是否阻止事件向更低优先级传递 state: 默认 state
156,077
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name def load_all_plugins( module_path: Iterable[str], plugin_dir: Iterable[str] ) -> Set[Plugin]: """导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入! 参数: module_path: 指定插件集合 plugin_dir: 指定文件夹路径集合 """ manager = PluginManager(module_path, plugin_dir) _managers.append(manager) return manager.load_all_plugins() class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None class PluginManager: """插件管理器。 参数: plugins: 独立插件模块名集合。 search_path: 插件搜索路径(文件夹)。 """ def __init__( self, plugins: Optional[Iterable[str]] = None, search_path: Optional[Iterable[str]] = None, ): # simple plugin not in search path self.plugins: Set[str] = set(plugins or []) self.search_path: Set[str] = set(search_path or []) # cache plugins self._third_party_plugin_names: Dict[str, str] = {} self._searched_plugin_names: Dict[str, Path] = {} self.prepare_plugins() def __repr__(self) -> str: return f"PluginManager(plugins={self.plugins}, search_path={self.search_path})" def third_party_plugins(self) -> Set[str]: """返回所有独立插件名称。""" return set(self._third_party_plugin_names.keys()) def searched_plugins(self) -> Set[str]: """返回已搜索到的插件名称。""" return set(self._searched_plugin_names.keys()) def available_plugins(self) -> Set[str]: """返回当前插件管理器中可用的插件名称。""" return self.third_party_plugins | self.searched_plugins def _previous_plugins(self) -> Set[str]: _pre_managers: List[PluginManager] if self in _managers: _pre_managers = _managers[: _managers.index(self)] else: _pre_managers = _managers[:] return { *chain.from_iterable(manager.available_plugins for manager in _pre_managers) } def prepare_plugins(self) -> Set[str]: """搜索插件并缓存插件名称。""" # get all previous ready to load plugins previous_plugins = self._previous_plugins() searched_plugins: Dict[str, Path] = {} third_party_plugins: Dict[str, str] = {} # check third party plugins for plugin in self.plugins: name = _module_name_to_plugin_name(plugin) if name in third_party_plugins or name in previous_plugins: raise RuntimeError( f"Plugin already exists: {name}! Check your plugin name" ) third_party_plugins[name] = plugin self._third_party_plugin_names = third_party_plugins # check plugins in search path for module_info in pkgutil.iter_modules(self.search_path): # ignore if startswith "_" if module_info.name.startswith("_"): continue if ( module_info.name in searched_plugins or module_info.name in previous_plugins or module_info.name in third_party_plugins ): raise RuntimeError( f"Plugin already exists: {module_info.name}! Check your plugin name" ) if not ( module_spec := module_info.module_finder.find_spec( module_info.name, None ) ): continue if not (module_path := module_spec.origin): continue searched_plugins[module_info.name] = Path(module_path).resolve() self._searched_plugin_names = searched_plugins return self.available_plugins def load_plugin(self, name: str) -> Optional[Plugin]: """加载指定插件。 对于独立插件,可以使用完整插件模块名或者插件名称。 参数: name: 插件名称。 """ try: if name in self.plugins: module = importlib.import_module(name) elif name in self._third_party_plugin_names: module = importlib.import_module(self._third_party_plugin_names[name]) elif name in self._searched_plugin_names: module = importlib.import_module( path_to_module_name(self._searched_plugin_names[name]) ) else: raise RuntimeError(f"Plugin not found: {name}! Check your plugin name") if ( plugin := getattr(module, "__plugin__", None) ) is None or not isinstance(plugin, Plugin): raise RuntimeError( f"Module {module.__name__} is not loaded as a plugin! " "Make sure not to import it before loading." ) logger.opt(colors=True).success( f'Succeeded to load plugin "<y>{escape_tag(plugin.name)}</y>"' + ( f' from "<m>{escape_tag(plugin.module_name)}</m>"' if plugin.module_name != plugin.name else "" ) ) return plugin except Exception as e: logger.opt(colors=True, exception=e).error( f'<r><bg #f8bbd0>Failed to import "{escape_tag(name)}"</bg #f8bbd0></r>' ) def load_all_plugins(self) -> Set[Plugin]: """加载所有可用插件。""" return set( filter(None, (self.load_plugin(name) for name in self.available_plugins)) ) The provided code snippet includes necessary dependencies for implementing the `load_plugins` function. Write a Python function `def load_plugins(*plugin_dir: str) -> Set[Plugin]` to solve the following problem: 导入文件夹下多个插件,以 `_` 开头的插件不会被导入! 参数: plugin_dir: 文件夹路径 Here is the function: def load_plugins(*plugin_dir: str) -> Set[Plugin]: """导入文件夹下多个插件,以 `_` 开头的插件不会被导入! 参数: plugin_dir: 文件夹路径 """ manager = PluginManager(search_path=plugin_dir) _managers.append(manager) return manager.load_all_plugins()
导入文件夹下多个插件,以 `_` 开头的插件不会被导入! 参数: plugin_dir: 文件夹路径
156,078
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name def load_all_plugins( module_path: Iterable[str], plugin_dir: Iterable[str] ) -> Set[Plugin]: """导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入! 参数: module_path: 指定插件集合 plugin_dir: 指定文件夹路径集合 """ manager = PluginManager(module_path, plugin_dir) _managers.append(manager) return manager.load_all_plugins() class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None The provided code snippet includes necessary dependencies for implementing the `load_from_json` function. Write a Python function `def load_from_json(file_path: str, encoding: str = "utf-8") -> Set[Plugin]` to solve the following problem: 导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 json 文件路径 encoding: 指定 json 文件编码 用法: ```json title=plugins.json { "plugins": ["some_plugin"], "plugin_dirs": ["some_dir"] } ``` ```python nonebot.load_from_json("plugins.json") ``` Here is the function: def load_from_json(file_path: str, encoding: str = "utf-8") -> Set[Plugin]: """导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 json 文件路径 encoding: 指定 json 文件编码 用法: ```json title=plugins.json { "plugins": ["some_plugin"], "plugin_dirs": ["some_dir"] } ``` ```python nonebot.load_from_json("plugins.json") ``` """ with open(file_path, encoding=encoding) as f: data = json.load(f) if not isinstance(data, dict): raise TypeError("json file must contains a dict!") plugins = data.get("plugins") plugin_dirs = data.get("plugin_dirs") assert isinstance(plugins, list), "plugins must be a list of plugin name" assert isinstance(plugin_dirs, list), "plugin_dirs must be a list of directories" return load_all_plugins(set(plugins), set(plugin_dirs))
导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 json 文件路径 encoding: 指定 json 文件编码 用法: ```json title=plugins.json { "plugins": ["some_plugin"], "plugin_dirs": ["some_dir"] } ``` ```python nonebot.load_from_json("plugins.json") ```
156,079
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name try: # pragma: py-gte-311 import tomllib # pyright: ignore[reportMissingImports] except ModuleNotFoundError: # pragma: py-lt-311 import tomli as tomllib def load_all_plugins( module_path: Iterable[str], plugin_dir: Iterable[str] ) -> Set[Plugin]: """导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入! 参数: module_path: 指定插件集合 plugin_dir: 指定文件夹路径集合 """ manager = PluginManager(module_path, plugin_dir) _managers.append(manager) return manager.load_all_plugins() class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None The provided code snippet includes necessary dependencies for implementing the `load_from_toml` function. Write a Python function `def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]` to solve the following problem: 导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 toml 文件路径 encoding: 指定 toml 文件编码 用法: ```toml title=pyproject.toml [tool.nonebot] plugins = ["some_plugin"] plugin_dirs = ["some_dir"] ``` ```python nonebot.load_from_toml("pyproject.toml") ``` Here is the function: def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]: """导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 toml 文件路径 encoding: 指定 toml 文件编码 用法: ```toml title=pyproject.toml [tool.nonebot] plugins = ["some_plugin"] plugin_dirs = ["some_dir"] ``` ```python nonebot.load_from_toml("pyproject.toml") ``` """ with open(file_path, encoding=encoding) as f: data = tomllib.loads(f.read()) nonebot_data = data.get("tool", {}).get("nonebot") if nonebot_data is None: raise ValueError("Cannot find '[tool.nonebot]' in given toml file!") if not isinstance(nonebot_data, dict): raise TypeError("'[tool.nonebot]' must be a Table!") plugins = nonebot_data.get("plugins", []) plugin_dirs = nonebot_data.get("plugin_dirs", []) assert isinstance(plugins, list), "plugins must be a list of plugin name" assert isinstance(plugin_dirs, list), "plugin_dirs must be a list of directories" return load_all_plugins(plugins, plugin_dirs)
导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件。 以 `_` 开头的插件不会被导入! 参数: file_path: 指定 toml 文件路径 encoding: 指定 toml 文件编码 用法: ```toml title=pyproject.toml [tool.nonebot] plugins = ["some_plugin"] plugin_dirs = ["some_dir"] ``` ```python nonebot.load_from_toml("pyproject.toml") ```
156,080
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: """加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 参数: module_path: 插件名称 `path.to.your.plugin` 或插件路径 `pathlib.Path(path/to/your/plugin)` """ module_path = ( path_to_module_name(module_path) if isinstance(module_path, Path) else module_path ) manager = PluginManager([module_path]) _managers.append(manager) return manager.load_plugin(module_path) class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None The provided code snippet includes necessary dependencies for implementing the `load_builtin_plugin` function. Write a Python function `def load_builtin_plugin(name: str) -> Optional[Plugin]` to solve the following problem: 导入 NoneBot 内置插件。 参数: name: 插件名称 Here is the function: def load_builtin_plugin(name: str) -> Optional[Plugin]: """导入 NoneBot 内置插件。 参数: name: 插件名称 """ return load_plugin(f"nonebot.plugins.{name}")
导入 NoneBot 内置插件。 参数: name: 插件名称
156,081
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name def load_all_plugins( module_path: Iterable[str], plugin_dir: Iterable[str] ) -> Set[Plugin]: """导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入! 参数: module_path: 指定插件集合 plugin_dir: 指定文件夹路径集合 """ manager = PluginManager(module_path, plugin_dir) _managers.append(manager) return manager.load_all_plugins() class Plugin: """存储插件信息""" name: str """插件索引标识,NoneBot 使用 文件/文件夹 名称作为标识符""" module: ModuleType """插件模块对象""" module_name: str """点分割模块路径""" manager: "PluginManager" """导入该插件的插件管理器""" matcher: Set[Type[Matcher]] = field(default_factory=set) """插件加载时定义的 `Matcher`""" parent_plugin: Optional["Plugin"] = None """父插件""" sub_plugins: Set["Plugin"] = field(default_factory=set) """子插件集合""" metadata: Optional[PluginMetadata] = None The provided code snippet includes necessary dependencies for implementing the `load_builtin_plugins` function. Write a Python function `def load_builtin_plugins(*plugins: str) -> Set[Plugin]` to solve the following problem: 导入多个 NoneBot 内置插件。 参数: plugins: 插件名称列表 Here is the function: def load_builtin_plugins(*plugins: str) -> Set[Plugin]: """导入多个 NoneBot 内置插件。 参数: plugins: 插件名称列表 """ return load_all_plugins([f"nonebot.plugins.{p}" for p in plugins], [])
导入多个 NoneBot 内置插件。 参数: plugins: 插件名称列表
156,082
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: """加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 参数: module_path: 插件名称 `path.to.your.plugin` 或插件路径 `pathlib.Path(path/to/your/plugin)` """ module_path = ( path_to_module_name(module_path) if isinstance(module_path, Path) else module_path ) manager = PluginManager([module_path]) _managers.append(manager) return manager.load_plugin(module_path) def _find_manager_by_name(name: str) -> Optional[PluginManager]: for manager in reversed(_managers): if name in manager.plugins or name in manager.searched_plugins: return manager The provided code snippet includes necessary dependencies for implementing the `require` function. Write a Python function `def require(name: str) -> ModuleType` to solve the following problem: 获取一个插件的导出内容。 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 参数: name: 插件名,即 {ref}`nonebot.plugin.model.Plugin.name`。 异常: RuntimeError: 插件无法加载 Here is the function: def require(name: str) -> ModuleType: """获取一个插件的导出内容。 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 参数: name: 插件名,即 {ref}`nonebot.plugin.model.Plugin.name`。 异常: RuntimeError: 插件无法加载 """ plugin = get_plugin(_module_name_to_plugin_name(name)) # if plugin not loaded if not plugin: # plugin already declared if manager := _find_manager_by_name(name): plugin = manager.load_plugin(name) # plugin not declared, try to declare and load it else: # clear current plugin chain, ensure plugin loaded in a new context _t = _current_plugin_chain.set(()) try: plugin = load_plugin(name) finally: _current_plugin_chain.reset(_t) if not plugin: raise RuntimeError(f'Cannot load plugin "{name}"!') return plugin.module
获取一个插件的导出内容。 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 参数: name: 插件名,即 {ref}`nonebot.plugin.model.Plugin.name`。 异常: RuntimeError: 插件无法加载
156,083
import json from pathlib import Path from types import ModuleType from typing import Set, Union, Iterable, Optional from nonebot.utils import path_to_module_name from .model import Plugin from .manager import PluginManager from . import _managers, get_plugin, _current_plugin_chain, _module_name_to_plugin_name The provided code snippet includes necessary dependencies for implementing the `inherit_supported_adapters` function. Write a Python function `def inherit_supported_adapters(*names: str) -> Optional[Set[str]]` to solve the following problem: 获取已加载插件的适配器支持状态集合。 如果传入了多个插件名称,返回值会自动取交集。 参数: names: 插件名称列表。 异常: RuntimeError: 插件未加载 ValueError: 插件缺少元数据 Here is the function: def inherit_supported_adapters(*names: str) -> Optional[Set[str]]: """获取已加载插件的适配器支持状态集合。 如果传入了多个插件名称,返回值会自动取交集。 参数: names: 插件名称列表。 异常: RuntimeError: 插件未加载 ValueError: 插件缺少元数据 """ final_supported: Optional[Set[str]] = None for name in names: plugin = get_plugin(_module_name_to_plugin_name(name)) if plugin is None: raise RuntimeError(f'Plugin "{name}" is not loaded!') meta = plugin.metadata if meta is None: raise ValueError(f'Plugin "{name}" has no metadata!') support = meta.supported_adapters if support is None: continue final_supported = ( support if final_supported is None else (final_supported & support) ) return final_supported and { ( f"nonebot.adapters.{adapter_name[1:]}" if adapter_name.startswith("~") else adapter_name ) for adapter_name in final_supported }
获取已加载插件的适配器支持状态集合。 如果传入了多个插件名称,返回值会自动取交集。 参数: names: 插件名称列表。 异常: RuntimeError: 插件未加载 ValueError: 插件缺少元数据
156,097
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated if PYDANTIC_V2: # pragma: pydantic-v2 from pydantic_core import CoreSchema, core_schema from pydantic._internal._repr import display_as_type from pydantic import TypeAdapter, GetCoreSchemaHandler from pydantic.fields import FieldInfo as BaseFieldInfo Required = Ellipsis """Alias of Ellipsis for compatibility with pydantic v1""" # Export undefined type from pydantic_core import PydanticUndefined as PydanticUndefined from pydantic_core import PydanticUndefinedType as PydanticUndefinedType # isort: split # Export model config dict from pydantic import ConfigDict as ConfigDict DEFAULT_CONFIG = ConfigDict(extra="allow", arbitrary_types_allowed=True) """Default config for validations""" class ModelField: """ModelField class for compatibility with pydantic v1""" name: str """The name of the field.""" annotation: Any """The annotation of the field.""" field_info: FieldInfo """The FieldInfo of the field.""" def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls(name, annotation, field_info) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos.""" return cls._construct(name, annotation, field_info or FieldInfo()) def _annotation_has_config(self) -> bool: """Check if the annotation has config. TypeAdapter raise error when annotation has config and given config is not None. """ type_is_annotated = origin_is_annotated(get_origin(self.annotation)) inner_type = ( get_args(self.annotation)[0] if type_is_annotated else self.annotation ) try: return ( issubclass(inner_type, BaseModel) or is_dataclass(inner_type) or is_typeddict(inner_type) ) except TypeError: return False def get_default(self) -> Any: """Get the default value of the field.""" return self.field_info.get_default(call_default_factory=True) def _type_display(self): """Get the display of the type of the field.""" return display_as_type(self.annotation) def __hash__(self) -> int: # Each ModelField is unique for our purposes, # to allow store them in a set. return id(self) else: # pragma: pydantic-v1 from pydantic import Extra from pydantic import parse_obj_as, parse_raw_as from pydantic import BaseConfig as PydanticConfig from pydantic.fields import FieldInfo as BaseFieldInfo from pydantic.fields import ModelField as BaseModelField from pydantic.schema import get_annotation_from_field_info # isort: split from pydantic.fields import Required as Required # isort: split from pydantic.fields import Undefined as PydanticUndefined from pydantic.fields import UndefinedType as PydanticUndefinedType class ConfigDict(PydanticConfig): """Config class that allow get value with default value.""" def get(cls, field: str, default: Any = None) -> Any: """Get a config value.""" return getattr(cls, field, default) class ModelField(BaseModelField): def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls( name=name, type_=annotation, class_validators=None, model_config=DEFAULT_CONFIG, default=field_info.default, default_factory=field_info.default_factory, required=( field_info.default is PydanticUndefined and field_info.default_factory is None ), field_info=field_info, ) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos. Field annotation is preprocessed with field_info. """ if field_info is not None: annotation = get_annotation_from_field_info( annotation, field_info, name ) return cls._construct(name, annotation, field_info or FieldInfo()) The provided code snippet includes necessary dependencies for implementing the `model_field_validate` function. Write a Python function `def model_field_validate( model_field: ModelField, value: Any, config: Optional[ConfigDict] = None ) -> Any` to solve the following problem: Validate the value pass to the field. Here is the function: def model_field_validate( model_field: ModelField, value: Any, config: Optional[ConfigDict] = None ) -> Any: """Validate the value pass to the field.""" type: Any = Annotated[model_field.annotation, model_field.field_info] return TypeAdapter( type, config=None if model_field._annotation_has_config() else config ).validate_python(value)
Validate the value pass to the field.
156,098
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated if PYDANTIC_V2: # pragma: pydantic-v2 from pydantic_core import CoreSchema, core_schema from pydantic._internal._repr import display_as_type from pydantic import TypeAdapter, GetCoreSchemaHandler from pydantic.fields import FieldInfo as BaseFieldInfo Required = Ellipsis """Alias of Ellipsis for compatibility with pydantic v1""" # Export undefined type from pydantic_core import PydanticUndefined as PydanticUndefined from pydantic_core import PydanticUndefinedType as PydanticUndefinedType # isort: split # Export model config dict from pydantic import ConfigDict as ConfigDict DEFAULT_CONFIG = ConfigDict(extra="allow", arbitrary_types_allowed=True) """Default config for validations""" class FieldInfo(BaseFieldInfo): """FieldInfo class with extra property for compatibility with pydantic v1""" # make default can be positional argument def __init__(self, default: Any = PydanticUndefined, **kwargs: Any) -> None: super().__init__(default=default, **kwargs) def extra(self) -> Dict[str, Any]: """Extra data that is not part of the standard pydantic fields. For compatibility with pydantic v1. """ # extract extra data from attributes set except used slots # we need to call super in advance due to # comprehension not inlined in cpython < 3.12 # https://peps.python.org/pep-0709/ slots = super().__slots__ return {k: v for k, v in self._attributes_set.items() if k not in slots} class ModelField: """ModelField class for compatibility with pydantic v1""" name: str """The name of the field.""" annotation: Any """The annotation of the field.""" field_info: FieldInfo """The FieldInfo of the field.""" def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls(name, annotation, field_info) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos.""" return cls._construct(name, annotation, field_info or FieldInfo()) def _annotation_has_config(self) -> bool: """Check if the annotation has config. TypeAdapter raise error when annotation has config and given config is not None. """ type_is_annotated = origin_is_annotated(get_origin(self.annotation)) inner_type = ( get_args(self.annotation)[0] if type_is_annotated else self.annotation ) try: return ( issubclass(inner_type, BaseModel) or is_dataclass(inner_type) or is_typeddict(inner_type) ) except TypeError: return False def get_default(self) -> Any: """Get the default value of the field.""" return self.field_info.get_default(call_default_factory=True) def _type_display(self): """Get the display of the type of the field.""" return display_as_type(self.annotation) def __hash__(self) -> int: # Each ModelField is unique for our purposes, # to allow store them in a set. return id(self) def extract_field_info(field_info: BaseFieldInfo) -> Dict[str, Any]: """Get FieldInfo init kwargs from a FieldInfo instance.""" kwargs = field_info._attributes_set.copy() kwargs["annotation"] = field_info.rebuild_annotation() return kwargs else: # pragma: pydantic-v1 from pydantic import Extra from pydantic import parse_obj_as, parse_raw_as from pydantic import BaseConfig as PydanticConfig from pydantic.fields import FieldInfo as BaseFieldInfo from pydantic.fields import ModelField as BaseModelField from pydantic.schema import get_annotation_from_field_info # isort: split from pydantic.fields import Required as Required # isort: split from pydantic.fields import Undefined as PydanticUndefined from pydantic.fields import UndefinedType as PydanticUndefinedType class FieldInfo(BaseFieldInfo): def __init__(self, default: Any = PydanticUndefined, **kwargs: Any): # preprocess default value to make it compatible with pydantic v2 # when default is Required, set it to PydanticUndefined if default is Required: default = PydanticUndefined super().__init__(default, **kwargs) class ModelField(BaseModelField): def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls( name=name, type_=annotation, class_validators=None, model_config=DEFAULT_CONFIG, default=field_info.default, default_factory=field_info.default_factory, required=( field_info.default is PydanticUndefined and field_info.default_factory is None ), field_info=field_info, ) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos. Field annotation is preprocessed with field_info. """ if field_info is not None: annotation = get_annotation_from_field_info( annotation, field_info, name ) return cls._construct(name, annotation, field_info or FieldInfo()) def extract_field_info(field_info: BaseFieldInfo) -> Dict[str, Any]: """Get FieldInfo init kwargs from a FieldInfo instance.""" kwargs = { s: getattr(field_info, s) for s in field_info.__slots__ if s != "extra" } kwargs.update(field_info.extra) return kwargs The provided code snippet includes necessary dependencies for implementing the `model_fields` function. Write a Python function `def model_fields(model: Type[BaseModel]) -> List[ModelField]` to solve the following problem: Get field list of a model. Here is the function: def model_fields(model: Type[BaseModel]) -> List[ModelField]: """Get field list of a model.""" return [ ModelField._construct( name=name, annotation=field_info.rebuild_annotation(), field_info=FieldInfo(**extract_field_info(field_info)), ) for name, field_info in model.model_fields.items() ]
Get field list of a model.
156,099
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated def model_dump( model: BaseModel, include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Dict[str, Any]: return model.model_dump( include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, )
null
156,100
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `type_validate_python` function. Write a Python function `def type_validate_python(type_: Type[T], data: Any) -> T` to solve the following problem: Validate data with given type. Here is the function: def type_validate_python(type_: Type[T], data: Any) -> T: """Validate data with given type.""" return TypeAdapter(type_).validate_python(data)
Validate data with given type.
156,101
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `type_validate_json` function. Write a Python function `def type_validate_json(type_: Type[T], data: Union[str, bytes]) -> T` to solve the following problem: Validate JSON with given type. Here is the function: def type_validate_json(type_: Type[T], data: Union[str, bytes]) -> T: """Validate JSON with given type.""" return TypeAdapter(type_).validate_json(data)
Validate JSON with given type.
156,102
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated if PYDANTIC_V2: # pragma: pydantic-v2 from pydantic_core import CoreSchema, core_schema from pydantic._internal._repr import display_as_type from pydantic import TypeAdapter, GetCoreSchemaHandler from pydantic.fields import FieldInfo as BaseFieldInfo Required = Ellipsis """Alias of Ellipsis for compatibility with pydantic v1""" # Export undefined type from pydantic_core import PydanticUndefined as PydanticUndefined from pydantic_core import PydanticUndefinedType as PydanticUndefinedType # isort: split # Export model config dict from pydantic import ConfigDict as ConfigDict DEFAULT_CONFIG = ConfigDict(extra="allow", arbitrary_types_allowed=True) """Default config for validations""" def __get_pydantic_core_schema__( cls: Type["_CustomValidationClass"], source_type: Any, handler: GetCoreSchemaHandler, ) -> CoreSchema: validators = list(cls.__get_validators__()) if len(validators) == 1: return core_schema.no_info_plain_validator_function(validators[0]) return core_schema.chain_schema( [core_schema.no_info_plain_validator_function(func) for func in validators] ) else: # pragma: pydantic-v1 from pydantic import Extra from pydantic import parse_obj_as, parse_raw_as from pydantic import BaseConfig as PydanticConfig from pydantic.fields import FieldInfo as BaseFieldInfo from pydantic.fields import ModelField as BaseModelField from pydantic.schema import get_annotation_from_field_info # isort: split from pydantic.fields import Required as Required # isort: split from pydantic.fields import Undefined as PydanticUndefined from pydantic.fields import UndefinedType as PydanticUndefinedType The provided code snippet includes necessary dependencies for implementing the `custom_validation` function. Write a Python function `def custom_validation(class_: Type["CVC"]) -> Type["CVC"]` to solve the following problem: Use pydantic v1 like validator generator in pydantic v2 Here is the function: def custom_validation(class_: Type["CVC"]) -> Type["CVC"]: """Use pydantic v1 like validator generator in pydantic v2""" setattr( class_, "__get_pydantic_core_schema__", classmethod(__get_pydantic_core_schema__), ) return class_
Use pydantic v1 like validator generator in pydantic v2
156,103
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated if PYDANTIC_V2: # pragma: pydantic-v2 from pydantic_core import CoreSchema, core_schema from pydantic._internal._repr import display_as_type from pydantic import TypeAdapter, GetCoreSchemaHandler from pydantic.fields import FieldInfo as BaseFieldInfo Required = Ellipsis """Alias of Ellipsis for compatibility with pydantic v1""" # Export undefined type from pydantic_core import PydanticUndefined as PydanticUndefined from pydantic_core import PydanticUndefinedType as PydanticUndefinedType # isort: split # Export model config dict from pydantic import ConfigDict as ConfigDict DEFAULT_CONFIG = ConfigDict(extra="allow", arbitrary_types_allowed=True) """Default config for validations""" class ModelField: """ModelField class for compatibility with pydantic v1""" name: str """The name of the field.""" annotation: Any """The annotation of the field.""" field_info: FieldInfo """The FieldInfo of the field.""" def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls(name, annotation, field_info) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos.""" return cls._construct(name, annotation, field_info or FieldInfo()) def _annotation_has_config(self) -> bool: """Check if the annotation has config. TypeAdapter raise error when annotation has config and given config is not None. """ type_is_annotated = origin_is_annotated(get_origin(self.annotation)) inner_type = ( get_args(self.annotation)[0] if type_is_annotated else self.annotation ) try: return ( issubclass(inner_type, BaseModel) or is_dataclass(inner_type) or is_typeddict(inner_type) ) except TypeError: return False def get_default(self) -> Any: """Get the default value of the field.""" return self.field_info.get_default(call_default_factory=True) def _type_display(self): """Get the display of the type of the field.""" return display_as_type(self.annotation) def __hash__(self) -> int: # Each ModelField is unique for our purposes, # to allow store them in a set. return id(self) def model_config(model: Type[BaseModel]) -> Any: """Get config of a model.""" return model.model_config else: # pragma: pydantic-v1 from pydantic import Extra from pydantic import parse_obj_as, parse_raw_as from pydantic import BaseConfig as PydanticConfig from pydantic.fields import FieldInfo as BaseFieldInfo from pydantic.fields import ModelField as BaseModelField from pydantic.schema import get_annotation_from_field_info # isort: split from pydantic.fields import Required as Required # isort: split from pydantic.fields import Undefined as PydanticUndefined from pydantic.fields import UndefinedType as PydanticUndefinedType class ConfigDict(PydanticConfig): """Config class that allow get value with default value.""" def get(cls, field: str, default: Any = None) -> Any: """Get a config value.""" return getattr(cls, field, default) class ModelField(BaseModelField): def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls( name=name, type_=annotation, class_validators=None, model_config=DEFAULT_CONFIG, default=field_info.default, default_factory=field_info.default_factory, required=( field_info.default is PydanticUndefined and field_info.default_factory is None ), field_info=field_info, ) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos. Field annotation is preprocessed with field_info. """ if field_info is not None: annotation = get_annotation_from_field_info( annotation, field_info, name ) return cls._construct(name, annotation, field_info or FieldInfo()) def model_config(model: Type[BaseModel]) -> Any: """Get config of a model.""" return model.__config__ The provided code snippet includes necessary dependencies for implementing the `model_field_validate` function. Write a Python function `def model_field_validate( model_field: ModelField, value: Any, config: Optional[Type[ConfigDict]] = None ) -> Any` to solve the following problem: Validate the value pass to the field. Set config before validate to ensure validate correctly. Here is the function: def model_field_validate( model_field: ModelField, value: Any, config: Optional[Type[ConfigDict]] = None ) -> Any: """Validate the value pass to the field. Set config before validate to ensure validate correctly. """ if model_field.model_config is not config: model_field.set_config(config or ConfigDict) v, errs_ = model_field.validate(value, {}, loc=()) if errs_: raise ValueError(value, model_field) return v
Validate the value pass to the field. Set config before validate to ensure validate correctly.
156,104
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated if PYDANTIC_V2: # pragma: pydantic-v2 from pydantic_core import CoreSchema, core_schema from pydantic._internal._repr import display_as_type from pydantic import TypeAdapter, GetCoreSchemaHandler from pydantic.fields import FieldInfo as BaseFieldInfo Required = Ellipsis """Alias of Ellipsis for compatibility with pydantic v1""" # Export undefined type from pydantic_core import PydanticUndefined as PydanticUndefined from pydantic_core import PydanticUndefinedType as PydanticUndefinedType # isort: split # Export model config dict from pydantic import ConfigDict as ConfigDict DEFAULT_CONFIG = ConfigDict(extra="allow", arbitrary_types_allowed=True) """Default config for validations""" class FieldInfo(BaseFieldInfo): """FieldInfo class with extra property for compatibility with pydantic v1""" # make default can be positional argument def __init__(self, default: Any = PydanticUndefined, **kwargs: Any) -> None: super().__init__(default=default, **kwargs) def extra(self) -> Dict[str, Any]: """Extra data that is not part of the standard pydantic fields. For compatibility with pydantic v1. """ # extract extra data from attributes set except used slots # we need to call super in advance due to # comprehension not inlined in cpython < 3.12 # https://peps.python.org/pep-0709/ slots = super().__slots__ return {k: v for k, v in self._attributes_set.items() if k not in slots} class ModelField: """ModelField class for compatibility with pydantic v1""" name: str """The name of the field.""" annotation: Any """The annotation of the field.""" field_info: FieldInfo """The FieldInfo of the field.""" def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls(name, annotation, field_info) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos.""" return cls._construct(name, annotation, field_info or FieldInfo()) def _annotation_has_config(self) -> bool: """Check if the annotation has config. TypeAdapter raise error when annotation has config and given config is not None. """ type_is_annotated = origin_is_annotated(get_origin(self.annotation)) inner_type = ( get_args(self.annotation)[0] if type_is_annotated else self.annotation ) try: return ( issubclass(inner_type, BaseModel) or is_dataclass(inner_type) or is_typeddict(inner_type) ) except TypeError: return False def get_default(self) -> Any: """Get the default value of the field.""" return self.field_info.get_default(call_default_factory=True) def _type_display(self): """Get the display of the type of the field.""" return display_as_type(self.annotation) def __hash__(self) -> int: # Each ModelField is unique for our purposes, # to allow store them in a set. return id(self) def extract_field_info(field_info: BaseFieldInfo) -> Dict[str, Any]: """Get FieldInfo init kwargs from a FieldInfo instance.""" kwargs = field_info._attributes_set.copy() kwargs["annotation"] = field_info.rebuild_annotation() return kwargs else: # pragma: pydantic-v1 from pydantic import Extra from pydantic import parse_obj_as, parse_raw_as from pydantic import BaseConfig as PydanticConfig from pydantic.fields import FieldInfo as BaseFieldInfo from pydantic.fields import ModelField as BaseModelField from pydantic.schema import get_annotation_from_field_info # isort: split from pydantic.fields import Required as Required # isort: split from pydantic.fields import Undefined as PydanticUndefined from pydantic.fields import UndefinedType as PydanticUndefinedType class FieldInfo(BaseFieldInfo): def __init__(self, default: Any = PydanticUndefined, **kwargs: Any): # preprocess default value to make it compatible with pydantic v2 # when default is Required, set it to PydanticUndefined if default is Required: default = PydanticUndefined super().__init__(default, **kwargs) class ModelField(BaseModelField): def _construct(cls, name: str, annotation: Any, field_info: FieldInfo) -> Self: return cls( name=name, type_=annotation, class_validators=None, model_config=DEFAULT_CONFIG, default=field_info.default, default_factory=field_info.default_factory, required=( field_info.default is PydanticUndefined and field_info.default_factory is None ), field_info=field_info, ) def construct( cls, name: str, annotation: Any, field_info: Optional[FieldInfo] = None ) -> Self: """Construct a ModelField from given infos. Field annotation is preprocessed with field_info. """ if field_info is not None: annotation = get_annotation_from_field_info( annotation, field_info, name ) return cls._construct(name, annotation, field_info or FieldInfo()) def extract_field_info(field_info: BaseFieldInfo) -> Dict[str, Any]: """Get FieldInfo init kwargs from a FieldInfo instance.""" kwargs = { s: getattr(field_info, s) for s in field_info.__slots__ if s != "extra" } kwargs.update(field_info.extra) return kwargs The provided code snippet includes necessary dependencies for implementing the `model_fields` function. Write a Python function `def model_fields(model: Type[BaseModel]) -> List[ModelField]` to solve the following problem: Get field list of a model. Here is the function: def model_fields(model: Type[BaseModel]) -> List[ModelField]: """Get field list of a model.""" # construct the model field without preprocess to avoid error return [ ModelField._construct( name=model_field.name, annotation=model_field.annotation, field_info=FieldInfo( **extract_field_info(model_field.field_info), ), ) for model_field in model.__fields__.values() ]
Get field list of a model.
156,105
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated def model_dump( model: BaseModel, include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Dict[str, Any]: return model.dict( include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, )
null
156,106
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `type_validate_python` function. Write a Python function `def type_validate_python(type_: Type[T], data: Any) -> T` to solve the following problem: Validate data with given type. Here is the function: def type_validate_python(type_: Type[T], data: Any) -> T: """Validate data with given type.""" return parse_obj_as(type_, data)
Validate data with given type.
156,107
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `type_validate_json` function. Write a Python function `def type_validate_json(type_: Type[T], data: Union[str, bytes]) -> T` to solve the following problem: Validate JSON with given type. Here is the function: def type_validate_json(type_: Type[T], data: Union[str, bytes]) -> T: """Validate JSON with given type.""" return parse_raw_as(type_, data)
Validate JSON with given type.
156,108
from dataclasses import dataclass, is_dataclass from typing_extensions import Self, Annotated, get_args, get_origin, is_typeddict from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Union, TypeVar, Callable, Optional, Protocol, Generator, ) from pydantic import VERSION, BaseModel from nonebot.typing import origin_is_annotated The provided code snippet includes necessary dependencies for implementing the `custom_validation` function. Write a Python function `def custom_validation(class_: Type["CVC"]) -> Type["CVC"]` to solve the following problem: Do nothing in pydantic v1 Here is the function: def custom_validation(class_: Type["CVC"]) -> Type["CVC"]: """Do nothing in pydantic v1""" return class_
Do nothing in pydantic v1
156,109
import asyncio import contextlib from datetime import datetime from contextlib import AsyncExitStack from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, matchers from nonebot.utils import escape_tag, run_coro_with_catch from nonebot.exception import ( NoLogException, StopPropagation, IgnoredException, SkippedException, ) from nonebot.typing import ( T_State, T_DependencyCache, T_RunPreProcessor, T_RunPostProcessor, T_EventPreProcessor, T_EventPostProcessor, ) from nonebot.internal.params import ( ArgParam, BotParam, EventParam, StateParam, DependParam, DefaultParam, MatcherParam, ExceptionParam, ) _event_preprocessors: Set[Dependent[Any]] = set() EVENT_PCS_PARAMS = ( DependParam, BotParam, EventParam, StateParam, DefaultParam, ) class Dependent(Generic[R]): """依赖注入容器 参数: call: 依赖注入的可调用对象,可以是任何 Callable 对象 pre_checkers: 依赖注入解析前的参数检查 params: 具名参数列表 parameterless: 匿名参数列表 allow_types: 允许的参数类型 """ call: _DependentCallable[R] params: Tuple[ModelField, ...] = field(default_factory=tuple) parameterless: Tuple[Param, ...] = field(default_factory=tuple) def __repr__(self) -> str: if inspect.isfunction(self.call) or inspect.isclass(self.call): call_str = self.call.__name__ else: call_str = repr(self.call) return ( f"Dependent(call={call_str}" + (f", parameterless={self.parameterless}" if self.parameterless else "") + ")" ) async def __call__(self, **kwargs: Any) -> R: try: # do pre-check await self.check(**kwargs) # solve param values values = await self.solve(**kwargs) # call function if is_coroutine_callable(self.call): return await cast(Callable[..., Awaitable[R]], self.call)(**values) else: return await run_sync(cast(Callable[..., R], self.call))(**values) except SkippedException as e: logger.trace(f"{self} skipped due to {e}") raise def parse_params( call: _DependentCallable[R], allow_types: Tuple[Type[Param], ...] ) -> Tuple[ModelField, ...]: fields: List[ModelField] = [] params = get_typed_signature(call).parameters.values() for param in params: if isinstance(param.default, Param): field_info = param.default else: for allow_type in allow_types: if field_info := allow_type._check_param(param, allow_types): break else: raise ValueError( f"Unknown parameter {param.name} " f"for function {call} with type {param.annotation}" ) annotation: Any = Any if param.annotation is not param.empty: annotation = param.annotation fields.append( ModelField.construct( name=param.name, annotation=annotation, field_info=field_info ) ) return tuple(fields) def parse_parameterless( parameterless: Tuple[Any, ...], allow_types: Tuple[Type[Param], ...] ) -> Tuple[Param, ...]: parameterless_params: List[Param] = [] for value in parameterless: for allow_type in allow_types: if param := allow_type._check_parameterless(value, allow_types): break else: raise ValueError(f"Unknown parameterless {value}") parameterless_params.append(param) return tuple(parameterless_params) def parse( cls, *, call: _DependentCallable[R], parameterless: Optional[Iterable[Any]] = None, allow_types: Iterable[Type[Param]], ) -> "Dependent[R]": allow_types = tuple(allow_types) params = cls.parse_params(call, allow_types) parameterless_params = ( () if parameterless is None else cls.parse_parameterless(tuple(parameterless), allow_types) ) return cls(call, params, parameterless_params) async def check(self, **params: Any) -> None: await asyncio.gather(*(param._check(**params) for param in self.parameterless)) await asyncio.gather( *(cast(Param, param.field_info)._check(**params) for param in self.params) ) async def _solve_field(self, field: ModelField, params: Dict[str, Any]) -> Any: param = cast(Param, field.field_info) value = await param._solve(**params) if value is PydanticUndefined: value = field.get_default() v = check_field_type(field, value) return v if param.validate else value async def solve(self, **params: Any) -> Dict[str, Any]: # solve parameterless for param in self.parameterless: await param._solve(**params) # solve param values values = await asyncio.gather( *(self._solve_field(field, params) for field in self.params) ) return {field.name: value for field, value in zip(self.params, values)} T_EventPreProcessor: TypeAlias = _DependentCallable[t.Any] The provided code snippet includes necessary dependencies for implementing the `event_preprocessor` function. Write a Python function `def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor` to solve the following problem: 事件预处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 Here is the function: def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor: """事件预处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 """ _event_preprocessors.add( Dependent[Any].parse(call=func, allow_types=EVENT_PCS_PARAMS) ) return func
事件预处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。
156,110
import asyncio import contextlib from datetime import datetime from contextlib import AsyncExitStack from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, matchers from nonebot.utils import escape_tag, run_coro_with_catch from nonebot.exception import ( NoLogException, StopPropagation, IgnoredException, SkippedException, ) from nonebot.typing import ( T_State, T_DependencyCache, T_RunPreProcessor, T_RunPostProcessor, T_EventPreProcessor, T_EventPostProcessor, ) from nonebot.internal.params import ( ArgParam, BotParam, EventParam, StateParam, DependParam, DefaultParam, MatcherParam, ExceptionParam, ) _event_postprocessors: Set[Dependent[Any]] = set() EVENT_PCS_PARAMS = ( DependParam, BotParam, EventParam, StateParam, DefaultParam, ) class Dependent(Generic[R]): """依赖注入容器 参数: call: 依赖注入的可调用对象,可以是任何 Callable 对象 pre_checkers: 依赖注入解析前的参数检查 params: 具名参数列表 parameterless: 匿名参数列表 allow_types: 允许的参数类型 """ call: _DependentCallable[R] params: Tuple[ModelField, ...] = field(default_factory=tuple) parameterless: Tuple[Param, ...] = field(default_factory=tuple) def __repr__(self) -> str: if inspect.isfunction(self.call) or inspect.isclass(self.call): call_str = self.call.__name__ else: call_str = repr(self.call) return ( f"Dependent(call={call_str}" + (f", parameterless={self.parameterless}" if self.parameterless else "") + ")" ) async def __call__(self, **kwargs: Any) -> R: try: # do pre-check await self.check(**kwargs) # solve param values values = await self.solve(**kwargs) # call function if is_coroutine_callable(self.call): return await cast(Callable[..., Awaitable[R]], self.call)(**values) else: return await run_sync(cast(Callable[..., R], self.call))(**values) except SkippedException as e: logger.trace(f"{self} skipped due to {e}") raise def parse_params( call: _DependentCallable[R], allow_types: Tuple[Type[Param], ...] ) -> Tuple[ModelField, ...]: fields: List[ModelField] = [] params = get_typed_signature(call).parameters.values() for param in params: if isinstance(param.default, Param): field_info = param.default else: for allow_type in allow_types: if field_info := allow_type._check_param(param, allow_types): break else: raise ValueError( f"Unknown parameter {param.name} " f"for function {call} with type {param.annotation}" ) annotation: Any = Any if param.annotation is not param.empty: annotation = param.annotation fields.append( ModelField.construct( name=param.name, annotation=annotation, field_info=field_info ) ) return tuple(fields) def parse_parameterless( parameterless: Tuple[Any, ...], allow_types: Tuple[Type[Param], ...] ) -> Tuple[Param, ...]: parameterless_params: List[Param] = [] for value in parameterless: for allow_type in allow_types: if param := allow_type._check_parameterless(value, allow_types): break else: raise ValueError(f"Unknown parameterless {value}") parameterless_params.append(param) return tuple(parameterless_params) def parse( cls, *, call: _DependentCallable[R], parameterless: Optional[Iterable[Any]] = None, allow_types: Iterable[Type[Param]], ) -> "Dependent[R]": allow_types = tuple(allow_types) params = cls.parse_params(call, allow_types) parameterless_params = ( () if parameterless is None else cls.parse_parameterless(tuple(parameterless), allow_types) ) return cls(call, params, parameterless_params) async def check(self, **params: Any) -> None: await asyncio.gather(*(param._check(**params) for param in self.parameterless)) await asyncio.gather( *(cast(Param, param.field_info)._check(**params) for param in self.params) ) async def _solve_field(self, field: ModelField, params: Dict[str, Any]) -> Any: param = cast(Param, field.field_info) value = await param._solve(**params) if value is PydanticUndefined: value = field.get_default() v = check_field_type(field, value) return v if param.validate else value async def solve(self, **params: Any) -> Dict[str, Any]: # solve parameterless for param in self.parameterless: await param._solve(**params) # solve param values values = await asyncio.gather( *(self._solve_field(field, params) for field in self.params) ) return {field.name: value for field, value in zip(self.params, values)} T_EventPostProcessor: TypeAlias = _DependentCallable[t.Any] The provided code snippet includes necessary dependencies for implementing the `event_postprocessor` function. Write a Python function `def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor` to solve the following problem: 事件后处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 Here is the function: def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor: """事件后处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 """ _event_postprocessors.add( Dependent[Any].parse(call=func, allow_types=EVENT_PCS_PARAMS) ) return func
事件后处理。 装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。
156,111
import asyncio import contextlib from datetime import datetime from contextlib import AsyncExitStack from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, matchers from nonebot.utils import escape_tag, run_coro_with_catch from nonebot.exception import ( NoLogException, StopPropagation, IgnoredException, SkippedException, ) from nonebot.typing import ( T_State, T_DependencyCache, T_RunPreProcessor, T_RunPostProcessor, T_EventPreProcessor, T_EventPostProcessor, ) from nonebot.internal.params import ( ArgParam, BotParam, EventParam, StateParam, DependParam, DefaultParam, MatcherParam, ExceptionParam, ) _run_preprocessors: Set[Dependent[Any]] = set() RUN_PREPCS_PARAMS = ( DependParam, BotParam, EventParam, StateParam, ArgParam, MatcherParam, DefaultParam, ) class Dependent(Generic[R]): """依赖注入容器 参数: call: 依赖注入的可调用对象,可以是任何 Callable 对象 pre_checkers: 依赖注入解析前的参数检查 params: 具名参数列表 parameterless: 匿名参数列表 allow_types: 允许的参数类型 """ call: _DependentCallable[R] params: Tuple[ModelField, ...] = field(default_factory=tuple) parameterless: Tuple[Param, ...] = field(default_factory=tuple) def __repr__(self) -> str: if inspect.isfunction(self.call) or inspect.isclass(self.call): call_str = self.call.__name__ else: call_str = repr(self.call) return ( f"Dependent(call={call_str}" + (f", parameterless={self.parameterless}" if self.parameterless else "") + ")" ) async def __call__(self, **kwargs: Any) -> R: try: # do pre-check await self.check(**kwargs) # solve param values values = await self.solve(**kwargs) # call function if is_coroutine_callable(self.call): return await cast(Callable[..., Awaitable[R]], self.call)(**values) else: return await run_sync(cast(Callable[..., R], self.call))(**values) except SkippedException as e: logger.trace(f"{self} skipped due to {e}") raise def parse_params( call: _DependentCallable[R], allow_types: Tuple[Type[Param], ...] ) -> Tuple[ModelField, ...]: fields: List[ModelField] = [] params = get_typed_signature(call).parameters.values() for param in params: if isinstance(param.default, Param): field_info = param.default else: for allow_type in allow_types: if field_info := allow_type._check_param(param, allow_types): break else: raise ValueError( f"Unknown parameter {param.name} " f"for function {call} with type {param.annotation}" ) annotation: Any = Any if param.annotation is not param.empty: annotation = param.annotation fields.append( ModelField.construct( name=param.name, annotation=annotation, field_info=field_info ) ) return tuple(fields) def parse_parameterless( parameterless: Tuple[Any, ...], allow_types: Tuple[Type[Param], ...] ) -> Tuple[Param, ...]: parameterless_params: List[Param] = [] for value in parameterless: for allow_type in allow_types: if param := allow_type._check_parameterless(value, allow_types): break else: raise ValueError(f"Unknown parameterless {value}") parameterless_params.append(param) return tuple(parameterless_params) def parse( cls, *, call: _DependentCallable[R], parameterless: Optional[Iterable[Any]] = None, allow_types: Iterable[Type[Param]], ) -> "Dependent[R]": allow_types = tuple(allow_types) params = cls.parse_params(call, allow_types) parameterless_params = ( () if parameterless is None else cls.parse_parameterless(tuple(parameterless), allow_types) ) return cls(call, params, parameterless_params) async def check(self, **params: Any) -> None: await asyncio.gather(*(param._check(**params) for param in self.parameterless)) await asyncio.gather( *(cast(Param, param.field_info)._check(**params) for param in self.params) ) async def _solve_field(self, field: ModelField, params: Dict[str, Any]) -> Any: param = cast(Param, field.field_info) value = await param._solve(**params) if value is PydanticUndefined: value = field.get_default() v = check_field_type(field, value) return v if param.validate else value async def solve(self, **params: Any) -> Dict[str, Any]: # solve parameterless for param in self.parameterless: await param._solve(**params) # solve param values values = await asyncio.gather( *(self._solve_field(field, params) for field in self.params) ) return {field.name: value for field, value in zip(self.params, values)} T_RunPreProcessor: TypeAlias = _DependentCallable[t.Any] The provided code snippet includes necessary dependencies for implementing the `run_preprocessor` function. Write a Python function `def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor` to solve the following problem: 运行预处理。 装饰一个函数,使它在每次事件响应器运行前执行。 Here is the function: def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor: """运行预处理。 装饰一个函数,使它在每次事件响应器运行前执行。 """ _run_preprocessors.add( Dependent[Any].parse(call=func, allow_types=RUN_PREPCS_PARAMS) ) return func
运行预处理。 装饰一个函数,使它在每次事件响应器运行前执行。
156,112
import asyncio import contextlib from datetime import datetime from contextlib import AsyncExitStack from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, matchers from nonebot.utils import escape_tag, run_coro_with_catch from nonebot.exception import ( NoLogException, StopPropagation, IgnoredException, SkippedException, ) from nonebot.typing import ( T_State, T_DependencyCache, T_RunPreProcessor, T_RunPostProcessor, T_EventPreProcessor, T_EventPostProcessor, ) from nonebot.internal.params import ( ArgParam, BotParam, EventParam, StateParam, DependParam, DefaultParam, MatcherParam, ExceptionParam, ) _run_postprocessors: Set[Dependent[Any]] = set() RUN_POSTPCS_PARAMS = ( DependParam, ExceptionParam, BotParam, EventParam, StateParam, ArgParam, MatcherParam, DefaultParam, ) class Dependent(Generic[R]): """依赖注入容器 参数: call: 依赖注入的可调用对象,可以是任何 Callable 对象 pre_checkers: 依赖注入解析前的参数检查 params: 具名参数列表 parameterless: 匿名参数列表 allow_types: 允许的参数类型 """ call: _DependentCallable[R] params: Tuple[ModelField, ...] = field(default_factory=tuple) parameterless: Tuple[Param, ...] = field(default_factory=tuple) def __repr__(self) -> str: if inspect.isfunction(self.call) or inspect.isclass(self.call): call_str = self.call.__name__ else: call_str = repr(self.call) return ( f"Dependent(call={call_str}" + (f", parameterless={self.parameterless}" if self.parameterless else "") + ")" ) async def __call__(self, **kwargs: Any) -> R: try: # do pre-check await self.check(**kwargs) # solve param values values = await self.solve(**kwargs) # call function if is_coroutine_callable(self.call): return await cast(Callable[..., Awaitable[R]], self.call)(**values) else: return await run_sync(cast(Callable[..., R], self.call))(**values) except SkippedException as e: logger.trace(f"{self} skipped due to {e}") raise def parse_params( call: _DependentCallable[R], allow_types: Tuple[Type[Param], ...] ) -> Tuple[ModelField, ...]: fields: List[ModelField] = [] params = get_typed_signature(call).parameters.values() for param in params: if isinstance(param.default, Param): field_info = param.default else: for allow_type in allow_types: if field_info := allow_type._check_param(param, allow_types): break else: raise ValueError( f"Unknown parameter {param.name} " f"for function {call} with type {param.annotation}" ) annotation: Any = Any if param.annotation is not param.empty: annotation = param.annotation fields.append( ModelField.construct( name=param.name, annotation=annotation, field_info=field_info ) ) return tuple(fields) def parse_parameterless( parameterless: Tuple[Any, ...], allow_types: Tuple[Type[Param], ...] ) -> Tuple[Param, ...]: parameterless_params: List[Param] = [] for value in parameterless: for allow_type in allow_types: if param := allow_type._check_parameterless(value, allow_types): break else: raise ValueError(f"Unknown parameterless {value}") parameterless_params.append(param) return tuple(parameterless_params) def parse( cls, *, call: _DependentCallable[R], parameterless: Optional[Iterable[Any]] = None, allow_types: Iterable[Type[Param]], ) -> "Dependent[R]": allow_types = tuple(allow_types) params = cls.parse_params(call, allow_types) parameterless_params = ( () if parameterless is None else cls.parse_parameterless(tuple(parameterless), allow_types) ) return cls(call, params, parameterless_params) async def check(self, **params: Any) -> None: await asyncio.gather(*(param._check(**params) for param in self.parameterless)) await asyncio.gather( *(cast(Param, param.field_info)._check(**params) for param in self.params) ) async def _solve_field(self, field: ModelField, params: Dict[str, Any]) -> Any: param = cast(Param, field.field_info) value = await param._solve(**params) if value is PydanticUndefined: value = field.get_default() v = check_field_type(field, value) return v if param.validate else value async def solve(self, **params: Any) -> Dict[str, Any]: # solve parameterless for param in self.parameterless: await param._solve(**params) # solve param values values = await asyncio.gather( *(self._solve_field(field, params) for field in self.params) ) return {field.name: value for field, value in zip(self.params, values)} T_RunPostProcessor: TypeAlias = _DependentCallable[t.Any] The provided code snippet includes necessary dependencies for implementing the `run_postprocessor` function. Write a Python function `def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor` to solve the following problem: 运行后处理。 装饰一个函数,使它在每次事件响应器运行后执行。 Here is the function: def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor: """运行后处理。 装饰一个函数,使它在每次事件响应器运行后执行。 """ _run_postprocessors.add( Dependent[Any].parse(call=func, allow_types=RUN_POSTPCS_PARAMS) ) return func
运行后处理。 装饰一个函数,使它在每次事件响应器运行后执行。
156,113
import asyncio import contextlib from datetime import datetime from contextlib import AsyncExitStack from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.dependencies import Dependent from nonebot.matcher import Matcher, matchers from nonebot.utils import escape_tag, run_coro_with_catch from nonebot.exception import ( NoLogException, StopPropagation, IgnoredException, SkippedException, ) from nonebot.typing import ( T_State, T_DependencyCache, T_RunPreProcessor, T_RunPostProcessor, T_EventPreProcessor, T_EventPostProcessor, ) from nonebot.internal.params import ( ArgParam, BotParam, EventParam, StateParam, DependParam, DefaultParam, MatcherParam, ExceptionParam, ) async def _apply_event_preprocessors( bot: "Bot", event: "Event", state: T_State, stack: Optional[AsyncExitStack] = None, dependency_cache: Optional[T_DependencyCache] = None, show_log: bool = True, ) -> bool: """运行事件预处理。 参数: bot: Bot 对象 event: Event 对象 state: 会话状态 stack: 异步上下文栈 dependency_cache: 依赖缓存 show_log: 是否显示日志 返回: 是否继续处理事件 """ if not _event_preprocessors: return True if show_log: logger.debug("Running PreProcessors...") try: await asyncio.gather( *( run_coro_with_catch( proc( bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ), (SkippedException,), ) for proc in _event_preprocessors ) ) except IgnoredException: logger.opt(colors=True).info( f"Event {escape_tag(event.get_event_name())} is <b>ignored</b>" ) return False except Exception as e: logger.opt(colors=True, exception=e).error( "<r><bg #f8bbd0>Error when running EventPreProcessors. " "Event ignored!</bg #f8bbd0></r>" ) return False return True async def _apply_event_postprocessors( bot: "Bot", event: "Event", state: T_State, stack: Optional[AsyncExitStack] = None, dependency_cache: Optional[T_DependencyCache] = None, show_log: bool = True, ) -> None: """运行事件后处理。 参数: bot: Bot 对象 event: Event 对象 state: 会话状态 stack: 异步上下文栈 dependency_cache: 依赖缓存 show_log: 是否显示日志 """ if not _event_postprocessors: return if show_log: logger.debug("Running PostProcessors...") try: await asyncio.gather( *( run_coro_with_catch( proc( bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ), (SkippedException,), ) for proc in _event_postprocessors ) ) except Exception as e: logger.opt(colors=True, exception=e).error( "<r><bg #f8bbd0>Error when running EventPostProcessors</bg #f8bbd0></r>" ) async def check_and_run_matcher( Matcher: Type[Matcher], bot: "Bot", event: "Event", state: T_State, stack: Optional[AsyncExitStack] = None, dependency_cache: Optional[T_DependencyCache] = None, ) -> None: """检查并运行事件响应器。 参数: Matcher: 事件响应器 bot: Bot 对象 event: Event 对象 state: 会话状态 stack: 异步上下文栈 dependency_cache: 依赖缓存 """ if not await _check_matcher( Matcher=Matcher, bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ): return await _run_matcher( Matcher=Matcher, bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ) logger: "Logger" = loguru.logger class TrieRule: prefix: CharTrie = CharTrie() def add_prefix(cls, prefix: str, value: TRIE_VALUE) -> None: if prefix in cls.prefix: logger.warning(f'Duplicated prefix rule "{prefix}"') return cls.prefix[prefix] = value def get_value(cls, bot: Bot, event: Event, state: T_State) -> CMD_RESULT: prefix = CMD_RESULT( command=None, raw_command=None, command_arg=None, command_start=None, command_whitespace=None, ) state[PREFIX_KEY] = prefix if event.get_type() != "message": return prefix message = event.get_message() message_seg: MessageSegment = message[0] if message_seg.is_text(): segment_text = str(message_seg).lstrip() if pf := cls.prefix.longest_prefix(segment_text): value: TRIE_VALUE = pf.value prefix[RAW_CMD_KEY] = pf.key prefix[CMD_START_KEY] = value.command_start prefix[CMD_KEY] = value.command msg = message.copy() msg.pop(0) # check whitespace arg_str = segment_text[len(pf.key) :] arg_str_stripped = arg_str.lstrip() # check next segment until arg detected or no text remain while not arg_str_stripped and msg and msg[0].is_text(): arg_str += str(msg.pop(0)) arg_str_stripped = arg_str.lstrip() has_arg = arg_str_stripped or msg if ( has_arg and (stripped_len := len(arg_str) - len(arg_str_stripped)) > 0 ): prefix[CMD_WHITESPACE_KEY] = arg_str[:stripped_len] # construct command arg if arg_str_stripped: new_message = msg.__class__(arg_str_stripped) for new_segment in reversed(new_message): msg.insert(0, new_segment) prefix[CMD_ARG_KEY] = msg return prefix def escape_tag(s: str) -> str: """用于记录带颜色日志时转义 `<tag>` 类型特殊标签 参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color) 参数: s: 需要转义的字符串 """ return re.sub(r"</?((?:[fb]g\s)?[^<>\s]*)>", r"\\\g<0>", s) class StopPropagation(ProcessException): """指示 NoneBot 终止事件向下层传播。 在 {ref}`nonebot.matcher.Matcher.block` 为 `True` 或使用 {ref}`nonebot.matcher.Matcher.stop_propagation` 方法时抛出。 用法: ```python matcher = on_notice(block=True) # 或者 async def handler(matcher: Matcher): matcher.stop_propagation() ``` """ class NoLogException(AdapterException): """指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息。 可在 {ref}`nonebot.adapters.Event.get_log_string` 时抛出 """ T_DependencyCache: TypeAlias = t.Dict[_DependentCallable[t.Any], "Task[t.Any]"] The provided code snippet includes necessary dependencies for implementing the `handle_event` function. Write a Python function `async def handle_event(bot: "Bot", event: "Event") -> None` to solve the following problem: 处理一个事件。调用该函数以实现分发事件。 参数: bot: Bot 对象 event: Event 对象 用法: ```python import asyncio asyncio.create_task(handle_event(bot, event)) ``` Here is the function: async def handle_event(bot: "Bot", event: "Event") -> None: """处理一个事件。调用该函数以实现分发事件。 参数: bot: Bot 对象 event: Event 对象 用法: ```python import asyncio asyncio.create_task(handle_event(bot, event)) ``` """ show_log = True log_msg = f"<m>{escape_tag(bot.type)} {escape_tag(bot.self_id)}</m> | " try: log_msg += event.get_log_string() except NoLogException: show_log = False if show_log: logger.opt(colors=True).success(log_msg) state: Dict[Any, Any] = {} dependency_cache: T_DependencyCache = {} # create event scope context async with AsyncExitStack() as stack: if not await _apply_event_preprocessors( bot=bot, event=event, state=state, stack=stack, dependency_cache=dependency_cache, ): return # Trie Match try: TrieRule.get_value(bot, event, state) except Exception as e: logger.opt(colors=True, exception=e).warning( "Error while parsing command for event" ) break_flag = False # iterate through all priority until stop propagation for priority in sorted(matchers.keys()): if break_flag: break if show_log: logger.debug(f"Checking for matchers in priority {priority}...") pending_tasks = [ check_and_run_matcher( matcher, bot, event, state.copy(), stack, dependency_cache ) for matcher in matchers[priority] ] results = await asyncio.gather(*pending_tasks, return_exceptions=True) for result in results: if not isinstance(result, Exception): continue if isinstance(result, StopPropagation): break_flag = True logger.debug("Stop event propagation") else: logger.opt(colors=True, exception=result).error( "<r><bg #f8bbd0>Error when checking Matcher.</bg #f8bbd0></r>" ) if show_log: logger.debug("Checking for matchers completed") await _apply_event_postprocessors(bot, event, state, stack, dependency_cache)
处理一个事件。调用该函数以实现分发事件。 参数: bot: Bot 对象 event: Event 对象 用法: ```python import asyncio asyncio.create_task(handle_event(bot, event)) ```
156,114
import asyncio import inspect from contextlib import AsyncExitStack, contextmanager, asynccontextmanager from typing_extensions import Self, Annotated, get_args, override, get_origin from typing import ( TYPE_CHECKING, Any, Type, Tuple, Union, Literal, Callable, Optional, cast, ) from pydantic.fields import FieldInfo as PydanticFieldInfo from nonebot.dependencies import Param, Dependent from nonebot.dependencies.utils import check_field_type from nonebot.typing import T_State, T_Handler, T_DependencyCache from nonebot.compat import FieldInfo, ModelField, PydanticUndefined, extract_field_info from nonebot.utils import ( get_name, run_sync, is_gen_callable, run_sync_ctx_manager, is_async_gen_callable, is_coroutine_callable, generic_check_issubclass, ) class ArgInner: def __init__( self, key: Optional[str], type: Literal["message", "str", "plaintext"] ) -> None: self.key: Optional[str] = key self.type: Literal["message", "str", "plaintext"] = type def __repr__(self) -> str: return f"ArgInner(key={self.key!r}, type={self.type!r})" The provided code snippet includes necessary dependencies for implementing the `Arg` function. Write a Python function `def Arg(key: Optional[str] = None) -> Any` to solve the following problem: Arg 参数消息 Here is the function: def Arg(key: Optional[str] = None) -> Any: """Arg 参数消息""" return ArgInner(key, "message")
Arg 参数消息
156,115
import asyncio import inspect from contextlib import AsyncExitStack, contextmanager, asynccontextmanager from typing_extensions import Self, Annotated, get_args, override, get_origin from typing import ( TYPE_CHECKING, Any, Type, Tuple, Union, Literal, Callable, Optional, cast, ) from pydantic.fields import FieldInfo as PydanticFieldInfo from nonebot.dependencies import Param, Dependent from nonebot.dependencies.utils import check_field_type from nonebot.typing import T_State, T_Handler, T_DependencyCache from nonebot.compat import FieldInfo, ModelField, PydanticUndefined, extract_field_info from nonebot.utils import ( get_name, run_sync, is_gen_callable, run_sync_ctx_manager, is_async_gen_callable, is_coroutine_callable, generic_check_issubclass, ) class ArgInner: def __init__( self, key: Optional[str], type: Literal["message", "str", "plaintext"] ) -> None: self.key: Optional[str] = key self.type: Literal["message", "str", "plaintext"] = type def __repr__(self) -> str: return f"ArgInner(key={self.key!r}, type={self.type!r})" The provided code snippet includes necessary dependencies for implementing the `ArgStr` function. Write a Python function `def ArgStr(key: Optional[str] = None) -> str` to solve the following problem: Arg 参数消息文本 Here is the function: def ArgStr(key: Optional[str] = None) -> str: """Arg 参数消息文本""" return ArgInner(key, "str") # type: ignore
Arg 参数消息文本
156,116
import asyncio import inspect from contextlib import AsyncExitStack, contextmanager, asynccontextmanager from typing_extensions import Self, Annotated, get_args, override, get_origin from typing import ( TYPE_CHECKING, Any, Type, Tuple, Union, Literal, Callable, Optional, cast, ) from pydantic.fields import FieldInfo as PydanticFieldInfo from nonebot.dependencies import Param, Dependent from nonebot.dependencies.utils import check_field_type from nonebot.typing import T_State, T_Handler, T_DependencyCache from nonebot.compat import FieldInfo, ModelField, PydanticUndefined, extract_field_info from nonebot.utils import ( get_name, run_sync, is_gen_callable, run_sync_ctx_manager, is_async_gen_callable, is_coroutine_callable, generic_check_issubclass, ) class ArgInner: def __init__( self, key: Optional[str], type: Literal["message", "str", "plaintext"] ) -> None: self.key: Optional[str] = key self.type: Literal["message", "str", "plaintext"] = type def __repr__(self) -> str: return f"ArgInner(key={self.key!r}, type={self.type!r})" The provided code snippet includes necessary dependencies for implementing the `ArgPlainText` function. Write a Python function `def ArgPlainText(key: Optional[str] = None) -> str` to solve the following problem: Arg 参数消息纯文本 Here is the function: def ArgPlainText(key: Optional[str] = None) -> str: """Arg 参数消息纯文本""" return ArgInner(key, "plaintext") # type: ignore
Arg 参数消息纯文本
156,117
import functools from string import Formatter from typing_extensions import TypeAlias from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, cast, overload, ) from _string import formatter_field_name_split def formatter_field_name_split( field_name: str, ) -> Tuple[str, List[Tuple[bool, str]]]: ...
null
156,118
import asyncio from typing_extensions import Self from contextlib import AsyncExitStack from typing import Set, List, Type, Tuple, Union, ClassVar, NoReturn, Optional from nonebot.dependencies import Dependent from nonebot.utils import run_coro_with_catch from nonebot.exception import SkippedException from nonebot.typing import T_DependencyCache, T_PermissionChecker from .adapter import Bot, Event from .params import Param, BotParam, EventParam, DependParam, DefaultParam class Permission: """{ref}`nonebot.matcher.Matcher` 权限类。 当事件传递时,在 {ref}`nonebot.matcher.Matcher` 运行前进行检查。 参数: checkers: PermissionChecker 用法: ```python Permission(async_function) | sync_function # 等价于 Permission(async_function, sync_function) ``` """ __slots__ = ("checkers",) HANDLER_PARAM_TYPES: ClassVar[List[Type[Param]]] = [ DependParam, BotParam, EventParam, DefaultParam, ] def __init__(self, *checkers: Union[T_PermissionChecker, Dependent[bool]]) -> None: self.checkers: Set[Dependent[bool]] = { ( checker if isinstance(checker, Dependent) else Dependent[bool].parse( call=checker, allow_types=self.HANDLER_PARAM_TYPES ) ) for checker in checkers } """存储 `PermissionChecker`""" def __repr__(self) -> str: return f"Permission({', '.join(repr(checker) for checker in self.checkers)})" async def __call__( self, bot: Bot, event: Event, stack: Optional[AsyncExitStack] = None, dependency_cache: Optional[T_DependencyCache] = None, ) -> bool: """检查是否满足某个权限。 参数: bot: Bot 对象 event: Event 对象 stack: 异步上下文栈 dependency_cache: 依赖缓存 """ if not self.checkers: return True results = await asyncio.gather( *( run_coro_with_catch( checker( bot=bot, event=event, stack=stack, dependency_cache=dependency_cache, ), (SkippedException,), False, ) for checker in self.checkers ), ) return any(results) def __and__(self, other: object) -> NoReturn: raise RuntimeError("And operation between Permissions is not allowed.") def __or__( self, other: Optional[Union["Permission", T_PermissionChecker]] ) -> "Permission": if other is None: return self elif isinstance(other, Permission): return Permission(*self.checkers, *other.checkers) else: return Permission(*self.checkers, other) def __ror__( self, other: Optional[Union["Permission", T_PermissionChecker]] ) -> "Permission": if other is None: return self elif isinstance(other, Permission): return Permission(*other.checkers, *self.checkers) else: return Permission(other, *self.checkers) class User: """检查当前事件是否属于指定会话。 参数: users: 会话 ID 元组 perm: 需同时满足的权限 """ __slots__ = ("users", "perm") def __init__( self, users: Tuple[str, ...], perm: Optional[Permission] = None ) -> None: self.users = users self.perm = perm def __repr__(self) -> str: return ( f"User(users={self.users}" + (f", permission={self.perm})" if self.perm else "") + ")" ) async def __call__(self, bot: Bot, event: Event) -> bool: try: session = event.get_session_id() except Exception: return False return bool( session in self.users and (self.perm is None or await self.perm(bot, event)) ) def _clean_permission(cls, perm: Permission) -> Optional[Permission]: if len(perm.checkers) == 1 and isinstance( user_perm := next(iter(perm.checkers)).call, cls ): return user_perm.perm return perm def from_event(cls, event: Event, perm: Optional[Permission] = None) -> Self: """从事件中获取会话 ID。 如果 `perm` 中仅有 `User` 类型的权限检查函数,则会去除原有的会话 ID 限制。 参数: event: Event 对象 perm: 需同时满足的权限 """ return cls((event.get_session_id(),), perm=perm and cls._clean_permission(perm)) def from_permission(cls, *users: str, perm: Optional[Permission] = None) -> Self: """指定会话与权限。 如果 `perm` 中仅有 `User` 类型的权限检查函数,则会去除原有的会话 ID 限制。 参数: users: 会话白名单 perm: 需同时满足的权限 """ return cls(users, perm=perm and cls._clean_permission(perm)) The provided code snippet includes necessary dependencies for implementing the `USER` function. Write a Python function `def USER(*users: str, perm: Optional[Permission] = None)` to solve the following problem: 匹配当前事件属于指定会话。 如果 `perm` 中仅有 `User` 类型的权限检查函数,则会去除原有检查函数的会话 ID 限制。 参数: user: 会话白名单 perm: 需要同时满足的权限 Here is the function: def USER(*users: str, perm: Optional[Permission] = None): """匹配当前事件属于指定会话。 如果 `perm` 中仅有 `User` 类型的权限检查函数,则会去除原有检查函数的会话 ID 限制。 参数: user: 会话白名单 perm: 需要同时满足的权限 """ return Permission(User.from_permission(*users, perm=perm))
匹配当前事件属于指定会话。 如果 `perm` 中仅有 `User` 类型的权限检查函数,则会去除原有检查函数的会话 ID 限制。 参数: user: 会话白名单 perm: 需要同时满足的权限
156,119
from typing import TYPE_CHECKING, Type, Union, TypeVar, overload from .abstract import Mixin, Driver D = TypeVar("D", bound="Driver") def combine_driver(driver: Type[D]) -> Type[D]: ...
null
156,120
from typing import TYPE_CHECKING, Type, Union, TypeVar, overload from .abstract import Mixin, Driver D = TypeVar("D", bound="Driver") class Mixin(abc.ABC): """可与其他驱动器共用的混入基类。""" def type(self) -> str: """混入驱动类型名称""" raise NotImplementedError def combine_driver(driver: Type[D], *mixins: Type[Mixin]) -> Type["CombinedDriver"]: ...
null
156,121
from typing import TYPE_CHECKING, Type, Union, TypeVar, overload from .abstract import Mixin, Driver D = TypeVar("D", bound="Driver") class Driver(abc.ABC): """驱动器基类。 驱动器控制框架的启动和停止,适配器的注册,以及机器人生命周期管理。 参数: env: 包含环境信息的 Env 对象 config: 包含配置信息的 Config 对象 """ _adapters: ClassVar[Dict[str, "Adapter"]] = {} """已注册的适配器列表""" _bot_connection_hook: ClassVar[Set[Dependent[Any]]] = set() """Bot 连接建立时执行的函数""" _bot_disconnection_hook: ClassVar[Set[Dependent[Any]]] = set() """Bot 连接断开时执行的函数""" def __init__(self, env: Env, config: Config): self.env: str = env.environment """环境名称""" self.config: Config = config """全局配置对象""" self._bots: Dict[str, "Bot"] = {} self._bot_tasks: Set[asyncio.Task] = set() self._lifespan = Lifespan() def __repr__(self) -> str: return ( f"Driver(type={self.type!r}, " f"adapters={len(self._adapters)}, bots={len(self._bots)})" ) def bots(self) -> Dict[str, "Bot"]: """获取当前所有已连接的 Bot""" return self._bots def register_adapter(self, adapter: Type["Adapter"], **kwargs) -> None: """注册一个协议适配器 参数: adapter: 适配器类 kwargs: 其他传递给适配器的参数 """ name = adapter.get_name() if name in self._adapters: logger.opt(colors=True).debug( f'Adapter "<y>{escape_tag(name)}</y>" already exists' ) return self._adapters[name] = adapter(self, **kwargs) logger.opt(colors=True).debug( f'Succeeded to load adapter "<y>{escape_tag(name)}</y>"' ) def type(self) -> str: """驱动类型名称""" raise NotImplementedError def logger(self): """驱动专属 logger 日志记录器""" raise NotImplementedError def run(self, *args, **kwargs): """启动驱动框架""" logger.opt(colors=True).debug( f"<g>Loaded adapters: {escape_tag(', '.join(self._adapters))}</g>" ) self.on_shutdown(self._cleanup) def on_startup(self, func: LIFESPAN_FUNC) -> LIFESPAN_FUNC: """注册一个启动时执行的函数""" return self._lifespan.on_startup(func) def on_shutdown(self, func: LIFESPAN_FUNC) -> LIFESPAN_FUNC: """注册一个停止时执行的函数""" return self._lifespan.on_shutdown(func) def on_bot_connect(cls, func: T_BotConnectionHook) -> T_BotConnectionHook: """装饰一个函数使他在 bot 连接成功时执行。 钩子函数参数: - bot: 当前连接上的 Bot 对象 """ cls._bot_connection_hook.add( Dependent[Any].parse(call=func, allow_types=BOT_HOOK_PARAMS) ) return func def on_bot_disconnect(cls, func: T_BotDisconnectionHook) -> T_BotDisconnectionHook: """装饰一个函数使他在 bot 连接断开时执行。 钩子函数参数: - bot: 当前连接上的 Bot 对象 """ cls._bot_disconnection_hook.add( Dependent[Any].parse(call=func, allow_types=BOT_HOOK_PARAMS) ) return func def _bot_connect(self, bot: "Bot") -> None: """在连接成功后,调用该函数来注册 bot 对象""" if bot.self_id in self._bots: raise RuntimeError(f"Duplicate bot connection with id {bot.self_id}") self._bots[bot.self_id] = bot async def _run_hook(bot: "Bot") -> None: dependency_cache: T_DependencyCache = {} async with AsyncExitStack() as stack: if coros := [ run_coro_with_catch( hook(bot=bot, stack=stack, dependency_cache=dependency_cache), (SkippedException,), ) for hook in self._bot_connection_hook ]: try: await asyncio.gather(*coros) except Exception as e: logger.opt(colors=True, exception=e).error( "<r><bg #f8bbd0>" "Error when running WebSocketConnection hook. " "Running cancelled!" "</bg #f8bbd0></r>" ) task = asyncio.create_task(_run_hook(bot)) task.add_done_callback(self._bot_tasks.discard) self._bot_tasks.add(task) def _bot_disconnect(self, bot: "Bot") -> None: """在连接断开后,调用该函数来注销 bot 对象""" if bot.self_id in self._bots: del self._bots[bot.self_id] async def _run_hook(bot: "Bot") -> None: dependency_cache: T_DependencyCache = {} async with AsyncExitStack() as stack: if coros := [ run_coro_with_catch( hook(bot=bot, stack=stack, dependency_cache=dependency_cache), (SkippedException,), ) for hook in self._bot_disconnection_hook ]: try: await asyncio.gather(*coros) except Exception as e: logger.opt(colors=True, exception=e).error( "<r><bg #f8bbd0>" "Error when running WebSocketDisConnection hook. " "Running cancelled!" "</bg #f8bbd0></r>" ) task = asyncio.create_task(_run_hook(bot)) task.add_done_callback(self._bot_tasks.discard) self._bot_tasks.add(task) async def _cleanup(self) -> None: """清理驱动器资源""" if self._bot_tasks: logger.opt(colors=True).debug( "<y>Waiting for running bot connection hooks...</y>" ) await asyncio.gather(*self._bot_tasks, return_exceptions=True) class Mixin(abc.ABC): """可与其他驱动器共用的混入基类。""" def type(self) -> str: """混入驱动类型名称""" raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `combine_driver` function. Write a Python function `def combine_driver( driver: Type[D], *mixins: Type[Mixin] ) -> Union[Type[D], Type["CombinedDriver"]]` to solve the following problem: 将一个驱动器和多个混入类合并。 Here is the function: def combine_driver( driver: Type[D], *mixins: Type[Mixin] ) -> Union[Type[D], Type["CombinedDriver"]]: """将一个驱动器和多个混入类合并。""" # check first if not issubclass(driver, Driver): raise TypeError("`driver` must be subclass of Driver") if not all(issubclass(m, Mixin) for m in mixins): raise TypeError("`mixins` must be subclass of Mixin") if not mixins: return driver def type_(self: "CombinedDriver") -> str: return ( driver.type.__get__(self) # type: ignore + "+" + "+".join(x.type.__get__(self) for x in mixins) # type: ignore ) return type( "CombinedDriver", (*mixins, driver), {"type": property(type_)} ) # type: ignore
将一个驱动器和多个混入类合并。
156,122
import sys import logging from typing import TYPE_CHECKING import loguru logger: "Logger" = loguru.logger The provided code snippet includes necessary dependencies for implementing the `default_filter` function. Write a Python function `def default_filter(record: "Record")` to solve the following problem: 默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。 Here is the function: def default_filter(record: "Record"): """默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。""" log_level = record["extra"].get("nonebot_log_level", "INFO") levelno = logger.level(log_level).no if isinstance(log_level, str) else log_level return record["level"].no >= levelno
默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。
156,123
from nonebot import on_command from nonebot.rule import to_me from nonebot.adapters import Message from nonebot.params import CommandArg from nonebot.plugin import PluginMetadata echo = on_command("echo", to_me()) def CommandArg() -> Any: """消息命令参数""" return Depends(_command_arg) async def handle_echo(message: Message = CommandArg()): if any((not seg.is_text()) or str(seg) for seg in message): await echo.send(message=message)
null
156,124
from typing import Dict, AsyncGenerator from nonebot.adapters import Event from nonebot.params import Depends from nonebot.plugin import PluginMetadata from nonebot.message import IgnoredException, event_preprocessor async def matcher_mutex(event: Event) -> AsyncGenerator[bool, None]: result = False try: session_id = event.get_session_id() except Exception: yield result else: current_event_id = id(event) if event_id := _running_matcher.get(session_id): result = event_id != current_event_id else: _running_matcher[session_id] = current_event_id yield result if not result: del _running_matcher[session_id] async def preprocess(mutex: bool = Depends(matcher_mutex)): if mutex: raise IgnoredException("Another matcher running")
null
156,125
import logging from functools import wraps from contextlib import asynccontextmanager from typing_extensions import ParamSpec, override from typing import TYPE_CHECKING, Union, TypeVar, Callable, Awaitable, AsyncGenerator from nonebot.drivers import Request from nonebot.log import LoguruHandler from nonebot.exception import WebSocketClosed from nonebot.drivers.none import Driver as NoneDriver from nonebot.drivers import WebSocket as BaseWebSocket from nonebot.drivers import WebSocketClientMixin, combine_driver T = TypeVar("T") P = ParamSpec("P") etClosed(DriverException): """WebSocket 连接已关闭。""" def __init__(self, code: int, reason: Optional[str] = None) -> None: self.code = code self.reason = reason def __repr__(self) -> str: return ( f"WebSocketClosed(code={self.code}" + (f", reason={self.reason!r}" if self.reason else "") + ")" ) def catch_closed(func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: @wraps(func) async def decorator(*args: P.args, **kwargs: P.kwargs) -> T: try: return await func(*args, **kwargs) except ConnectionClosed as e: raise WebSocketClosed(e.code, e.reason) return decorator
null
156,126
import logging import contextlib from functools import wraps from typing_extensions import override from typing import Any, Dict, List, Tuple, Union, Optional from pydantic import BaseModel from nonebot.config import Env from nonebot.drivers import ASGIMixin from nonebot.exception import WebSocketClosed from nonebot.internal.driver import FileTypes from nonebot.drivers import Driver as BaseDriver from nonebot.config import Config as NoneBotConfig from nonebot.drivers import Request as BaseRequest from nonebot.drivers import WebSocket as BaseWebSocket from nonebot.compat import model_dump, type_validate_python from nonebot.drivers import HTTPServerSetup, WebSocketServerSetup etClosed(DriverException): """WebSocket 连接已关闭。""" def __init__(self, code: int, reason: Optional[str] = None) -> None: self.code = code self.reason = reason def __repr__(self) -> str: return ( f"WebSocketClosed(code={self.code}" + (f", reason={self.reason!r}" if self.reason else "") + ")" ) def catch_closed(func): @wraps(func) async def decorator(*args, **kwargs): try: return await func(*args, **kwargs) except WebSocketDisconnect as e: raise WebSocketClosed(e.code) except KeyError: raise TypeError("WebSocket received unexpected frame type") return decorator
null
156,127
import asyncio from functools import wraps from typing_extensions import override from typing import Any, Dict, List, Tuple, Union, Optional, cast from pydantic import BaseModel from nonebot.config import Env from nonebot.drivers import ASGIMixin from nonebot.exception import WebSocketClosed from nonebot.internal.driver import FileTypes from nonebot.drivers import Driver as BaseDriver from nonebot.config import Config as NoneBotConfig from nonebot.drivers import Request as BaseRequest from nonebot.drivers import WebSocket as BaseWebSocket from nonebot.compat import model_dump, type_validate_python from nonebot.drivers import HTTPServerSetup, WebSocketServerSetup etClosed(DriverException): """WebSocket 连接已关闭。""" def __init__(self, code: int, reason: Optional[str] = None) -> None: def __repr__(self) -> str: def catch_closed(func): @wraps(func) async def decorator(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: raise WebSocketClosed(1000) return decorator
null
156,128
from pathlib import Path from fastapi.staticfiles import StaticFiles from nonebot.drivers.fastapi import Driver seDriver, ASGIMixin): """FastAPI 驱动框架。""" def __init__(self, env: Env, config: NoneBotConfig): super().__init__(env, config) self.fastapi_config: Config = type_validate_python(Config, model_dump(config)) self._server_app = FastAPI( lifespan=self._lifespan_manager, openapi_url=self.fastapi_config.fastapi_openapi_url, docs_url=self.fastapi_config.fastapi_docs_url, redoc_url=self.fastapi_config.fastapi_redoc_url, **self.fastapi_config.fastapi_extra, ) def type(self) -> str: """驱动名称: `fastapi`""" return "fastapi" def server_app(self) -> FastAPI: """`FastAPI APP` 对象""" return self._server_app def asgi(self) -> FastAPI: """`FastAPI APP` 对象""" return self._server_app def logger(self) -> logging.Logger: """fastapi 使用的 logger""" return logging.getLogger("fastapi") def setup_http_server(self, setup: HTTPServerSetup): async def _handle(request: Request) -> Response: return await self._handle_http(request, setup) self._server_app.add_api_route( setup.path.path, _handle, name=setup.name, methods=[setup.method], include_in_schema=self.fastapi_config.fastapi_include_adapter_schema, ) def setup_websocket_server(self, setup: WebSocketServerSetup) -> None: async def _handle(websocket: WebSocket) -> None: await self._handle_ws(websocket, setup) self._server_app.add_api_websocket_route( setup.path.path, _handle, name=setup.name, ) async def _lifespan_manager(self, app: FastAPI): await self._lifespan.startup() try: yield finally: await self._lifespan.shutdown() def run( self, host: Optional[str] = None, port: Optional[int] = None, *, app: Optional[str] = None, **kwargs, ): """使用 `uvicorn` 启动 FastAPI""" super().run(host, port, app=app, **kwargs) LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, "handlers": { "default": { "class": "nonebot.log.LoguruHandler", }, }, "loggers": { "uvicorn.error": {"handlers": ["default"], "level": "INFO"}, "uvicorn.access": { "handlers": ["default"], "level": "INFO", }, }, } uvicorn.run( app or self.server_app, # type: ignore host=host or str(self.config.host), port=port or self.config.port, reload=self.fastapi_config.fastapi_reload, reload_dirs=self.fastapi_config.fastapi_reload_dirs, reload_delay=self.fastapi_config.fastapi_reload_delay, reload_includes=self.fastapi_config.fastapi_reload_includes, reload_excludes=self.fastapi_config.fastapi_reload_excludes, log_config=LOGGING_CONFIG, **kwargs, ) async def _handle_http( self, request: Request, setup: HTTPServerSetup, ) -> Response: json: Any = None with contextlib.suppress(Exception): json = await request.json() data: Optional[dict] = None files: Optional[List[Tuple[str, FileTypes]]] = None with contextlib.suppress(Exception): form = await request.form() data = {} files = [] for key, value in form.multi_items(): if isinstance(value, UploadFile): files.append( (key, (value.filename, value.file, value.content_type)) ) else: data[key] = value http_request = BaseRequest( request.method, str(request.url), headers=request.headers.items(), cookies=request.cookies, content=await request.body(), data=data, json=json, files=files, version=request.scope["http_version"], ) response = await setup.handle_func(http_request) return Response( response.content, response.status_code, dict(response.headers.items()) ) async def _handle_ws(self, websocket: WebSocket, setup: WebSocketServerSetup): request = BaseRequest( "GET", str(websocket.url), headers=websocket.headers.items(), cookies=websocket.cookies, version=websocket.scope.get("http_version", "1.1"), ) ws = FastAPIWebSocket( request=request, websocket=websocket, ) await setup.handle_func(ws) def register_route(driver: Driver): app = driver.server_app static_path = str((Path(__file__).parent / ".." / "dist").resolve()) app.mount("/website", StaticFiles(directory=static_path, html=True), name="docs")
null
156,129
import os import pathlib import psutil import socket import sys import time from datetime import datetime, timedelta from plotmanager.library.parse.configuration import get_config_info from plotmanager.library.utilities.configuration import test_configuration from plotmanager.library.utilities.exceptions import ManagerError, TerminationException from plotmanager.library.utilities.jobs import load_jobs from plotmanager.library.utilities.log import analyze_log_dates, check_log_progress, analyze_log_times from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import print_view, print_json from plotmanager.library.utilities.processes import is_windows, get_manager_processes, get_running_plots, \ start_process, identify_drive, get_system_drives def get_config_info(): config = _get_config() chia_location = _get_chia_location(config=config) backend = _get_backend_settings(config=config) manager_check_interval, log_level = _get_manager_settings(config=config) log_directory = _get_log_settings(config=config) if not os.path.exists(log_directory): os.makedirs(log_directory) jobs = _get_jobs(config=config) max_concurrent, max_for_phase_1, minimum_minutes_between_jobs = _get_global_config(config=config) progress_settings = _get_progress_settings(config=config) notification_settings = _get_notifications_settings(config=config) view_settings = _get_view_settings(config=config) instrumentation_settings = _get_instrumentation_settings(config=config) return chia_location, log_directory, jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, log_level, view_settings, \ instrumentation_settings, backend def test_configuration(chia_location, notification_settings, instrumentation_settings): if not os.path.exists(chia_location): raise InvalidChiaLocationException('The chia_location in your config.yaml does not exist. Please confirm if ' 'you have the right version. Also confirm if you have a space after the ' 'colon. "chia_location: <DRIVE>" not "chia_location:<DRIVE>"') if notification_settings.get('notify_discord'): try: import discord_notify except ImportError: raise MissingImportError('Failed to find import "discord_notify". Be sure to run "pip install -r ' 'requirements-notification.txt".') if notification_settings.get('notify_sound'): try: import playsound except ImportError: raise MissingImportError('Failed to find import "playsound". Be sure to run "pip install -r ' 'requirements-notification.txt".') if notification_settings.get('notify_pushover'): try: import pushover except ImportError: raise MissingImportError('Failed to find import "pushover". Be sure to run "pip install -r ' 'requirements-notification.txt".') if instrumentation_settings.get('notify_telegram'): try: import telegram_notifier except ImportError: raise MissingImportError('Failed to find import "telegram_notifier". Be sure to run "pip install -r ' 'requirements-notification.txt".') if instrumentation_settings.get('notify_ifttt'): try: import requests except ImportError: raise MissingImportError('Failed to find import "requests". Be sure to run "pip install -r ' 'requirements-notification.txt".') if instrumentation_settings.get('prometheus_enabled'): try: import prometheus_client except ImportError: raise MissingImportError('Failed to find import "prometheus_client". Be sure to run "pip install -r ' 'requirements-notification.txt".') class ManagerError(Exception): pass def load_jobs(config_jobs): jobs = [] checked_job_names = [] checked_temporary_directories = [] for info in config_jobs: job = deepcopy(Job()) job.total_running = 0 job.name = info['name'] if job.name in checked_job_names: raise InvalidConfigurationSetting(f'Found the same job name for multiple jobs. Job names should be unique. ' f'Duplicate: {job.name}') checked_job_names.append(info['name']) job.max_plots = info['max_plots'] job.farmer_public_key = info.get('farmer_public_key', None) job.pool_public_key = info.get('pool_public_key', None) job.pool_contract_address = info.get('pool_contract_address', None) job.max_concurrent = info['max_concurrent'] job.max_concurrent_with_start_early = info['max_concurrent_with_start_early'] if job.max_concurrent_with_start_early < job.max_concurrent: raise InvalidConfigurationSetting('Your "max_concurrent_with_start_early" value must be greater than or ' 'equal to your "max_concurrent" value.') if (job.pool_contract_address and job.pool_public_key) is not None: raise InvalidConfigurationSetting('You cant use both "pool_contract_address" and "pool_public_key" at once ' 'You can only define one per job') job.max_for_phase_1 = info['max_for_phase_1'] job.initial_delay_minutes = info.get('initial_delay_minutes', 0) if not job.initial_delay_minutes: job.initial_delay_minutes = 0 job.stagger_minutes = info.get('stagger_minutes', None) job.max_for_phase_1 = info.get('max_for_phase_1', None) job.concurrency_start_early_phase = info.get('concurrency_start_early_phase', None) job.concurrency_start_early_phase_delay = info.get('concurrency_start_early_phase_delay', None) job.temporary2_destination_sync = info.get('temporary2_destination_sync', False) job.exclude_final_directory = info.get('exclude_final_directory', False) job.skip_full_destinations = info.get('skip_full_destinations', True) temporary_directory = info['temporary_directory'] if not isinstance(temporary_directory, list): temporary_directory = [temporary_directory] for directory in temporary_directory: if directory not in checked_temporary_directories: checked_temporary_directories.append(directory) continue raise InvalidConfigurationSetting(f'You cannot use the same temporary directory for more than one job: ' f'{directory}') job.temporary_directory = temporary_directory job.destination_directory = info['destination_directory'] temporary2_directory = info.get('temporary2_directory', None) if not temporary2_directory: temporary2_directory = None job.temporary2_directory = temporary2_directory job.size = info['size'] job.bitfield = info['bitfield'] job.threads = info['threads'] job.threadX_p2 = info.get('threadX_p2') job.buckets = info['buckets'] job.buckets_p3 = info.get('buckets_p3') job.memory_buffer = info['memory_buffer'] job.unix_process_priority = info.get('unix_process_priority', 10) if not -20 <= job.unix_process_priority <= 20: raise InvalidConfigurationSetting('UNIX Process Priority must be between -20 and 19.') job.windows_process_priority = info.get('windows_process_priority', 32) if job.windows_process_priority not in [64, 16384, 32, 32768, 128, 256]: raise InvalidConfigurationSetting('Windows Process Priority must any of the following: [64, 16384, 32, ' '32768, 128, 256]. Please view README for more details. If you don\'t ' 'know what you are doing, please use 32.') job.enable_cpu_affinity = info.get('enable_cpu_affinity', False) if job.enable_cpu_affinity: job.cpu_affinity = info['cpu_affinity'] jobs.append(job) return jobs def send_notifications(title, body, settings): try: _send_notifications(title=title, body=body, settings=settings) except: pass def get_manager_processes(): processes = [] for process in psutil.process_iter(): try: if not re.search(r'^pythonw?(?:\d+\.\d+|\d+)?(?:\.exe)?$', process.name(), flags=re.I): continue if not _contains_in_list('python', process.cmdline(), case_insensitive=True) or \ not _contains_in_list('stateless-manager.py', process.cmdline()): continue processes.append(process) except (psutil.NoSuchProcess, psutil.AccessDenied): pass return processes def is_windows(): return platform.system() == 'Windows' def start_process(args, log_file): kwargs = {} if is_windows(): flags = 0 flags |= 0x00000008 kwargs = { 'creationflags': flags, } process = subprocess.Popen( args=args, stdout=log_file, stderr=log_file, shell=False, **kwargs, ) return process def start_manager(): if get_manager_processes(): raise ManagerError('Manager is already running.') directory = pathlib.Path().resolve() stateless_manager_path = os.path.join(directory, 'stateless-manager.py') if not os.path.exists(stateless_manager_path): raise FileNotFoundError('Failed to find stateless-manager.') debug_log_file_path = os.path.join(directory, 'debug.log') debug_log_file = open(debug_log_file_path, 'a') python_file_path = sys.executable chia_location, log_directory, config_jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, debug_level, view_settings, \ instrumentation_settings, backend = get_config_info() load_jobs(config_jobs) test_configuration(chia_location=chia_location, notification_settings=notification_settings, instrumentation_settings=instrumentation_settings) extra_args = [] if is_windows(): pythonw_file_path = '\\'.join(python_file_path.split('\\')[:-1] + ['pythonw.exe']) else: pythonw_file_path = '\\'.join(python_file_path.split('\\')[:-1] + ['python &']) extra_args.append('&') if os.path.exists(pythonw_file_path): python_file_path = pythonw_file_path args = [python_file_path, stateless_manager_path] + extra_args start_process(args=args, log_file=debug_log_file) time.sleep(3) if not get_manager_processes(): raise ManagerError('Failed to start Manager. Please look at debug.log for more details on the error. It is in the same folder as manager.py.') send_notifications( title='Plot manager started', body=f'Plot Manager has started on {socket.gethostname()}...', settings=notification_settings, ) print('Plot Manager has started...')
null
156,130
import os import pathlib import psutil import socket import sys import time from datetime import datetime, timedelta from plotmanager.library.parse.configuration import get_config_info from plotmanager.library.utilities.configuration import test_configuration from plotmanager.library.utilities.exceptions import ManagerError, TerminationException from plotmanager.library.utilities.jobs import load_jobs from plotmanager.library.utilities.log import analyze_log_dates, check_log_progress, analyze_log_times from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import print_view, print_json from plotmanager.library.utilities.processes import is_windows, get_manager_processes, get_running_plots, \ start_process, identify_drive, get_system_drives class TerminationException(Exception): pass def get_manager_processes(): processes = [] for process in psutil.process_iter(): try: if not re.search(r'^pythonw?(?:\d+\.\d+|\d+)?(?:\.exe)?$', process.name(), flags=re.I): continue if not _contains_in_list('python', process.cmdline(), case_insensitive=True) or \ not _contains_in_list('stateless-manager.py', process.cmdline()): continue processes.append(process) except (psutil.NoSuchProcess, psutil.AccessDenied): pass return processes def stop_manager(): processes = get_manager_processes() if not processes: print("No manager processes were found.") return for process in processes: try: process.terminate() except psutil.NoSuchProcess: pass if get_manager_processes(): raise TerminationException("Failed to stop manager processes.") print("Successfully stopped manager processes.")
null
156,131
import os import pathlib import psutil import socket import sys import time from datetime import datetime, timedelta from plotmanager.library.parse.configuration import get_config_info from plotmanager.library.utilities.configuration import test_configuration from plotmanager.library.utilities.exceptions import ManagerError, TerminationException from plotmanager.library.utilities.jobs import load_jobs from plotmanager.library.utilities.log import analyze_log_dates, check_log_progress, analyze_log_times from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import print_view, print_json from plotmanager.library.utilities.processes import is_windows, get_manager_processes, get_running_plots, \ start_process, identify_drive, get_system_drives def get_config_info(): config = _get_config() chia_location = _get_chia_location(config=config) backend = _get_backend_settings(config=config) manager_check_interval, log_level = _get_manager_settings(config=config) log_directory = _get_log_settings(config=config) if not os.path.exists(log_directory): os.makedirs(log_directory) jobs = _get_jobs(config=config) max_concurrent, max_for_phase_1, minimum_minutes_between_jobs = _get_global_config(config=config) progress_settings = _get_progress_settings(config=config) notification_settings = _get_notifications_settings(config=config) view_settings = _get_view_settings(config=config) instrumentation_settings = _get_instrumentation_settings(config=config) return chia_location, log_directory, jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, log_level, view_settings, \ instrumentation_settings, backend def load_jobs(config_jobs): jobs = [] checked_job_names = [] checked_temporary_directories = [] for info in config_jobs: job = deepcopy(Job()) job.total_running = 0 job.name = info['name'] if job.name in checked_job_names: raise InvalidConfigurationSetting(f'Found the same job name for multiple jobs. Job names should be unique. ' f'Duplicate: {job.name}') checked_job_names.append(info['name']) job.max_plots = info['max_plots'] job.farmer_public_key = info.get('farmer_public_key', None) job.pool_public_key = info.get('pool_public_key', None) job.pool_contract_address = info.get('pool_contract_address', None) job.max_concurrent = info['max_concurrent'] job.max_concurrent_with_start_early = info['max_concurrent_with_start_early'] if job.max_concurrent_with_start_early < job.max_concurrent: raise InvalidConfigurationSetting('Your "max_concurrent_with_start_early" value must be greater than or ' 'equal to your "max_concurrent" value.') if (job.pool_contract_address and job.pool_public_key) is not None: raise InvalidConfigurationSetting('You cant use both "pool_contract_address" and "pool_public_key" at once ' 'You can only define one per job') job.max_for_phase_1 = info['max_for_phase_1'] job.initial_delay_minutes = info.get('initial_delay_minutes', 0) if not job.initial_delay_minutes: job.initial_delay_minutes = 0 job.stagger_minutes = info.get('stagger_minutes', None) job.max_for_phase_1 = info.get('max_for_phase_1', None) job.concurrency_start_early_phase = info.get('concurrency_start_early_phase', None) job.concurrency_start_early_phase_delay = info.get('concurrency_start_early_phase_delay', None) job.temporary2_destination_sync = info.get('temporary2_destination_sync', False) job.exclude_final_directory = info.get('exclude_final_directory', False) job.skip_full_destinations = info.get('skip_full_destinations', True) temporary_directory = info['temporary_directory'] if not isinstance(temporary_directory, list): temporary_directory = [temporary_directory] for directory in temporary_directory: if directory not in checked_temporary_directories: checked_temporary_directories.append(directory) continue raise InvalidConfigurationSetting(f'You cannot use the same temporary directory for more than one job: ' f'{directory}') job.temporary_directory = temporary_directory job.destination_directory = info['destination_directory'] temporary2_directory = info.get('temporary2_directory', None) if not temporary2_directory: temporary2_directory = None job.temporary2_directory = temporary2_directory job.size = info['size'] job.bitfield = info['bitfield'] job.threads = info['threads'] job.threadX_p2 = info.get('threadX_p2') job.buckets = info['buckets'] job.buckets_p3 = info.get('buckets_p3') job.memory_buffer = info['memory_buffer'] job.unix_process_priority = info.get('unix_process_priority', 10) if not -20 <= job.unix_process_priority <= 20: raise InvalidConfigurationSetting('UNIX Process Priority must be between -20 and 19.') job.windows_process_priority = info.get('windows_process_priority', 32) if job.windows_process_priority not in [64, 16384, 32, 32768, 128, 256]: raise InvalidConfigurationSetting('Windows Process Priority must any of the following: [64, 16384, 32, ' '32768, 128, 256]. Please view README for more details. If you don\'t ' 'know what you are doing, please use 32.') job.enable_cpu_affinity = info.get('enable_cpu_affinity', False) if job.enable_cpu_affinity: job.cpu_affinity = info['cpu_affinity'] jobs.append(job) return jobs def check_log_progress(jobs, running_work, progress_settings, notification_settings, view_settings, instrumentation_settings, backend): for pid, work in list(running_work.items()): logging.info(f'Checking log progress for PID: {pid}') if not work.log_file: continue f = open(work.log_file, 'r') data = f.read() f.close() line_count = (data.count('\n') + 1) progress = get_progress(line_count=line_count, progress_settings=progress_settings, backend=backend) phase_times, phase_dates = get_phase_info(data, view_settings, backend=backend, start_time=work.datetime_start) current_phase = 1 if phase_times: current_phase = max(phase_times.keys()) + 1 work.phase_times = phase_times work.phase_dates = phase_dates work.current_phase = current_phase work.progress = f'{progress:.2f}%' if psutil.pid_exists(pid) and 'renamed final file from ' not in data.lower(): logging.info(f'PID still alive: {pid}') continue logging.info(f'PID no longer alive: {pid}') for job in jobs: if not job or not work or not work.job: continue if job.name != work.job.name: continue logging.info(f'Removing PID {pid} from job: {job.name}') if pid in job.running_work: job.running_work.remove(pid) job.total_running -= 1 job.total_completed += 1 increment_plots_completed(increment=1, job_name=job.name, instrumentation_settings=instrumentation_settings) send_notifications( title='Plot Completed', body=f'You completed a plot on {socket.gethostname()}!', settings=notification_settings, ) break del running_work[pid] def print_json(jobs, running_work, view_settings, backend='chia'): get_job_data(jobs=jobs, running_work=running_work, view_settings=view_settings, as_json=True, backend=backend) def get_system_drives(): drives = [] for disk in psutil.disk_partitions(all=True): drive = disk.mountpoint if is_windows(): drive = os.path.splitdrive(drive)[0] drives.append(drive) drives.sort(reverse=True) return drives def identify_drive(file_path, drives): if not file_path: return None for drive in drives: if drive not in file_path: continue return drive return None def get_running_plots(jobs, running_work, instrumentation_settings, backend='chia'): chia_processes = [] logging.info(f'Getting running plots') chia_executable_name = get_chia_executable_name(backend) for process in psutil.process_iter(): try: if chia_executable_name not in process.name() and 'python' not in process.name().lower(): continue except (psutil.AccessDenied, psutil.NoSuchProcess): continue try: if (('plots' not in process.cmdline() or 'create' not in process.cmdline()) and backend == 'chia') or\ (('python' in process.name() or 'zombie' in process.status()) and backend == 'madmax'): continue except (psutil.ZombieProcess, psutil.NoSuchProcess): continue if process.parent(): try: parent_commands = process.parent().cmdline() if 'plots' in parent_commands and 'create' in parent_commands: continue except (psutil.AccessDenied, psutil.ZombieProcess): pass logging.info(f'Found chia plotting process: {process.pid}') datetime_start = datetime.fromtimestamp(process.create_time()) chia_processes.append([datetime_start, process]) chia_processes.sort(key=lambda x: (x[0])) for datetime_start, process in chia_processes: logging.info(f'Finding log file for process: {process.pid}') log_file_path = None commands = [] try: commands = process.cmdline() for file in process.open_files(): if '.mui' == file.path[-4:]: continue if file.path[-4:] not in ['.log', '.txt']: continue if file.path[-9:] == 'debug.log': continue log_file_path = file.path logging.info(f'Found log file: {log_file_path}') break except (psutil.AccessDenied, RuntimeError): logging.info(f'Failed to find log file: {process.pid}') except psutil.NoSuchProcess: continue assumed_job = None logging.info(f'Finding associated job') temporary_directory, temporary2_directory, destination_directory = get_plot_directories(commands=commands) for job in jobs: if isinstance(job.temporary_directory, list) and temporary_directory not in job.temporary_directory: continue if not isinstance(job.temporary_directory, list) and temporary_directory != job.temporary_directory: continue logging.info(f'Found job: {job.name}') assumed_job = job break plot_id = None if log_file_path: plot_id = get_plot_id(file_path=log_file_path, backend=backend) temp_file_size = get_temp_size(plot_id=plot_id, temporary_directory=temporary_directory, temporary2_directory=temporary2_directory) temporary_drive, temporary2_drive, destination_drive = get_plot_drives(commands=commands) k_size = get_plot_k_size(commands=commands, backend=backend) work = deepcopy(Work()) work.job = assumed_job work.log_file = log_file_path work.datetime_start = datetime_start work.pid = process.pid work.plot_id = plot_id work.work_id = '?' if assumed_job: work.work_id = assumed_job.current_work_id assumed_job.current_work_id += 1 assumed_job.total_running += 1 set_plots_running(total_running_plots=assumed_job.total_running, job_name=assumed_job.name, instrumentation_settings=instrumentation_settings) assumed_job.running_work = assumed_job.running_work + [process.pid] work.temporary_drive = temporary_drive work.temporary2_drive = temporary2_drive work.destination_drive = destination_drive work.temp_file_size = temp_file_size work.k_size = k_size running_work[work.pid] = work logging.info(f'Finished finding running plots') return jobs, running_work def json_output(): chia_location, log_directory, config_jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, debug_level, view_settings, \ instrumentation_settings, backend = get_config_info() system_drives = get_system_drives() drives = {'temp': [], 'temp2': [], 'dest': []} jobs = load_jobs(config_jobs) for job in jobs: directories = { 'temp': job.temporary_directory, 'dest': job.destination_directory, 'temp2': job.temporary2_directory, } for key, directory_list in directories.items(): if directory_list is None: continue if not isinstance(directory_list, list): directory_list = [directory_list] for directory in directory_list: drive = identify_drive(file_path=directory, drives=system_drives) if drive in drives[key]: continue drives[key].append(drive) running_work = {} jobs = load_jobs(config_jobs) jobs, running_work = get_running_plots(jobs=jobs, running_work=running_work, instrumentation_settings=instrumentation_settings, backend=backend) check_log_progress(jobs=jobs, running_work=running_work, progress_settings=progress_settings, notification_settings=notification_settings, view_settings=view_settings, instrumentation_settings=instrumentation_settings, backend=backend) print_json(jobs=jobs, running_work=running_work, view_settings=view_settings, backend=backend) has_file = False if len(running_work.values()) == 0: has_file = True for work in running_work.values(): if not work.log_file: continue has_file = True break if not has_file: print("Restarting view due to psutil going stale...") system_args = [f'"{sys.executable}"'] + sys.argv os.execv(sys.executable, system_args) exit()
null
156,132
import os import pathlib import psutil import socket import sys import time from datetime import datetime, timedelta from plotmanager.library.parse.configuration import get_config_info from plotmanager.library.utilities.configuration import test_configuration from plotmanager.library.utilities.exceptions import ManagerError, TerminationException from plotmanager.library.utilities.jobs import load_jobs from plotmanager.library.utilities.log import analyze_log_dates, check_log_progress, analyze_log_times from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import print_view, print_json from plotmanager.library.utilities.processes import is_windows, get_manager_processes, get_running_plots, \ start_process, identify_drive, get_system_drives def get_config_info(): config = _get_config() chia_location = _get_chia_location(config=config) backend = _get_backend_settings(config=config) manager_check_interval, log_level = _get_manager_settings(config=config) log_directory = _get_log_settings(config=config) if not os.path.exists(log_directory): os.makedirs(log_directory) jobs = _get_jobs(config=config) max_concurrent, max_for_phase_1, minimum_minutes_between_jobs = _get_global_config(config=config) progress_settings = _get_progress_settings(config=config) notification_settings = _get_notifications_settings(config=config) view_settings = _get_view_settings(config=config) instrumentation_settings = _get_instrumentation_settings(config=config) return chia_location, log_directory, jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, log_level, view_settings, \ instrumentation_settings, backend def load_jobs(config_jobs): jobs = [] checked_job_names = [] checked_temporary_directories = [] for info in config_jobs: job = deepcopy(Job()) job.total_running = 0 job.name = info['name'] if job.name in checked_job_names: raise InvalidConfigurationSetting(f'Found the same job name for multiple jobs. Job names should be unique. ' f'Duplicate: {job.name}') checked_job_names.append(info['name']) job.max_plots = info['max_plots'] job.farmer_public_key = info.get('farmer_public_key', None) job.pool_public_key = info.get('pool_public_key', None) job.pool_contract_address = info.get('pool_contract_address', None) job.max_concurrent = info['max_concurrent'] job.max_concurrent_with_start_early = info['max_concurrent_with_start_early'] if job.max_concurrent_with_start_early < job.max_concurrent: raise InvalidConfigurationSetting('Your "max_concurrent_with_start_early" value must be greater than or ' 'equal to your "max_concurrent" value.') if (job.pool_contract_address and job.pool_public_key) is not None: raise InvalidConfigurationSetting('You cant use both "pool_contract_address" and "pool_public_key" at once ' 'You can only define one per job') job.max_for_phase_1 = info['max_for_phase_1'] job.initial_delay_minutes = info.get('initial_delay_minutes', 0) if not job.initial_delay_minutes: job.initial_delay_minutes = 0 job.stagger_minutes = info.get('stagger_minutes', None) job.max_for_phase_1 = info.get('max_for_phase_1', None) job.concurrency_start_early_phase = info.get('concurrency_start_early_phase', None) job.concurrency_start_early_phase_delay = info.get('concurrency_start_early_phase_delay', None) job.temporary2_destination_sync = info.get('temporary2_destination_sync', False) job.exclude_final_directory = info.get('exclude_final_directory', False) job.skip_full_destinations = info.get('skip_full_destinations', True) temporary_directory = info['temporary_directory'] if not isinstance(temporary_directory, list): temporary_directory = [temporary_directory] for directory in temporary_directory: if directory not in checked_temporary_directories: checked_temporary_directories.append(directory) continue raise InvalidConfigurationSetting(f'You cannot use the same temporary directory for more than one job: ' f'{directory}') job.temporary_directory = temporary_directory job.destination_directory = info['destination_directory'] temporary2_directory = info.get('temporary2_directory', None) if not temporary2_directory: temporary2_directory = None job.temporary2_directory = temporary2_directory job.size = info['size'] job.bitfield = info['bitfield'] job.threads = info['threads'] job.threadX_p2 = info.get('threadX_p2') job.buckets = info['buckets'] job.buckets_p3 = info.get('buckets_p3') job.memory_buffer = info['memory_buffer'] job.unix_process_priority = info.get('unix_process_priority', 10) if not -20 <= job.unix_process_priority <= 20: raise InvalidConfigurationSetting('UNIX Process Priority must be between -20 and 19.') job.windows_process_priority = info.get('windows_process_priority', 32) if job.windows_process_priority not in [64, 16384, 32, 32768, 128, 256]: raise InvalidConfigurationSetting('Windows Process Priority must any of the following: [64, 16384, 32, ' '32768, 128, 256]. Please view README for more details. If you don\'t ' 'know what you are doing, please use 32.') job.enable_cpu_affinity = info.get('enable_cpu_affinity', False) if job.enable_cpu_affinity: job.cpu_affinity = info['cpu_affinity'] jobs.append(job) return jobs def analyze_log_dates(log_directory, analysis): files = get_completed_log_files(log_directory, skip=list(analysis['files'].keys())) for file_path, contents in files.items(): data = _analyze_log_end_date(contents, file_path) if data is None: continue analysis['files'][file_path] = {'data': data, 'checked': False} analysis = _get_date_summary(analysis) return analysis def check_log_progress(jobs, running_work, progress_settings, notification_settings, view_settings, instrumentation_settings, backend): for pid, work in list(running_work.items()): logging.info(f'Checking log progress for PID: {pid}') if not work.log_file: continue f = open(work.log_file, 'r') data = f.read() f.close() line_count = (data.count('\n') + 1) progress = get_progress(line_count=line_count, progress_settings=progress_settings, backend=backend) phase_times, phase_dates = get_phase_info(data, view_settings, backend=backend, start_time=work.datetime_start) current_phase = 1 if phase_times: current_phase = max(phase_times.keys()) + 1 work.phase_times = phase_times work.phase_dates = phase_dates work.current_phase = current_phase work.progress = f'{progress:.2f}%' if psutil.pid_exists(pid) and 'renamed final file from ' not in data.lower(): logging.info(f'PID still alive: {pid}') continue logging.info(f'PID no longer alive: {pid}') for job in jobs: if not job or not work or not work.job: continue if job.name != work.job.name: continue logging.info(f'Removing PID {pid} from job: {job.name}') if pid in job.running_work: job.running_work.remove(pid) job.total_running -= 1 job.total_completed += 1 increment_plots_completed(increment=1, job_name=job.name, instrumentation_settings=instrumentation_settings) send_notifications( title='Plot Completed', body=f'You completed a plot on {socket.gethostname()}!', settings=notification_settings, ) break del running_work[pid] def print_view(jobs, running_work, analysis, drives, next_log_check, view_settings, loop, backend): # Job Table job_data = get_job_data(jobs=jobs, running_work=running_work, view_settings=view_settings, backend=backend) # Drive Table drive_data = '' if view_settings.get('include_drive_info'): drive_data = get_drive_data(drives, running_work, job_data) manager_processes = get_manager_processes() if os.name == 'nt': os.system('cls') else: os.system('clear') print(pretty_print_job_data(job_data)) print(f'Manager Status: {"Running" if manager_processes else "Stopped"}') print() if view_settings.get('include_drive_info'): print(drive_data) if view_settings.get('include_cpu'): print(f'CPU Usage: {psutil.cpu_percent()}%') if view_settings.get('include_ram'): ram_usage = psutil.virtual_memory() print(f'RAM Usage: {pretty_print_bytes(ram_usage.used, "gb")}/{pretty_print_bytes(ram_usage.total, "gb", 2, "GiB")}' f'({ram_usage.percent}%)') print() if view_settings.get('include_plot_stats'): print(f'Plots Completed Yesterday: {analysis["summary"].get(datetime.now().date() - timedelta(days=1), 0)}') print(f'Plots Completed Today: {analysis["summary"].get(datetime.now().date(), 0)}') print() if loop: print(f"Next log check at {next_log_check.strftime('%Y-%m-%d %H:%M:%S')}") print() def get_system_drives(): drives = [] for disk in psutil.disk_partitions(all=True): drive = disk.mountpoint if is_windows(): drive = os.path.splitdrive(drive)[0] drives.append(drive) drives.sort(reverse=True) return drives def identify_drive(file_path, drives): if not file_path: return None for drive in drives: if drive not in file_path: continue return drive return None def get_running_plots(jobs, running_work, instrumentation_settings, backend='chia'): chia_processes = [] logging.info(f'Getting running plots') chia_executable_name = get_chia_executable_name(backend) for process in psutil.process_iter(): try: if chia_executable_name not in process.name() and 'python' not in process.name().lower(): continue except (psutil.AccessDenied, psutil.NoSuchProcess): continue try: if (('plots' not in process.cmdline() or 'create' not in process.cmdline()) and backend == 'chia') or\ (('python' in process.name() or 'zombie' in process.status()) and backend == 'madmax'): continue except (psutil.ZombieProcess, psutil.NoSuchProcess): continue if process.parent(): try: parent_commands = process.parent().cmdline() if 'plots' in parent_commands and 'create' in parent_commands: continue except (psutil.AccessDenied, psutil.ZombieProcess): pass logging.info(f'Found chia plotting process: {process.pid}') datetime_start = datetime.fromtimestamp(process.create_time()) chia_processes.append([datetime_start, process]) chia_processes.sort(key=lambda x: (x[0])) for datetime_start, process in chia_processes: logging.info(f'Finding log file for process: {process.pid}') log_file_path = None commands = [] try: commands = process.cmdline() for file in process.open_files(): if '.mui' == file.path[-4:]: continue if file.path[-4:] not in ['.log', '.txt']: continue if file.path[-9:] == 'debug.log': continue log_file_path = file.path logging.info(f'Found log file: {log_file_path}') break except (psutil.AccessDenied, RuntimeError): logging.info(f'Failed to find log file: {process.pid}') except psutil.NoSuchProcess: continue assumed_job = None logging.info(f'Finding associated job') temporary_directory, temporary2_directory, destination_directory = get_plot_directories(commands=commands) for job in jobs: if isinstance(job.temporary_directory, list) and temporary_directory not in job.temporary_directory: continue if not isinstance(job.temporary_directory, list) and temporary_directory != job.temporary_directory: continue logging.info(f'Found job: {job.name}') assumed_job = job break plot_id = None if log_file_path: plot_id = get_plot_id(file_path=log_file_path, backend=backend) temp_file_size = get_temp_size(plot_id=plot_id, temporary_directory=temporary_directory, temporary2_directory=temporary2_directory) temporary_drive, temporary2_drive, destination_drive = get_plot_drives(commands=commands) k_size = get_plot_k_size(commands=commands, backend=backend) work = deepcopy(Work()) work.job = assumed_job work.log_file = log_file_path work.datetime_start = datetime_start work.pid = process.pid work.plot_id = plot_id work.work_id = '?' if assumed_job: work.work_id = assumed_job.current_work_id assumed_job.current_work_id += 1 assumed_job.total_running += 1 set_plots_running(total_running_plots=assumed_job.total_running, job_name=assumed_job.name, instrumentation_settings=instrumentation_settings) assumed_job.running_work = assumed_job.running_work + [process.pid] work.temporary_drive = temporary_drive work.temporary2_drive = temporary2_drive work.destination_drive = destination_drive work.temp_file_size = temp_file_size work.k_size = k_size running_work[work.pid] = work logging.info(f'Finished finding running plots') return jobs, running_work def view(loop=True): chia_location, log_directory, config_jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, debug_level, view_settings, \ instrumentation_settings, backend = get_config_info() view_check_interval = view_settings['check_interval'] system_drives = get_system_drives() analysis = {'files': {}} drives = {'temp': [], 'temp2': [], 'dest': []} jobs = load_jobs(config_jobs) for job in jobs: directories = { 'dest': job.destination_directory, 'temp': job.temporary_directory, 'temp2': job.temporary2_directory, } for key, directory_list in directories.items(): if directory_list is None: continue if not isinstance(directory_list, list): directory_list = [directory_list] for directory in directory_list: drive = identify_drive(file_path=directory, drives=system_drives) if drive in drives[key]: continue drives[key].append(drive) while True: running_work = {} try: analysis = analyze_log_dates(log_directory=log_directory, analysis=analysis) jobs = load_jobs(config_jobs) jobs, running_work = get_running_plots(jobs=jobs, running_work=running_work, instrumentation_settings=instrumentation_settings, backend=backend) check_log_progress(jobs=jobs, running_work=running_work, progress_settings=progress_settings, notification_settings=notification_settings, view_settings=view_settings, instrumentation_settings=instrumentation_settings, backend=backend) print_view(jobs=jobs, running_work=running_work, analysis=analysis, drives=drives, next_log_check=datetime.now() + timedelta(seconds=view_check_interval), view_settings=view_settings, loop=loop, backend=backend) if not loop: break time.sleep(view_check_interval) has_file = False if len(running_work.values()) == 0: has_file = True for work in running_work.values(): if not work.log_file: continue has_file = True break if not has_file: print("Restarting view due to psutil going stale...") system_args = ['python'] + sys.argv os.execv(sys.executable, system_args) except KeyboardInterrupt: print("Stopped view.") exit()
null
156,133
import os import pathlib import psutil import socket import sys import time from datetime import datetime, timedelta from plotmanager.library.parse.configuration import get_config_info from plotmanager.library.utilities.configuration import test_configuration from plotmanager.library.utilities.exceptions import ManagerError, TerminationException from plotmanager.library.utilities.jobs import load_jobs from plotmanager.library.utilities.log import analyze_log_dates, check_log_progress, analyze_log_times from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import print_view, print_json from plotmanager.library.utilities.processes import is_windows, get_manager_processes, get_running_plots, \ start_process, identify_drive, get_system_drives def get_config_info(): config = _get_config() chia_location = _get_chia_location(config=config) backend = _get_backend_settings(config=config) manager_check_interval, log_level = _get_manager_settings(config=config) log_directory = _get_log_settings(config=config) if not os.path.exists(log_directory): os.makedirs(log_directory) jobs = _get_jobs(config=config) max_concurrent, max_for_phase_1, minimum_minutes_between_jobs = _get_global_config(config=config) progress_settings = _get_progress_settings(config=config) notification_settings = _get_notifications_settings(config=config) view_settings = _get_view_settings(config=config) instrumentation_settings = _get_instrumentation_settings(config=config) return chia_location, log_directory, jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, log_level, view_settings, \ instrumentation_settings, backend def analyze_log_times(log_directory, backend): total_times = {1: 0, 2: 0, 3: 0, 4: 0} line_numbers = {1: [], 2: [], 3: [], 4: []} count = 0 files = get_completed_log_files(log_directory) for file_path, contents in files.items(): count += 1 start_time_raw = os.path.getctime(file_path) start_time = datetime.fromtimestamp(start_time_raw) phase_times, phase_dates = get_phase_info(contents, pretty_print=False, backend=backend, start_time=start_time) for phase, seconds in phase_times.items(): total_times[phase] += seconds splits = _get_log_splits_for_backend(backend, contents) phase = 0 new_lines = 1 for split in splits: phase += 1 if phase >= 5: break new_lines += split.count('\n') line_numbers[phase].append(new_lines) for phase in range(1, 5): print(f' phase{phase}_line_end: {int(round(sum(line_numbers[phase]) / len(line_numbers[phase]), 0))}') for phase in range(1, 5): print(f' phase{phase}_weight: {round(total_times[phase] / sum(total_times.values()) * 100, 2)}') def analyze_logs(): chia_location, log_directory, config_jobs, manager_check_interval, max_concurrent, max_for_phase_1, \ minimum_minutes_between_jobs, progress_settings, notification_settings, debug_level, view_settings, \ instrumentation_settings, backend = get_config_info() analyze_log_times(log_directory, backend)
null
156,134
import logging import os import platform import psutil import re import subprocess from copy import deepcopy from datetime import datetime from plotmanager.library.utilities.objects import Work from plotmanager.library.utilities.instrumentation import set_plots_running def get_chia_executable_name(backend): executable_name_parsers = dict( chia=_get_chia_backend_executable_name, madmax=_get_madmax_backend_executable_name, ) return executable_name_parsers.get(backend)() def get_plot_drives(commands, drives=None): if not drives: drives = get_system_drives() temporary_directory, temporary2_directory, destination_directory = get_plot_directories(commands=commands) temporary_drive = identify_drive(file_path=temporary_directory, drives=drives) destination_drive = identify_drive(file_path=destination_directory, drives=drives) temporary2_drive = None if temporary2_directory: temporary2_drive = identify_drive(file_path=temporary2_directory, drives=drives) return temporary_drive, temporary2_drive, destination_drive def get_chia_drives(): drive_stats = {'temp': {}, 'temp2': {}, 'dest': {}} chia_executable_name = get_chia_executable_name() for process in psutil.process_iter(): try: if chia_executable_name not in process.name() and 'python' not in process.name().lower(): continue except (psutil.AccessDenied, psutil.NoSuchProcess): continue try: if 'plots' not in process.cmdline() or 'create' not in process.cmdline(): continue except (psutil.ZombieProcess, psutil.NoSuchProcess): continue commands = process.cmdline() temporary_drive, temporary2_drive, destination_drive = get_plot_drives(commands=commands) if not temporary_drive and not destination_drive: continue if temporary_drive not in drive_stats['temp']: drive_stats['temp'][temporary_drive] = 0 drive_stats['temp'][temporary_drive] += 1 if destination_drive not in drive_stats['dest']: drive_stats['dest'][destination_drive] = 0 drive_stats['dest'][destination_drive] += 1 if temporary2_drive: if temporary2_drive not in drive_stats['temp2']: drive_stats['temp2'][temporary2_drive] = 0 drive_stats['temp2'][temporary2_drive] += 1 return drive_stats
null
156,135
import logging import psutil from copy import deepcopy from datetime import datetime, timedelta from plotmanager.library.commands import plots from plotmanager.library.utilities.exceptions import InvalidConfigurationSetting from plotmanager.library.utilities.processes import identify_drive, is_windows, start_process from plotmanager.library.utilities.objects import Job, Work from plotmanager.library.utilities.log import get_log_file_name def has_active_jobs_and_work(jobs): for job in jobs: if job.total_kicked_off < job.max_plots: return True return False
null
156,136
import logging import psutil from copy import deepcopy from datetime import datetime, timedelta from plotmanager.library.commands import plots from plotmanager.library.utilities.exceptions import InvalidConfigurationSetting from plotmanager.library.utilities.processes import identify_drive, is_windows, start_process from plotmanager.library.utilities.objects import Job, Work from plotmanager.library.utilities.log import get_log_file_name def get_drives_free_space(jobs, system_drives, running_work): drives_free_space = {} for job in jobs: directories = [job.destination_directory] if isinstance(job.destination_directory, list): directories = job.destination_directory for directory in directories: drive = identify_drive(file_path=directory, drives=system_drives) if drive in drives_free_space: continue try: free_space = psutil.disk_usage(drive).free except: logging.exception(f"Failed to get disk_usage of drive {drive}.") # I need to do this because if Manager fails, I don't want it to break. free_space = None drives_free_space[drive] = free_space logging.info(f'Free space before checking active jobs: {drives_free_space}') for pid, work in running_work.items(): drive = work.destination_drive if drive[-1] == '/' or drive[-1] == '\\': drive = drive[:-1] if drive in drives_free_space.keys(): if drives_free_space[drive] is None: continue else: continue work_size = determine_job_size(work.k_size) drives_free_space[drive] -= work_size logging.info(drive) logging.info(f'Free space after checking active jobs: {drives_free_space}') return drives_free_space def start_work(job, chia_location, log_directory, drives_free_space, backend): logging.info(f'Starting new plot for job: {job.name}') nice_val = job.unix_process_priority if is_windows(): nice_val = job.windows_process_priority now = datetime.now() log_file_path = get_log_file_name(log_directory, job, now) logging.info(f'Job log file path: {log_file_path}') destination_directory, temporary_directory, temporary2_directory, job = \ get_target_directories(job, drives_free_space=drives_free_space) if not destination_directory: return job, None logging.info(f'Job temporary directory: {temporary_directory}') logging.info(f'Job destination directory: {destination_directory}') work = deepcopy(Work()) work.job = job work.log_file = log_file_path work.datetime_start = now work.work_id = job.current_work_id work.k_size = job.size work.destination_drive = destination_directory job.current_work_id += 1 if job.temporary2_destination_sync: logging.info(f'Job temporary2 and destination sync') temporary2_directory = destination_directory logging.info(f'Job temporary2 directory: {temporary2_directory}') plot_command = plots.create( chia_location=chia_location, farmer_public_key=job.farmer_public_key, pool_public_key=job.pool_public_key, pool_contract_address=job.pool_contract_address, size=job.size, memory_buffer=job.memory_buffer, temporary_directory=temporary_directory, temporary2_directory=temporary2_directory, destination_directory=destination_directory, threads=job.threads, threadX_p2=job.threadX_p2, buckets=job.buckets, buckets_p3=job.buckets_p3, bitfield=job.bitfield, exclude_final_directory=job.exclude_final_directory, backend=backend, ) logging.info(f'Starting with plot command: {plot_command}') log_file = open(log_file_path, 'a') logging.info(f'Starting process') process = start_process(args=plot_command, log_file=log_file) pid = process.pid logging.info(f'Started process: {pid}') logging.info(f'Setting priority level: {nice_val}') psutil.Process(pid).nice(nice_val) logging.info(f'Set priority level') if job.enable_cpu_affinity: logging.info(f'Setting process cpu affinity: {job.cpu_affinity}') psutil.Process(pid).cpu_affinity(job.cpu_affinity) logging.info(f'Set process cpu affinity') work.pid = pid job.total_running += 1 job.total_kicked_off += 1 job.running_work = job.running_work + [pid] logging.info(f'Job total running: {job.total_running}') logging.info(f'Job running: {job.running_work}') return job, work def monitor_jobs_to_start(jobs, running_work, max_concurrent, max_for_phase_1, next_job_work, chia_location, log_directory, next_log_check, minimum_minutes_between_jobs, system_drives, backend): total_phase_1_count = 0 for pid in running_work.keys(): if running_work[pid].current_phase > 1: continue total_phase_1_count += 1 for i, job in enumerate(jobs): drives_free_space = get_drives_free_space(jobs, system_drives, running_work) logging.info(f'Checking to queue work for job: {job.name}') if len(running_work.values()) >= max_concurrent: logging.info(f'Global concurrent limit met, skipping. Running plots: {len(running_work.values())}, ' f'Max global concurrent limit: {max_concurrent}') continue if total_phase_1_count >= max_for_phase_1: logging.info(f'Global max for phase 1 limit has been met, skipping. Count: {total_phase_1_count}, ' f'Setting Max: {max_for_phase_1}') continue phase_1_count = 0 for pid in job.running_work: if running_work[pid].current_phase > 1: continue phase_1_count += 1 logging.info(f'Total jobs in phase 1: {phase_1_count}') if job.max_for_phase_1 and phase_1_count >= job.max_for_phase_1: logging.info(f'Job max for phase 1 met, skipping. Max: {job.max_for_phase_1}') continue if job.total_kicked_off >= job.max_plots: logging.info(f'Job\'s total kicked off greater than or equal to max plots, skipping. Total Kicked Off: ' f'{job.total_kicked_off}, Max Plots: {job.max_plots}') continue if job.name in next_job_work and next_job_work[job.name] > datetime.now(): logging.info(f'Waiting for job stagger, skipping. Next allowable time: {next_job_work[job.name]}') continue discount_running = 0 if job.concurrency_start_early_phase is not None: for pid in job.running_work: work = running_work[pid] try: start_early_date = work.phase_dates[job.concurrency_start_early_phase - 1] except (KeyError, AttributeError): start_early_date = work.datetime_start if work.current_phase < job.concurrency_start_early_phase: continue if datetime.now() <= (start_early_date + timedelta(minutes=job.concurrency_start_early_phase_delay)): continue discount_running += 1 if (job.total_running - discount_running) >= job.max_concurrent: logging.info(f'Job\'s max concurrent limit has been met, skipping. Max concurrent minus start_early: ' f'{job.total_running - discount_running}, Max concurrent: {job.max_concurrent}') continue if job.total_running >= job.max_concurrent_with_start_early: logging.info( f'Job\'s max concurrnet limit with start early has been met, skipping. Max: {job.max_concurrent_with_start_early}') continue if job.stagger_minutes: next_job_work[job.name] = datetime.now() + timedelta(minutes=job.stagger_minutes) logging.info(f'Calculating new job stagger time. Next stagger kickoff: {next_job_work[job.name]}') if minimum_minutes_between_jobs: logging.info(f'Setting a minimum stagger for all jobs. {minimum_minutes_between_jobs}') minimum_stagger = datetime.now() + timedelta(minutes=minimum_minutes_between_jobs) for j in jobs: if next_job_work[j.name] > minimum_stagger: logging.info(f'Skipping stagger for {j.name}. Stagger is larger than minimum_minutes_between_jobs. ' f'Min: {minimum_stagger}, Current: {next_job_work[j.name]}') continue logging.info( f'Setting a new stagger for {j.name}. minimum_minutes_between_jobs is larger than assigned ' f'stagger. Min: {minimum_stagger}, Current: {next_job_work[j.name]}') next_job_work[j.name] = minimum_stagger job, work = start_work( job=job, chia_location=chia_location, log_directory=log_directory, drives_free_space=drives_free_space, backend=backend, ) jobs[i] = deepcopy(job) if work is None: continue total_phase_1_count += 1 next_log_check = datetime.now() running_work[work.pid] = work return jobs, running_work, next_job_work, next_log_check
null
156,137
import dateparser import logging import os import psutil import re import socket import time from plotmanager.library.utilities.instrumentation import increment_plots_completed from plotmanager.library.utilities.notifications import send_notifications from plotmanager.library.utilities.print import pretty_print_time from datetime import timedelta, datetime def _get_regex(pattern, string, flags=re.I): return re.search(pattern, string, flags=flags).groups()
null
156,138
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) def get_package_metadata(): metadata = {} with open(os.path.join(here, "../__packaging__.py")) as f: exec(f.read(), metadata) return SimpleNamespace(**metadata)
null
156,139
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) def get_relative_path(path): return os.path.join(here, os.path.pardir, path)
null
156,140
import os from types import SimpleNamespace from setuptools import find_packages, setup root = os.path.abspath(os.path.join(here, "../../")) def get_long_description(): readme_path = os.path.join(root, "README.md") with open(readme_path, "r", encoding="utf-8") as fh: return fh.read()
null
156,141
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) The provided code snippet includes necessary dependencies for implementing the `get_install_requires` function. Write a Python function `def get_install_requires()` to solve the following problem: Gets the contents of install_requires from text file. Getting the minimum requirements from a text file allows us to pre-install them in docker, speeding up our docker builds and better utilizing the docker layer cache. The requirements in requires.txt are in fact the minimum set of packages you need to run OPAL (and are thus different from a "requirements.txt" file). Here is the function: def get_install_requires(): """Gets the contents of install_requires from text file. Getting the minimum requirements from a text file allows us to pre-install them in docker, speeding up our docker builds and better utilizing the docker layer cache. The requirements in requires.txt are in fact the minimum set of packages you need to run OPAL (and are thus different from a "requirements.txt" file). """ with open(os.path.join(here, "requires.txt")) as fp: return [ line.strip() for line in fp.read().splitlines() if not line.startswith("#") ]
Gets the contents of install_requires from text file. Getting the minimum requirements from a text file allows us to pre-install them in docker, speeding up our docker builds and better utilizing the docker layer cache. The requirements in requires.txt are in fact the minimum set of packages you need to run OPAL (and are thus different from a "requirements.txt" file).
156,142
from typing import Callable, Dict, List import click import typer from typer.main import Typer from .types import ConfiEntry def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kwargs() # make the key fit cmd-style (i.e. kebab-case) adjusted_key = entry.key.lower().replace("_", "-") keys = [f"--{adjusted_key}", entry.key] # add flag if given (i.e '-t' option) if entry.flags is not None: keys.extend(entry.flags) # use lower case as the key, and as is (no prefix, and no case altering) as the name # see https://click.palletsprojects.com/en/7.x/options/#name-your-options cli = click.option(*keys, **option_kwargs)(cli) # pass context cli = click.pass_context(cli) # wrap in group cli = click.group(invoke_without_command=True)(cli) return cli def get_cli_object_for_config_objects( config_objects: list, typer_app: Typer = None, help: str = None, on_start: Callable = None, ): # callback to save CLI results back to objects def callback(ctx, **kwargs): if callable(on_start): on_start(ctx, **kwargs) for key, value in kwargs.items(): # find the confi-object which the key belongs to and ... for config_obj in config_objects: if key in config_obj.entries: # ... update that object with the new value setattr(config_obj, key, value) config_obj._entries[key].value = value if help is not None: callback.__doc__ = help # Create a merged config-entires map entries = {} for config_obj in config_objects: entries.update(config_obj.entries) # convert to a click-cli group click_group = create_click_cli(entries, callback) # add the typer app into our click group if typer_app is not None: typer_click_object = typer.main.get_command(typer_app) # add the app commands directly to out click app for name, cmd in typer_click_object.commands.items(): click_group.add_command(cmd, name) return click_group
null
156,143
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined def no_cast(value): return value
null
156,144
import inspect import json import logging import string from collections import OrderedDict from functools import partial, wraps from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union from decouple import Csv, UndefinedValueError, config, text_type, undefined from opal_common.authentication.casting import cast_private_key, cast_public_key from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception from pydantic import BaseModel, ValidationError from typer import Typer from .cli import get_cli_object_for_config_objects from .types import ConfiDelay, ConfiEntry, no_cast The provided code snippet includes necessary dependencies for implementing the `cast_boolean` function. Write a Python function `def cast_boolean(value)` to solve the following problem: Parse an entry as a boolean. - all variations of "true" and 1 are treated as True - all variations of "false" and 0 are treated as False Here is the function: def cast_boolean(value): """Parse an entry as a boolean. - all variations of "true" and 1 are treated as True - all variations of "false" and 0 are treated as False """ if isinstance(value, bool): return value elif isinstance(value, str): value = value.lower() if value == "true" or value == "1": return True elif value == "false" or value == "0": return False else: raise UndefinedValueError(f"{value} - is not a valid boolean") else: raise UndefinedValueError(f"{value} - is not a valid boolean")
Parse an entry as a boolean. - all variations of "true" and 1 are treated as True - all variations of "false" and 0 are treated as False
156,145
import inspect import json import logging import string from collections import OrderedDict from functools import partial, wraps from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union from decouple import Csv, UndefinedValueError, config, text_type, undefined from opal_common.authentication.casting import cast_private_key, cast_public_key from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception from pydantic import BaseModel, ValidationError from typer import Typer from .cli import get_cli_object_for_config_objects from .types import ConfiDelay, ConfiEntry, no_cast def cast_pydantic(model: BaseModel): def cast_pydantic_by_model(value): if isinstance(value, str): return model.parse_raw(value) else: return model.parse_obj(value) return cast_pydantic_by_model
null
156,146
import inspect import json import logging import string from collections import OrderedDict from functools import partial, wraps from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union from decouple import Csv, UndefinedValueError, config, text_type, undefined from opal_common.authentication.casting import cast_private_key, cast_public_key from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception from pydantic import BaseModel, ValidationError from typer import Typer from .cli import get_cli_object_for_config_objects from .types import ConfiDelay, ConfiEntry, no_cast class ConfiDelay: """Delay loaded confi entry default values.""" def __init__(self, value, index=-1) -> None: self._value = value # sorting index self.index = index def value(self): return self._value def eval(self, config=None): values = {k: v.value for k, v in config.entries.items()} if config else {} if isinstance(self._value, str): return self._value.format(**values) if callable(self._value): callargs = inspect.getcallargs(self._value) args = {k: values.get(k, undefined) for k, v in callargs.items()} return self._value(**args) def __repr__(self) -> str: try: return f"<Delayed {self.eval()}>" except: return f"<Delayed {self._value}>" The provided code snippet includes necessary dependencies for implementing the `ignore_confi_delay_cast` function. Write a Python function `def ignore_confi_delay_cast(cast_func)` to solve the following problem: when we pass a ConfiDelay as the default to decouple, until this delayed default is evaluated by confi, there is no point in casting it. After a ConfiDelay is evaluated, the resulted value should be passed again to the cast method, and this time it will indeed be cast. Here is the function: def ignore_confi_delay_cast(cast_func): """when we pass a ConfiDelay as the default to decouple, until this delayed default is evaluated by confi, there is no point in casting it. After a ConfiDelay is evaluated, the resulted value should be passed again to the cast method, and this time it will indeed be cast. """ @wraps(cast_func) def wrapped_cast(value, *args, **kwargs): if isinstance(value, ConfiDelay): return value return cast_func(value, *args, **kwargs) return wrapped_cast
when we pass a ConfiDelay as the default to decouple, until this delayed default is evaluated by confi, there is no point in casting it. After a ConfiDelay is evaluated, the resulted value should be passed again to the cast method, and this time it will indeed be cast.
156,147
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def get_filepaths_with_glob(root_path: str, file_regex: str): return glob.glob(os.path.join(root_path, file_regex))
null
156,148
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def hash_file(tmp_file_path): BUF_SIZE = 65536 # lets read stuff in 64kb chunks! sha256_hash = hashlib.sha256() with open(tmp_file_path, "rb") as file: while True: data = file.read(BUF_SIZE) if not data: break sha256_hash.update(data) return sha256_hash.hexdigest()
null
156,149
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp async def throw_if_bad_status_code( response: aiohttp.ClientResponse, expected: List[int], logger=None ) -> aiohttp.ClientResponse: if response.status in expected: return response # else, bad status code details = await response.json() if logger: logger.warning( "Unexpected response code {status}: {details}", status=response.status, details=details, ) raise ValueError( f"unexpected response code while fetching bundle: {response.status}" )
null
156,150
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def tuple_to_dict(tup: Tuple[str, str]) -> Dict[str, str]: return dict([tup])
null
156,151
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp The provided code snippet includes necessary dependencies for implementing the `build_aws_rest_auth_headers` function. Write a Python function `def build_aws_rest_auth_headers(key_id: str, secret_key: str, host: str, path: str)` to solve the following problem: Use the AWS signature algorithm (https://docs.aws.amazon.com/AmazonS3/la test/userguide/RESTAuthentication.html) to generate the hTTP headers. Args: key_id (str): Access key (aka user ID) of an account in the S3 service. secret_key (str): Secret key (aka password) of an account in the S3 service. host (str): S3 storage host path (str): path to bundle file in s3 storage (including bucket) Returns: http headers Here is the function: def build_aws_rest_auth_headers(key_id: str, secret_key: str, host: str, path: str): """Use the AWS signature algorithm (https://docs.aws.amazon.com/AmazonS3/la test/userguide/RESTAuthentication.html) to generate the hTTP headers. Args: key_id (str): Access key (aka user ID) of an account in the S3 service. secret_key (str): Secret key (aka password) of an account in the S3 service. host (str): S3 storage host path (str): path to bundle file in s3 storage (including bucket) Returns: http headers """ def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def getSignatureKey(key, dateStamp, regionName, serviceName): kDate = sign(("AWS4" + key).encode("utf-8"), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, "aws4_request") return kSigning t = datetime.utcnow() amzdate = t.strftime("%Y%m%dT%H%M%SZ") datestamp = t.strftime("%Y%m%d") canonical_headers = "host:" + host + "\n" + "x-amz-date:" + amzdate + "\n" signed_headers = "host;x-amz-date" payload_hash = hashlib.sha256("".encode("utf-8")).hexdigest() canonical_request = ( "GET" + "\n" + path + "\n" + "\n" + canonical_headers + "\n" + signed_headers + "\n" + payload_hash ) region = "us-east-1" algorithm = "AWS4-HMAC-SHA256" credential_scope = datestamp + "/" + region + "/" + "s3" + "/" + "aws4_request" string_to_sign = ( algorithm + "\n" + amzdate + "\n" + credential_scope + "\n" + hashlib.sha256(canonical_request.encode("utf-8")).hexdigest() ) signing_key = getSignatureKey(secret_key, datestamp, region, "s3") signature = hmac.new( signing_key, (string_to_sign).encode("utf-8"), hashlib.sha256 ).hexdigest() authorization_header = ( algorithm + " " + "Credential=" + key_id + "/" + credential_scope + ", " + "SignedHeaders=" + signed_headers + ", " + "Signature=" + signature ) return { "x-amz-date": amzdate, "Authorization": authorization_header, }
Use the AWS signature algorithm (https://docs.aws.amazon.com/AmazonS3/la test/userguide/RESTAuthentication.html) to generate the hTTP headers. Args: key_id (str): Access key (aka user ID) of an account in the S3 service. secret_key (str): Secret key (aka password) of an account in the S3 service. host (str): S3 storage host path (str): path to bundle file in s3 storage (including bucket) Returns: http headers
156,152
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def sorted_list_from_set(s: set) -> list: l = list(s) l.sort() return l
null
156,153
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp The provided code snippet includes necessary dependencies for implementing the `thread_worker` function. Write a Python function `async def thread_worker(queue: asyncio.Queue, logger: logging.Logger)` to solve the following problem: The worker task is *running and then awaiting* a coroutine that was scheduled on the thread's async loop from *OUTSIDE* (i.e: from another thread). Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself Here is the function: async def thread_worker(queue: asyncio.Queue, logger: logging.Logger): """The worker task is *running and then awaiting* a coroutine that was scheduled on the thread's async loop from *OUTSIDE* (i.e: from another thread). Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself """ while True: # get the next coroutine scheduled on the thread's queue # this may block until another coroutine is scheduled coro: Coroutine = await queue.get() try: # await on the coroutine and possibly block *this* worker await coro except Exception as err: logger.exception(f"Scheduled coroutine - {coro} failed") finally: # Notify the queue that the "work item" has been processed. queue.task_done()
The worker task is *running and then awaiting* a coroutine that was scheduled on the thread's async loop from *OUTSIDE* (i.e: from another thread). Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself
156,154
import functools import logging def log_exception(logger=logging.getLogger(), rethrow=True): def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logger.exception(e) if rethrow: raise return wrapper return deco
null
156,155
import asyncio from typing import Coroutine from ..events import FetchEvent from ..fetcher_register import FetcherRegister from ..logger import get_logger from .base_fetching_engine import BaseFetchingEngine logger = get_logger("fetch_worker") class FetchEvent(BaseModel): """Event used to describe an queue fetching tasks Design note - By using a Pydantic model - we can create a potentially transfer FetchEvents to be handled by other network nodes (perhaps via RPC) """ # Event id to be filled by the engine id: str = None # optional name of the specific event name: str = None # A string identifying the fetcher class to use (as registered in the fetcher register) fetcher: str # The url the event targets for fetching url: str # Specific fetcher configuration (overridden by deriving event classes (FetcherConfig) config: dict = None # Tenacity.retry - Override default retry configuration for this event retry: dict = None class FetcherRegister: """A store for fetcher providers.""" # Builtin fetchers BASIC_CONFIG = { "HttpFetchProvider": HttpFetchProvider, } def __init__(self, config: Optional[Dict[str, BaseFetchProvider]] = None) -> None: if config is not None: self._config = config else: from ..emport import emport_objects_by_class # load fetchers fetchers = [] for module_path in opal_common_config.FETCH_PROVIDER_MODULES: try: providers_to_register = emport_objects_by_class( module_path, BaseFetchProvider, ["*"] ) for provider_name, provider_class in providers_to_register: logger.info( f"Loading FetcherProvider '{provider_name}' found at: {repr(provider_class)}" ) fetchers.extend(providers_to_register) except: logger.exception( f"Failed to load FetchingProvider module: {module_path}" ) self._config = {name: fetcher for name, fetcher in fetchers} logger.info("Fetcher Register loaded", extra={"config": self._config}) def register_fetcher(self, name: str, fetcher_class: Type[BaseFetchProvider]): self._config[name] = fetcher_class def get_fetcher(self, name: str, event: FetchEvent) -> BaseFetchProvider: """Init a fetcher instance from a registered fetcher class name. Args: name (str): Name of a registered fetcher event (FetchEvent): Event used to configure the fetcher Returns: BaseFetchProvider: A fetcher instance """ provider_class = self._config.get(name, None) if provider_class is None: raise NoMatchingFetchProviderException( f"Couldn't find a match for - {name} , {event}" ) fetcher = provider_class(event) if event.retry is not None: fetcher.set_retry_config(event.retry) return fetcher def get_fetcher_for_event(self, event: FetchEvent) -> BaseFetchProvider: """Same as get_fetcher, using the event information to deduce the fetcher class. Args: event (FetchEvent): Event used to choose and configure the fetcher Returns: BaseFetchProvider: A fetcher instance """ return self.get_fetcher(event.fetcher, event) class BaseFetchingEngine: """An interface base class for a task queue manager used for fetching events.""" def register(self) -> FetcherRegister: """access to the underlying fetcher providers register.""" raise NotImplementedError() async def __aenter__(self): """Async Context manager to cancel tasks on exit.""" raise NotImplementedError() async def __aexit__(self, exc_type, exc, tb): raise NotImplementedError() async def terminate_tasks(self): """Cancel and wait on the internal worker tasks.""" raise NotImplementedError() async def queue_url( self, url: str, callback: Coroutine, config: FetcherConfig = None, fetcher="HttpFetchProvider", ) -> FetchEvent: """Simplified default fetching handler for queuing a fetch task. Args: url (str): the URL to fetch from callback (Coroutine): a callback to call with the fetched result config (FetcherConfig, optional): Configuration to be used by the fetcher. Defaults to None. fetcher (str, optional): Which fetcher class to use. Defaults to "HttpFetchProvider". Returns: the queued event (which will be mutated to at least have an Id) """ raise NotImplementedError() async def queue_fetch_event( self, event: FetchEvent, callback: Coroutine ) -> FetchEvent: """Basic handler to queue a fetch event for a fetcher class. Waits if the queue is full. Args: event (FetchEvent): the fetch event to queue as a task callback (Coroutine): a callback to call with the fetched result Returns: the queued event (which will be mutated to at least have an Id) """ raise NotImplementedError() def register_failure_handler(self, callback: OnFetchFailureCallback): """Register a callback to be called with exception and original event in case of failure. Args: callback (OnFetchFailureCallback): callback to register """ raise NotImplementedError() async def _on_failure(self, error: Exception, event: FetchEvent): """Call event failure subscribers. Args: error (Exception): thrown exception event (FetchEvent): event which was being handled """ raise NotImplementedError() The provided code snippet includes necessary dependencies for implementing the `fetch_worker` function. Write a Python function `async def fetch_worker(queue: asyncio.Queue, engine)` to solve the following problem: The worker task performing items added to the Engine's Queue. Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself Here is the function: async def fetch_worker(queue: asyncio.Queue, engine): """The worker task performing items added to the Engine's Queue. Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself """ engine: BaseFetchingEngine register: FetcherRegister = engine.register while True: # types event: FetchEvent callback: Coroutine # get a event from the queue event, callback = await queue.get() # take care of it try: # get fetcher for the event fetcher = register.get_fetcher_for_event(event) # fetch async with fetcher: res = await fetcher.fetch() data = await fetcher.process(res) # callback to event owner try: await callback(data) except Exception as err: logger.exception(f"Fetcher callback - {callback} failed") await engine._on_failure(err, event) except Exception as err: logger.exception("Failed to process fetch event") await engine._on_failure(err, event) finally: # Notify the queue that the "work item" has been processed. queue.task_done()
The worker task performing items added to the Engine's Queue. Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself
156,156
from ..events import FetchEvent class FetchEvent(BaseModel): """Event used to describe an queue fetching tasks Design note - By using a Pydantic model - we can create a potentially transfer FetchEvents to be handled by other network nodes (perhaps via RPC) """ # Event id to be filled by the engine id: str = None # optional name of the specific event name: str = None # A string identifying the fetcher class to use (as registered in the fetcher register) fetcher: str # The url the event targets for fetching url: str # Specific fetcher configuration (overridden by deriving event classes (FetcherConfig) config: dict = None # Tenacity.retry - Override default retry configuration for this event retry: dict = None The provided code snippet includes necessary dependencies for implementing the `OnFetchFailureCallback` function. Write a Python function `async def OnFetchFailureCallback(exception: Exception, event: FetchEvent)` to solve the following problem: Args: exception (Exception): The exception thrown causing the failure event (FetchEvent): the queued event which failed Here is the function: async def OnFetchFailureCallback(exception: Exception, event: FetchEvent): """ Args: exception (Exception): The exception thrown causing the failure event (FetchEvent): the queued event which failed """ pass
Args: exception (Exception): The exception thrown causing the failure event (FetchEvent): the queued event which failed
156,157
import logging logger = logging.getLogger("opal.fetcher") def get_logger(name): return logger.getChild(name)
null
156,158
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized from opal_common.logger import logger JWTClaims = Dict[str, Any] class Unauthorized(HTTPException): """HTTP 401 Unauthorized exception.""" def __init__(self, description="Bearer token is not valid!", **kwargs): super().__init__( status_code=status.HTTP_401_UNAUTHORIZED, detail={"error": description, **kwargs}, headers={"WWW-Authenticate": "Bearer"}, ) class JWTVerifier: """given a cryptographic public key, can verify jwt tokens.""" def __init__( self, public_key: Optional[PublicKey], algorithm: JWTAlgorithm, audience: str, issuer: str, ): """inits the signer if and only if the keys provided to __init__ were generate together are are valid. otherwise will throw. JWT verifier can be initialized without a public key (None) in which case verifier.enabled == False and jwt verification is turned off. This allows opal to run both in secure mode (with jwt-based authentication) and in insecure mode (intended for development environments and running locally). Args: public_key (PublicKey): a valid public key or None algorithm (JWTAlgorithm): the jwt algorithm to use (possible values: https://pyjwt.readthedocs.io/en/stable/algorithms.html) audience (string): the value for the aud claim: https://tools.ietf.org/html/rfc7519#section-4.1.3 issuer (string): the value for the iss claim: https://tools.ietf.org/html/rfc7519#section-4.1.1 """ self._public_key = public_key self._algorithm: str = algorithm.value self._audience = audience self._issuer = issuer self._enabled = True self._verify_public_key() def _verify_public_key(self): """verifies whether or not the public key is a valid crypto key (according to the JWT algorithm).""" if self._public_key is not None: # save jwk try: self._jwk: PyJWK = PyJWK.from_json( self.get_jwk(), algorithm=self._algorithm ) except jwt.exceptions.InvalidKeyError as e: logger.error(f"Invalid public key for jwt verification, error: {e}!") self._disable() else: self._disable() def get_jwk(self) -> str: """returns the jwk json contents.""" algorithm: Optional[Algorithm] = get_default_algorithms().get(self._algorithm) if algorithm is None: raise ValueError(f"invalid jwt algorithm: {self._algorithm}") return algorithm.to_jwk(self._public_key) def _disable(self): self._enabled = False def enabled(self): """whether or not the verifier has valid cryptographic keys.""" return self._enabled def verify(self, token: str) -> JWTClaims: """verifies a JWT token is valid. if valid returns dict with jwt claims, otherwise throws. """ try: return jwt.decode( token, self._public_key, algorithms=[self._algorithm], audience=self._audience, issuer=self._issuer, ) except jwt.ExpiredSignatureError: raise Unauthorized(token=token, description="Access token is expired") except jwt.InvalidAudienceError: raise Unauthorized( token=token, description="Invalid access token: invalid audience claim" ) except jwt.InvalidIssuerError: raise Unauthorized( token=token, description="Invalid access token: invalid issuer claim" ) except jwt.DecodeError: raise Unauthorized(token=token, description="Could not decode access token") except Exception: raise Unauthorized(token=token, description="Unknown JWT error") The provided code snippet includes necessary dependencies for implementing the `verify_logged_in` function. Write a Python function `def verify_logged_in(verifier: JWTVerifier, token: Optional[str]) -> JWTClaims` to solve the following problem: forces bearer token authentication with valid JWT or throws 401. Here is the function: def verify_logged_in(verifier: JWTVerifier, token: Optional[str]) -> JWTClaims: """forces bearer token authentication with valid JWT or throws 401.""" try: if not verifier.enabled: logger.debug("JWT verification disabled, cannot verify requests!") return {} if token is None: raise Unauthorized(description="access token was not provided") claims: JWTClaims = verifier.verify(token) subject = claims.get("sub", "") invalid = Unauthorized(description="invalid sub claim") if not subject: raise invalid try: _ = UUID(subject) except ValueError: raise invalid # returns the entire claims dict so we can do more checks on it if needed return claims or {} except (Unauthorized, HTTPException) as err: # err.details is sometimes string and sometimes dict details: dict = {} if isinstance(err.detail, dict): details = err.detail.copy() elif isinstance(err.detail, str): details = {"msg": err.detail} else: details = {"msg": repr(err.detail)} # pop the token before logging - tokens should not appear in logs details.pop("token", None) # logs the error and reraises logger.error( f"Authentication failed with {err.status_code} due to error: {details}" ) raise
forces bearer token authentication with valid JWT or throws 401.