Exemplo n.º 1
0
    def parse_input(self):
        args = input().split(' ')

        if args[0].upper() in commands.keys():
            commands[args[0].upper()](self, args[1:])
        else:
            self.current_screen = f"{args[0]} не является внутренней или внешней командой\r\n"
        
        self.current_screen += f'\n{self.cwd.lower()}>'
Exemplo n.º 2
0
def route(message):
    '''routes message to proper function'''
    user = message.body['user']
    text = message.body['text'].replace(u'\u201c', '"').replace(u'\u201d', '"')
    command, query = parse(text)
    if command.lower() in commands.keys():
        response, attachments = commands[command.lower()](query, user)
    else:
        response, attachments = commands['help']("", "")
    message.send_webapi(response, attachments)
Exemplo n.º 3
0
def handleMessage(message):
    if len(message.body) < 1:
        return commands["unknown"](message)

    command = message.body.split(" ")[0]
    command = command.lower()

    if command in commands.keys():
        return commands[command](message)
    else:
        return commands["search"](message)
Exemplo n.º 4
0
def index():
    if request.method == 'GET':
        return render_template('index.html', commands=commands, addresses=receiving_addresses)

    if request.method == 'POST':
        command = request.get_json()
        command_name = command.get('command_name')
        command_addresses = command.get('addresses')
        logging.debug("Received: {}".format(str(command)))
        results = {}

        if command_name == "custom":
            custom = command.get('custom_values')
            if custom is not None:
                custom = [int(i) for i in custom]
                results = send_all(command_addresses, create_command_array(custom))

        elif command_name in commands.keys():
            results = send_all(command_addresses, create_command_array(commands[command_name]))

        return jsonify(**results)
Exemplo n.º 5
0
def process_message(message):
    responses = []
    forename = message.name.split(" ", 1)[0]
    f_matches = re.search("can i get an? (.+) in the chat", message.text, flags=re.IGNORECASE | re.MULTILINE)
    if f_matches is not None and len(f_matches.groups()):
        responses.append(f_matches.groups()[0] + " ❤")
    if message.sender_type == SenderType.USER:
        if message.text.startswith(PREFIX):
            instructions = message.text[len(PREFIX):].strip().split(None, 1)
            command = instructions.pop(0).lower()
            query = instructions[0] if len(instructions) > 0 else ""
            # Prevent response if prefix is repeated
            if PREFIX in command:
                pass
            # Check if there's a static response for this command
            elif command in static_commands:
                responses.append(static_commands[command])
            # If not, query appropriate module for a response
            elif command in commands:
                # Make sure there are enough arguments
                if len(modules.Module.lines(None, query)) < commands[command].ARGC:
                    responses.append(commands[command].ARGUMENT_WARNING)
                else:
                    response = commands[command].response(query, message)
                    if response is not None:
                        responses.append(response)
            elif command == "help":
                if query:
                    query = query.strip(PREFIX)
                    if query in static_commands:
                        responses.append(PREFIX + query + ": static response.")
                    elif query in commands:
                        responses.append(PREFIX + query + ": " + commands[query].DESCRIPTION + f". Requires {commands[query].ARGC} argument(s).")
                    else:
                        responses.append("No such command.")
                else:
                    help_string = "--- Help ---"
                    help_string += "\nStatic commands: " + ", ".join([PREFIX + title for title in static_commands])
                    help_string += "\nTools: " + ", ".join([PREFIX + title for title in commands])
                    help_string += f"\n(Run `{PREFIX}help commandname` for in-depth explanations.)"
                    responses.append(help_string)
            elif command == "register":
                # TODO: this is lazy and bad, fix it
                args = query.split(None, 1)
                new_command = args.pop(0).lower()
                content = None
                if args:
                    content = args[0]
                response = Response.query.get(new_command)
                if response is None:
                    if not content and not message.image_url:
                        responses.append("Please provide content or an image.")
                    else:
                        response = Response(name=new_command, content=content, image_url=message.image_url)
                        db.session.add(response)
                        db.session.commit()
                        responses.append(f"Command {new_command} registered successfully.")
                else:
                    responses.append(f"Command {new_command} already registered!")
            elif command == "unregister":
                response = Response.query.get(query)
                if response is None:
                    responses.append(f"No registered command named {query}.")
                else:
                    db.session.delete(response)
                    db.session.commit()
                    responses.append(f"Command {query} unregistered.")
                """
                elif command == "stats":
                    count = Bot.query.count()
                    responses.append(f"I am currently in {count} GroupMe groups. Add me to more at https://yalebot.herokuapp.com!")
                """
            else:
                response = Response.query.get(command)
                if response is not None:
                    responses.append((response.content, response.image_url) if response.image_url else response.content)
                else:
                    try:
                        closest = difflib.get_close_matches(command, list(static_commands.keys()) + list(commands.keys()), 1)[0]
                        advice = f"Perhaps you meant {PREFIX}{closest}? "
                    except IndexError:
                        advice = ""
                    responses.append(f"Command not found. {advice}Use !help to view a list of commands.")
        if "thank" in message.text.lower() and "yalebot" in message.text.lower():
            responses.append("You're welcome, " + forename + "! :)")
    if message.sender_type == SenderType.SYSTEM:
        for option in system_commands:
            if system_commands[option].RE.match(message.text):
                responses.append(system_commands[option].response(message.text, message))
        """
        if system_commands["welcome"].RE.match(message.text):
            check_names = system_commands["welcome"].get_names_groupme(message.text)
            for check_name in check_names:
                responses.append(commands["verify"].check_user(check_name))
        """
    return responses
Exemplo n.º 6
0
def process(responses, tts_client, voice, audio_config, stream, widget):
    """Iterates through server responses and processes them.

    The responses passed is a generator that will block until a response
    is provided by the server.

    Each response may contain multiple results, and each result may contain
    multiple alternatives; for details, see https://goo.gl/tjCPAU.  Here we
    print only the transcription for the top alternative of the top result.
    """
    audio_path = "audio/"
    if not os.path.exists(audio_path):
        os.makedirs(audio_path)
    
    for response in responses:

        if get_current_time() - stream.start_time > STREAMING_LIMIT:
            stream.start_time = get_current_time()
            break
        
        if not response.results:
            continue

        # The `results` list is consecutive. For streaming, we only care about
        # the first result being considered, since once it's `is_final`, it
        # moves on to considering the next utterance.
        result = response.results[0]
        if not result.alternatives:
            continue

        if result.is_final:
            stream.is_final_end_time = stream.result_end_time
            stream.last_transcript_was_final = True

            # Display the transcription of the top alternative
            transcript = result.alternatives[0].transcript
            parsed = transcript.strip().lower()
            # print("Parsed: ", parsed)
            words = set(parsed.split())

            # Adjust time for endless streaming
            result_seconds = 0
            result_nanos = 0

            if result.result_end_time.seconds:
                result_seconds = result.result_end_time.seconds

            if result.result_end_time.nanos:
                result_nanos = result.result_end_time.nanos

            stream.result_end_time = int((result_seconds * 1000)
                                        + (result_nanos / 1000000))

            # Handles command phrases of varying length: 
            #   1 edit mode and/or 1 action

            # Find the edit mode
            command = words.intersection(commands.keys())  # Check speech input against synonyms
            # print("Command: ", command)
            if command:
                repeatables = ('undo', 'redo', 'rotate')
                command = list(command)[0]
                mode = commands[command]
                if (widget.mode != mode) or (mode in repeatables):
                    # print(len(widget.picture.history))
                    # print(widget.picture.history_pos)
                    process_word(widget, audio_path, tts_client, voice, audio_config, mode)

            # Find the action to take
            if widget.mode in edit_modes and widget.mode in actions:
                mode = widget.mode
                action = words.intersection(actions[mode].keys())
                # print("Action: ", action)
                if action: 
                    action = list(action)[0]
                    action = actions[mode][action]  # Get action keyword
                    process_word(widget, audio_path, tts_client, voice, audio_config, mode, action)
            
            # If an exit keyword is spoken, the entire program terminates
            exit_keyword = words.intersection(terminator)
            if exit_keyword:
                exit_keyword = list(exit_keyword)[0]
                widget.on_speech_recognized(exit_keyword)
                sys.exit()