Merge pull request #65 from dhghf/cmd-refactor

CMD module refactor
This commit is contained in:
Ville Ranki 2020-03-30 21:36:38 +03:00 committed by GitHub
commit 6a9a1f845c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 30 deletions

View File

@ -218,11 +218,11 @@ Environ variables seen by commands:
Commands: Commands:
* !cmd run "command" - Run command "command" (Must be done as bot owner) * !cmd run command - Run command "command" (Must be done as bot owner)
* !cmd add cmdname "command" - Add new named command "command" (Must be done as bot owner) * !cmd add "cmdname" command - Add new named command "command" (Must be done as bot owner)
* !cmd remove cmdname - Remove named command (Must be done as bot owner) * !cmd remove "cmdname" - Remove named command (Must be done as bot owner)
* !cmd list - List named commands * !cmd list - List named commands
* !cmd cmdname - Run a named command * !cmd "cmdname" - Run a named command
Example: Example:

View File

@ -4,36 +4,61 @@ import shlex
class MatrixModule(BotModule): class MatrixModule(BotModule):
commands = dict() # cmd name -> shell command def __init__(self, name):
super().__init__(name)
self.commands = {}
async def matrix_message(self, bot, room, event): async def matrix_message(self, bot, room, event):
args = shlex.split(event.body) args = shlex.split(event.body)
args.pop(0) args.pop(0)
# Message body possibilities:
if len(args) == 2: # ["run", "echo", "Hello", "world"]
if args[0] == 'run': if args[0] == 'run':
command_body = MatrixModule.stitch(args[1:])
bot.must_be_owner(event) bot.must_be_owner(event)
out = self.run_command(args[1], event.sender, room.display_name) out = self.run_command(command_body, event.sender, room.display_name)
await self.send_output(bot, room, out) await self.send_output(bot, room, out)
if args[0] == 'remove': # Message body possibilities:
# ["remove", "command_name"]
elif args[0] == 'remove':
command_name = args[1]
bot.must_be_owner(event) bot.must_be_owner(event)
cmdname = args[1] if command_name in self.commands:
self.commands.pop(cmdname, None) await bot.send_text(room, f'Removed "{self.commands[command_name]}"')
del self.commands[command_name]
bot.save_settings() bot.save_settings()
await bot.send_text(room, 'Command removed.') else:
elif len(args) == 3: await bot.send_text(room, f'Could not find command "{command_name}"')
if args[0] == 'add': # Message body possibilities:
# ["add", "command_name", "echo", "Hello", "world"]
elif args[0] == 'add':
command_name = args[1]
command_body = MatrixModule.stitch(args[2:])
bot.must_be_owner(event) bot.must_be_owner(event)
cmdname = args[1] self.commands[command_name] = command_body
self.commands[cmdname] = args[2]
bot.save_settings() bot.save_settings()
await bot.send_text(room, 'Command added.') await bot.send_text(room, f'Added "{command_name}" -> "{command_body}".')
elif len(args) == 1: # Message body possibilities:
if args[0] == 'list': # ["list"]
await bot.send_text(room, 'Known commands: ' + str(self.commands)) elif args[0] == 'list':
elif args[0] in self.commands: if len(self.commands) == 0:
self.logger.debug(f"room: {room.display_name} sender: {event.sender} wants to run cmd {args[0]}") await bot.send_text(room, "No known commands")
out = self.run_command(self.commands[args[0]], event.sender, room.display_name) else:
known_commands = "Known commands:\n"
for command_name in self.commands.keys():
command_body = self.commands[command_name]
known_commands += f' - "{command_name}" -> "{command_body}"\n'
await bot.send_text(room, known_commands)
# Message body possibilities:
# ["command_name"]
else:
command_name = args[0]
if command_name in self.commands:
target_command = self.commands[command_name]
self.logger.debug(
f"room: {room.display_name} sender: {event.sender} wants to run cmd {target_command}"
)
out = self.run_command(target_command, event.sender, room.display_name)
await self.send_output(bot, room, out) await self.send_output(bot, room, out)
else: else:
await bot.send_text(room, 'Unknown command.') await bot.send_text(room, 'Unknown command.')
@ -51,6 +76,19 @@ class MatrixModule(BotModule):
if data.get('commands'): if data.get('commands'):
self.commands = data['commands'] self.commands = data['commands']
@staticmethod
def stitch(body: list) -> str:
"""
This is used for stitching arguments again
Examples:
["echo", "Hello", "world"] -> "echo Hello world"
Args:
body: str[]
Returns: str
"""
return " ".join(body)
def run_command(self, command, user, roomname): def run_command(self, command, user, roomname):
self.logger.info(f"Running command {command}..") self.logger.info(f"Running command {command}..")
environment = {'MATRIX_USER': user, 'MATRIX_ROOM': roomname} environment = {'MATRIX_USER': user, 'MATRIX_ROOM': roomname}