Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现set_arg和get_arg类方法 #2217

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions nonebot/internal/matcher/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ class Matcher(metaclass=MatcherMeta):
def __init__(self):
self.handlers = self.handlers.copy()
self.state = self._default_state.copy()
self._m_t = current_matcher.set(self)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这是在干啥?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

让Matcher()的情况也能get到matcher

但不知道该在啥时候reset,就写个变量,让它在ensure_context里被覆盖...


def __repr__(self) -> str:
return (
Expand Down Expand Up @@ -609,26 +610,30 @@ def get_last_receive(
"""
return self.state.get(LAST_RECEIVE_KEY, default)

@classmethod
@overload
def get_arg(self, key: str) -> Union[Message, None]:
def get_arg(cls, key: str) -> Union[Message, None]:
...

@classmethod
@overload
def get_arg(self, key: str, default: T) -> Union[Message, T]:
def get_arg(cls, key: str, default: T) -> Union[Message, T]:
...

@classmethod
def get_arg(
self, key: str, default: Optional[T] = None
cls, key: str, default: Optional[T] = None
) -> Optional[Union[Message, T]]:
"""获取一个 `got` 消息

如果没有找到对应的消息,返回 `default` 值
"""
return self.state.get(ARG_KEY.format(key=key), default)
return current_matcher.get().state.get(ARG_KEY.format(key=key), default)

def set_arg(self, key: str, message: Message) -> None:
@classmethod
def set_arg(cls, key: str, message: Message) -> None:
"""设置一个 `got` 消息"""
self.state[ARG_KEY.format(key=key)] = message
current_matcher.get().state[ARG_KEY.format(key=key)] = message

def set_target(self, target: str, cache: bool = True) -> None:
if cache:
Expand Down Expand Up @@ -700,13 +705,13 @@ async def resolve_reject(self):
def ensure_context(self, bot: Bot, event: Event):
b_t = current_bot.set(bot)
e_t = current_event.set(event)
m_t = current_matcher.set(self)
self._m_t = current_matcher.set(self)
try:
yield
finally:
current_bot.reset(b_t)
current_event.reset(e_t)
current_matcher.reset(m_t)
current_matcher.reset(self._m_t)

async def simple_run(
self,
Expand Down
Loading