# This is part of Kaylee # -- this code is licensed GPLv3 # Copyright 2015-2017 Clayton G. Hobbs # Portions Copyright 2013 Jezra """Run shell commands that match voice commands This Kaylee plugin can be used to perform the job of `Blather `__. Its configuration is of the following format:: ".shell": { "VOICE_COMMAND": "SHELL_COMMAND", ... } A VOICE_COMMAND may contain any number of the special word ``%d``, which is a stand-in for a spoken number. The spoken number is transformed into a decimal integer which may be substituted into the SHELL_COMMAND any number of times. These substitutions are made by writing ``{INDEX}`` in the SHELL_COMMAND, where INDEX is an integer counting the ``%d`` strings from 0. An example of this type of command is:: "%d is a number": "echo 'the number you said was {0}'" """ import subprocess from .pluginbase import PluginBase from ..numbers import NumberParser class Plugin(PluginBase): """Run shell commands that match voice commands""" def __init__(self, config, name): """Initialize the shell plugin""" super().__init__(config, name) self.number_parser = NumberParser() self.commands = self.options for voice_cmd in self.commands.keys(): self.corpus_strings.add(voice_cmd.strip().replace('%d', '')) def _run_command(self, cmd): """Print the command, then run it""" print(cmd) subprocess.call(cmd, shell=True) def recognizer_finished(self, recognizer, text): """Run the shell command corresponding to a recognized voice command Spoken number(s) may be substituted in the shell command. The shell commands are printed immediately before they are executed. """ numt, nums = self.number_parser.parse_all_numbers(text) # Is there a matching command? if text in self.commands: self.emit('processed', text) cmd = self.commands[text] self._run_command(cmd) return True # Is there a matching command with numbers substituted? elif numt in self.commands: self.emit('processed', text) cmd = self.commands[numt] cmd = cmd.format(*nums) self._run_command(cmd) return True else: return False