Skip to content
This repository has been archived by the owner on Mar 13, 2023. It is now read-only.

Commit

Permalink
feat: add listener shortcut to event objects (#611)
Browse files Browse the repository at this point in the history
feat: add listener shortcutn to event objects

real niche, but its useful to me!
  • Loading branch information
LordOfPolls committed Aug 20, 2022
1 parent 1898b8d commit a0b80bd
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion naff/api/events/internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ def on_guild_join(event):
"""
import re
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Optional, Callable, Coroutine

from naff.client.const import MISSING
from naff.models.discord.snowflake import to_snowflake
from naff.client.utils.attr_utils import define, field, docs
import naff.models as models

__all__ = (
"BaseEvent",
Expand Down Expand Up @@ -70,6 +71,32 @@ def resolved_name(self) -> str:
name = self.override_name or self.__class__.__name__
return _event_reg.sub("_", name).lower()

@classmethod
def listen(cls, coro: Callable[..., Coroutine], client: "Client") -> "models.Listener":
"""
A shortcut for creating a listener for this event
Args:
coro: The coroutine to call when the event is triggered.
client: The client instance to listen to.
??? Hint "Example Usage:"
```python
class SomeClass:
def __init__(self, bot: Client):
Ready.listen(self.some_func, bot)
async def some_func(self, event):
print(f"{event.resolved_name} triggered")
```
Returns:
A listener object.
"""
listener = models.Listener.create(cls().resolved_name)(coro)
client.add_listener(listener)
return listener


@define(slots=False, kw_only=False)
class GuildEvent:
Expand Down

0 comments on commit a0b80bd

Please sign in to comment.