Skip to content

Commit

Permalink
feat(Chat): added was_executed callback to middleware, using that to …
Browse files Browse the repository at this point in the history
…update internal state of middleware only when a command was actually executed.
  • Loading branch information
Teekeks committed Aug 31, 2023
1 parent 70f9c15 commit b14dece
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 14 deletions.
5 changes: 5 additions & 0 deletions docs/tutorial/chat-use-middleware.rst
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ In the following example, we will create a middleware which allows the command t
# add your own logic here, return True if the command should execute and False otherwise
return random.choice([True, False])
async def was_executed(cmd: ChatCommand):
# this will be called whenever a command this Middleware is attached to was executed, use this to update your internal state
# since this is a basic example, we do nothing here
pass
Now use this middleware as any other:

Expand Down
2 changes: 2 additions & 0 deletions twitchAPI/chat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,8 @@ async def _can_execute_command(_com: ChatCommand, _name: str) -> bool:
if _can_execute_command(command, command_name):
t = asyncio.ensure_future(handler(command), loop=self._callback_loop)
t.add_done_callback(self._task_callback)
for _mid in self._command_middleware + self._command_specific_middleware.get(command_name, []):
await _mid.was_executed(command)
else:
if self.log_no_registered_command_handler:
self.logger.info(f'no handler registered for command "{command_name}"')
Expand Down
48 changes: 34 additions & 14 deletions twitchAPI/chat/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ async def can_execute(self, command: 'ChatCommand') -> bool:
:param command: The command to check if it should be executed"""
pass

@abstractmethod
async def was_executed(self, command: 'ChatCommand'):
"""Will be called when a command was executed, use to update internal state"""
pass


class ChannelRestriction(BaseCommandMiddleware):
"""Filters in which channels a command can be executed in"""
Expand All @@ -57,6 +62,9 @@ async def can_execute(self, command: 'ChatCommand') -> bool:
return False
return command.room.name not in self.denied

async def was_executed(self, command: 'ChatCommand'):
pass


class UserRestriction(BaseCommandMiddleware):
"""Filters which users can execute a command"""
Expand All @@ -80,6 +88,9 @@ async def can_execute(self, command: 'ChatCommand') -> bool:
return False
return command.user.name not in self.denied

async def was_executed(self, command: 'ChatCommand'):
pass


class StreamerOnly(BaseCommandMiddleware):
"""Restricts the use of commands to only the streamer in their channel"""
Expand All @@ -93,6 +104,9 @@ def __int__(self, execute_blocked_handler: Optional[Callable[[ChatCommand], Awai
async def can_execute(self, command: 'ChatCommand') -> bool:
return command.room.name == command.user.name

async def was_executed(self, command: 'ChatCommand'):
pass


class ChannelCommandCooldown(BaseCommandMiddleware):
"""Restricts a command to only be executed once every :const:`cooldown_seconds` seconds in a channel regardless of user."""
Expand All @@ -108,18 +122,20 @@ def __int__(self,

async def can_execute(self, command: 'ChatCommand') -> bool:
if self._last_executed.get(command.name) is None:
self._last_executed[command.name] = {}
self._last_executed[command.name][command.room.name] = datetime.now()
return True
last_executed = self._last_executed.get(command.name).get(command.room.name)
last_executed = self._last_executed[command.name].get(command.room.name)
if last_executed is None:
self._last_executed[command.name][command.room.name] = datetime.now()
return True
since = (datetime.now() - last_executed).total_seconds()
if since >= self.cooldown:
self._last_executed[command.name][command.room.name] = datetime.now()
return since >= self.cooldown

async def was_executed(self, command: 'ChatCommand'):
if self._last_executed.get(command.name) is None:
self._last_executed[command.name] = {}
self._last_executed[command.name][command.room.name] = datetime.now()
return
self._last_executed[command.name][command.room.name] = datetime.now()


class ChannelUserCommandCooldown(BaseCommandMiddleware):
"""Restricts a command to be only executed once every :const:`cooldown_seconds` in a channel by a user."""
Expand All @@ -135,20 +151,24 @@ def __int__(self,

async def can_execute(self, command: 'ChatCommand') -> bool:
if self._last_executed.get(command.name) is None:
self._last_executed[command.name] = {}
self._last_executed[command.name][command.room.name] = {}
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return True
if self._last_executed[command.name].get(command.room.name) is None:
self._last_executed[command.name][command.room.name] = {}
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return True
last_executed = self._last_executed[command.name][command.room.name].get(command.user.name)
if last_executed is None:
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return True
since = (datetime.now() - last_executed).total_seconds()
if since >= self.cooldown:
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return since >= self.cooldown

async def was_executed(self, command: 'ChatCommand'):
if self._last_executed.get(command.name) is None:
self._last_executed[command.name] = {}
self._last_executed[command.name][command.room.name] = {}
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return
if self._last_executed[command.name].get(command.room.name) is None:
self._last_executed[command.name][command.room.name] = {}
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()
return
self._last_executed[command.name][command.room.name][command.user.name] = datetime.now()

0 comments on commit b14dece

Please sign in to comment.