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

Implement decorator-based event handler registration #165

Merged
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
20 changes: 20 additions & 0 deletions pydle/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from . import connection, protocol
import warnings
import inspect
import functools

__all__ = ['Error', 'AlreadyInChannel', 'NotInChannel', 'BasicClient', 'ClientPool']
DEFAULT_NICKNAME = '<unregistered>'
Expand Down Expand Up @@ -448,6 +450,24 @@ def __getattr__(self, attr):
# This isn't a handler, just raise an error.
raise AttributeError(attr)

# Bonus features
def event(self, func):
"""
Registers the specified `func` to handle events of the same name.

The func will always be called with, at least, the bot's `self` instance.

Returns decorated func, unmodified.
"""
if not func.__name__.startswith("on_"):
raise NameError("Event handlers must start with 'on_'.")

if not inspect.iscoroutinefunction(func):
raise AssertionError("Wrapped function {!r} must be an `async def` function.".format(func))
setattr(self, func.__name__, functools.partial(func, self))

return func


class ClientPool:
""" A pool of clients that are ran and handled in parallel. """
Expand Down