Skip to content

Commit

Permalink
Implement a global check function
Browse files Browse the repository at this point in the history
  • Loading branch information
nexy7574 committed Feb 7, 2025
1 parent 716ae61 commit 99deabc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
8 changes: 8 additions & 0 deletions src/niobot/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,14 @@ async def _auto_join_room_backlog_callback(self, room: nio.MatrixRoom, event: ni
if event.state_key == self.user_id:
await self._auto_join_room_callback(room, event)

async def global_command_check(self, ctx: "Context") -> bool:
"""A global check that runs before every command.
This is a no-op by default, but can be overridden to provide global checks.
If this function returns False or raises an error, the check is considered failed, and the command will not run.
"""
return True

@staticmethod
def latency(event: nio.Event, *, received_at: typing.Optional[float] = None) -> float:
"""Returns the latency for a given event in milliseconds
Expand Down
28 changes: 18 additions & 10 deletions src/niobot/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,20 @@ def display_usage(self) -> str:
usage.append(opt.format(arg.name))
return " ".join(usage)

@staticmethod
async def run_check(function, name: str, context: Context) -> typing.Literal[True]:
from .utils import force_await

try:
cr = await force_await(function, context)
except CheckFailure:
raise # re-raise existing check failures
except Exception as e:
raise CheckFailure(name, exception=e) from e
if not cr:
raise CheckFailure(name)
return True

async def can_run(self, ctx: Context) -> bool:
"""Checks if the current user passes all the checks on the command.
Expand All @@ -362,19 +376,11 @@ async def can_run(self, ctx: Context) -> bool:
"""
if self.disabled:
raise CommandDisabledError(self)
from .utils import force_await

await self.run_check(ctx.client.global_command_check, "global_command_check", ctx)
if self.checks:
for chk_func in self.checks:
name = self.callback.__nio_checks__[chk_func]
try:
cr = await force_await(chk_func, ctx)
except CheckFailure:
raise # re-raise existing check failures
except Exception as e:
raise CheckFailure(name, exception=e) from e
if not cr:
raise CheckFailure(name)
await self.run_check(chk_func, chk_func.__name__, ctx)
return True

async def parse_args(
Expand Down Expand Up @@ -412,8 +418,10 @@ async def parse_args(
self.log.debug("Parsed argument %d (%r<%r>) to %r", next_arg, arg, value, parsed)
if arg.greedy:
to_pass[arg].append(parsed)
self.log.debug("Not incrementing argument index due to greedy=True")
else:
to_pass[arg] = parsed
self.log.debug("Incrementing next_arg from %d to %d", next_arg, next_arg + 1)
next_arg += 1

for arg, value in to_pass.items():
Expand Down

0 comments on commit 99deabc

Please sign in to comment.