Skip to content

Commit

Permalink
Document add/remove listener
Browse files Browse the repository at this point in the history
  • Loading branch information
EvieePy committed Jan 4, 2025
1 parent eced984 commit fe8d5be
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions twitchio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,27 @@ async def save_tokens(self, path: str | None = None, /) -> None:
await self._http.save(path)

def add_listener(self, listener: Callable[..., Coroutine[Any, Any, None]], *, event: str | None = None) -> None:
# TODO: Docs...
"""Method to add an event listener to the client.
See: :meth:`.listen` for more information on event listeners and for a decorator version of this function.
Parameters
----------
listener: Callable[..., Coroutine[Any, Any, None]]
The coroutine to assign as the callback for the listener.
event: str | None
An optional :class:`str` which indicates which event to listen to. This should include the ``event_`` prefix.
Defaults to ``None`` which uses the coroutine function name passed instead.
Raises
------
ValueError
The ``event`` string passed should start with ``event_``.
ValueError
The ``event`` string passed must not == ``event_``.
TypeError
The listener callback must be a coroutine function.
"""
name: str = event or listener.__name__

if not name.startswith("event_"):
Expand All @@ -729,15 +749,32 @@ def add_listener(self, listener: Callable[..., Coroutine[Any, Any, None]], *, ev
raise ValueError('Listener and event names cannot be named "event_".')

if not asyncio.iscoroutinefunction(listener):
raise ValueError("Listeners and Events must be coroutines.")
raise TypeError("Listeners and Events must be coroutines.")

self._listeners[name].add(listener)

def remove_listener(self, listener: Callable[..., Coroutine[Any, Any, None]]) -> None:
# TODO: Docs...
def remove_listener(
self,
listener: Callable[..., Coroutine[Any, Any, None]],
) -> Callable[..., Coroutine[Any, Any, None]] | None:
"""Method to remove a currently registered listener from the client.
Parameters
----------
listener: Callable[..., Coroutine[Any, Any, None]]
The coroutine wrapped with :meth:`.listen` or added via :meth:`.add_listener` to remove as a listener.
Returns
-------
Callable[..., Coroutine[Any, Any, None]]
If a listener was removed, the coroutine function will be returned.
None
Returns ``None`` when no listener was removed.
"""
for listeners in self._listeners.values():
if listener in listeners:
listeners.remove(listener)
return listener

def listen(self, name: str | None = None) -> Any:
"""|deco|
Expand Down

0 comments on commit fe8d5be

Please sign in to comment.