Ejemplo n.º 1
0
    def test_parse_command(self):
        from parser import parse_command

        sender = 'foo'
        host = '@host.bar'

        user_command = ':{nick}!~{host} {action} {args}'
        server_command = '{action} {args}'

        with patch('parser.get_sender') as get_sender:
            get_sender.return_value = sender

            self.assertDictEqual(parse_command(user_command.format(nick=sender,
                host=sender + host, action='JOIN', args='#chan')),
                {'sender': sender, 'action': 'JOIN', 'arguments': '',
                'action_args': ['#chan']})

            self.assertDictEqual(parse_command(user_command.format(nick=sender,
                host=sender + host, action='KICK', args='#chan user :reason')),
                {'sender': sender, 'action': 'KICK', 'arguments': 'reason',
                'action_args': ['#chan', 'user']})

            self.assertDictEqual(parse_command(user_command.format(nick=sender,
                host=sender + host, action='QUIT', args=':reason')),
                {'sender': sender, 'action': 'QUIT', 'arguments': 'reason',
                'action_args': []})

            self.assertDictEqual(parse_command(server_command.format(
                action='PING', args=':[email protected]')), {'action': 'PING',
                'arguments': '*****@*****.**', 'action_args': [],
                'sender': ''})
Ejemplo n.º 2
0
    def test_parse_command(self):
        from parser import parse_command

        sender = 'foo'
        host = '@host.bar'

        user_command = ':{nick}!~{host} {action} {args}'
        server_command = '{action} {args}'

        with patch('parser.get_sender') as get_sender:
            get_sender.return_value = sender

            self.assertDictEqual(
                parse_command(
                    user_command.format(nick=sender,
                                        host=sender + host,
                                        action='JOIN',
                                        args='#chan')), {
                                            'sender': sender,
                                            'action': 'JOIN',
                                            'arguments': '',
                                            'action_args': ['#chan']
                                        })

            self.assertDictEqual(
                parse_command(
                    user_command.format(nick=sender,
                                        host=sender + host,
                                        action='KICK',
                                        args='#chan user :reason')), {
                                            'sender': sender,
                                            'action': 'KICK',
                                            'arguments': 'reason',
                                            'action_args': ['#chan', 'user']
                                        })

            self.assertDictEqual(
                parse_command(
                    user_command.format(nick=sender,
                                        host=sender + host,
                                        action='QUIT',
                                        args=':reason')), {
                                            'sender': sender,
                                            'action': 'QUIT',
                                            'arguments': 'reason',
                                            'action_args': []
                                        })

            self.assertDictEqual(
                parse_command(
                    server_command.format(action='PING',
                                          args=':[email protected]')), {
                                              'action': 'PING',
                                              'arguments': '*****@*****.**',
                                              'action_args': [],
                                              'sender': ''
                                          })
Ejemplo n.º 3
0
def main():
    """
    Creates and instance of PetermanBot, then continuously has it
    handle events and scan the network for officers.
    """

    bot_token = config['bot_key']
    bot_id = config['bot_id']

    slack_client = MySlackClient(bot_token, bot_id)
    start_pb_timers(pb)

    while True:
        user_id, channel_id, user_input = slack_client.get_user_input()
        if channel_id:
            command_text, args, kwargs = parse_command(user_input)

            if not validate_command(command_text):
                message = "Invalid command. Type `help` for help."
            elif not validate_command_permissions(command_text, user_id):
                message = "You do not have permissions to use that command."
            else:
                command = command_mapping[command_text]()
                message = command.action()

            slack_client.send_user_message(channel_id, message)
            if command_text == kill_command_name and validate_command_permissions(command_text, user_id):
                os._exit(0)
Ejemplo n.º 4
0
def repl():
    state = REPLState()
    print((bold("Google Drive Terminal v0.0.1")))
    driveapi = driveinit()
    identifier = bold(green('drive:'))
    completer = AutoCompleter(["cd", "ls", "dl", "download"])
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    while True:
        try:
            command = input("{}{}$ ".format(identifier,
                                            bold(blue(state.get_pwd()))))
            parse_command(command, state, driveapi)
        except KeyboardInterrupt:
            print()
            continue
        except EOFError:
            print()
            exit()
        except Exception as e:
            if DEVELOPMENT_MODE:
                raise e
            else:
                print(e)
Ejemplo n.º 5
0
def run(socket, channels, cmds, nick, logfile):
    # buffer for some command received
    buff = ""

    while len(channels):
        receive = socket.recv(4096)
        buff = buff + receive
        response = ""

        if receive:
            log_write(
                logfile, get_datetime()["time"], " <> ", receive + ("" if "\n" == receive[len(receive) - 1] else "\n")
            )

        if -1 != buff.find("\n"):
            # get a full command from the buffer
            command = buff[0 : buff.find("\n")]
            buff = buff[buff.find("\n") + 1 :]

            # command's components after parsing
            components = parser.parse_command(command)

            if "PING" == components["action"]:
                response = []
                response.append("PONG")
                response.append(":" + components["arguments"])

            elif "PRIVMSG" == components["action"] and "!" == components["arguments"][0]:
                # search in commands list only if the message from the user
                # starts with an exclamation mark

                pos = components["arguments"].find(" ")
                if -1 == pos:
                    pos = len(components["arguments"])

                # get the command issued to the bot without the exclamation mark
                cmd = components["arguments"][1:pos]
                response = run_cmd(socket, cmd, components, cmds)

            elif "KICK" == components["action"] and nick == components["action_args"][1]:
                channels.remove(components["action_args"][0])

            elif "QUIT" == components["action"] and -1 != components["arguments"].find("Ping timeout: "):
                channels[:] = []

            send_response(response, send_to(command), socket, logfile)

            buff = ""
Ejemplo n.º 6
0
def main() -> None:
    parser = argparse.ArgumentParser(description="Python with pipes")
    parser.add_argument("command", help="the pypthon command")
    parser.add_argument("-s", "--show-python", help="show python code generated", action="store_true")
    parser.add_argument("-i", "--import", help="module to import eg: -i 'requests' -i 'numpy'", default=[], action="append")
    parser.add_argument("-d", "--dry-run", help="don't run python code", action="store_true")
    parser.add_argument("-e", "--environment", help="show variables excluding -i imports in environment", action="store_true")
    args = parser.parse_args()
    python = parse_command(args.command)
    if args.show_python or args.dry_run:
        print(python)
    code = '\n'.join([
        get_user_custom_setup(),
        python
    ])
    for module in getattr(args, "import"):
        import_string = f"import {module}"
        if not args.dry_run:
            exec(import_string, globals())
    if args.dry_run or args.environment:
        pprint(sorted(v for v in globals() if v[:1] != "_"))
    if not args.dry_run:
        exec(code)
Ejemplo n.º 7
0
def run(socket, channels, cmds, nick, logfile):
    # buffer for some command received
    buff = ''
    num_workers = sum(len(v) for k, v in cmds.iteritems())

    #TODO: what happens if I use all the workers?

    #TODO: don't let commands to run for more than one minute

    with futures.ProcessPoolExecutor(max_workers=num_workers) as executor:
        while len(channels):
            receive = socket.recv(4096)
            buff = buff + receive
            response = ''

            if receive:
                log_write(logfile, get_datetime()['time'], ' <> ', receive + \
                    ('' if '\n' == receive[len(receive)-1] else '\n'))

            if -1 != buff.find('\n'):
                # get a full command from the buffer
                command = buff[0:buff.find('\n')]
                buff = buff[buff.find('\n') + 1:]

                # command's components after parsing
                components = parser.parse_command(command)
                to = send_to(command)

                if 'PING' == components['action']:
                    response = []
                    response.append('PONG')
                    response.append(':' + components['arguments'])

                elif 'PRIVMSG' == components['action']:
                    if '!' == components['arguments'][0]:
                        # a command from a user only makes sense if it starts
                        # with an exclamation mark

                        pos = components['arguments'].find(' ')
                        if -1 == pos:
                            pos = len(components['arguments'])

                        # get the command issued to the bot without the "!"
                        cmd = components['arguments'][1:pos]

                        callable_cmd = get_cmd(cmd, cmds['user'], logfile)
                        if callable_cmd:
                            run_cmd(socket, executor, to, callable_cmd,
                                    components, logfile)
                        else:
                            callable_cmd = get_cmd(cmd, cmds['core'], logfile)

                            if callable_cmd:
                                try:
                                    response = callable_cmd(socket, components)
                                except Exception as e:
                                    response = err.C_EXCEPTION.format(
                                        callable_cmd.__name__)

                                    log_write(logfile, response, ' <> ',
                                              str(e) + '\n')

                    # run auto commands
                    for cmd in config.cmds['auto']:
                        callable_cmd = get_cmd(cmd, cmds['auto'], logfile)
                        if callable_cmd:
                            run_cmd(socket, executor, to, callable_cmd,
                                    components, logfile)

                elif 'KICK' == components['action'] and \
                    nick == components['action_args'][1]:
                    channels.remove(components['action_args'][0])

                elif 'QUIT' == components['action'] and \
                        -1 != components['arguments'].find('Ping timeout: '):
                    channels[:] = []

                # this call is still necessary in case that a PONG response or a
                # core command response should be sent, every other response is
                # sent when the futures finish working from their respective
                # thread
                send_response(response, to, socket, logfile)

                buff = ''
Ejemplo n.º 8
0
def run(socket, channels, cmds, nick):
    # buffer for some command received
    buff = ''
    num_workers = sum(len(v) for k, v in cmds.iteritems())

    # TODO: what happens if I use all the workers?

    # TODO: don't let commands to run for more than one minute

    with concurrent.futures.ProcessPoolExecutor(max_workers=num_workers) as executor:
        while len(channels):
            receive = socket.recv(4096)
            buff = buff + receive
            response = ''

            if receive:
                logging.debug(receive + \
                    ('' if '\n' == receive[len(receive)-1] else '\n'))

            if -1 != buff.find('\n'):
                # get a full command from the buffer
                command = buff[0 : buff.find('\n')]
                buff = buff[buff.find('\n')+1 : ]

                # command's components after parsing
                components = parser.parse_command(command)
                to = send_to(command)

                if 'PING' == components['action']:
                    response = []
                    response.append('PONG')
                    response.append(':' + components['arguments'])

                elif 'PRIVMSG' == components['action']:
                    if '!' == components['arguments'][0]:
                        # a command from a user only makes sense if it starts
                        # with an exclamation mark

                        pos = components['arguments'].find(' ')
                        if -1 == pos:
                            pos = len(components['arguments'])

                        # get the command issued to the bot without the "!"
                        cmd = components['arguments'][1:pos]

                        callable_cmd = get_cmd(cmd, cmds['user'])
                        if callable_cmd:
                            run_cmd(socket, executor, to, callable_cmd,
                                    components)
                        else:
                            callable_cmd = get_cmd(cmd, cmds['core'])

                            if callable_cmd:
                                try:
                                    response = callable_cmd(socket, components)
                                except Exception as e:
                                    response = err.C_EXCEPTION.format(
                                    callable_cmd.__name__)

                                    logging.error(str(e))

                    # run auto commands
                    for cmd in config.cmds['auto']:
                        callable_cmd = get_cmd(cmd, cmds['auto'])
                        if callable_cmd:
                            run_cmd(socket, executor, to, callable_cmd,
                                    components)

                elif 'KICK' == components['action'] and \
                    nick == components['action_args'][1]:
                        channels.remove(components['action_args'][0])

                elif 'QUIT' == components['action'] and \
                        -1 != components['arguments'].find('Ping timeout: '):
                    channels[:] = []

                # this call is still necessary in case that a PONG response or a
                # core command response should be sent, every other response is
                # sent when the futures finish working from their respective
                # thread
                send_response(response, to, socket)

                buff = ''
Ejemplo n.º 9
0
        time.sleep(float(polling_time))
        continue

    # Test the HTTP response code.
    # Success.
    if request.status_code == 200:
        logger.debug("Message queue " + bot_name + " found.")

        # Extract the user command.
        user_command = json.loads(request.text)
        user_command = user_command["command"]
        user_command = clean_up_user_command(user_command)
        logger.debug("Value of user_command: " + str(user_command))

        # Parse the user command.
        parsed_command = parser.parse_command(user_command)

        # If the parsed command comes back None (i.e., it wasn't well formed)
        # throw an error and bounce to the top of the loop.
        if not parsed_command:
            time.sleep(float(polling_time))
            continue

        # If the user is requesting help, assemble a response and send it back
        # to the server's message queue.
        if parsed_command == "help":
            reply = "My name is " + bot_name + " and I am an instance of " + sys.argv[0] + ".\n\n"
            if user_text:
                reply = reply + user_text + "\n\n"
            reply = reply + "I am a bot which interfaces with a Shaarli instance to run searches and send back results.  I am interfaced with the following Shaarli instance: " + shaarli_url + "\n\n"
            reply = reply + "To run a search, send me a message that looks something like this:\n\n"
Ejemplo n.º 10
0
    except:
        logging.warning("Connection attempt to message queue timed out or failed.  Going back to sleep to try again later.")
        time.sleep(float(polling_time))
        continue

    # Test the HTTP response code.
    # Success.
    if request.status_code == 200:
        logger.debug("Message queue " + bot_name + " found.")

        # Extract the command.
        command = json.loads(request.text)
        command = command["command"]

        # Parse the command.
        command = parser.parse_command(command)
        logger.debug("Parsed command: " + str(command))

        # If the command was empty, return to the top of the loop.
        if not command:
            logger.debug("Empty command.")
            time.sleep(float(polling_time))
            continue

        if command == "unknown":
            message = "I didn't recognize that command."
            send_message_to_user(message)
            continue

        # If the user is requesting online help...
        if command == "help":
Ejemplo n.º 11
0
Archivo: bot.py Proyecto: samhal/frendo
 def respond_to_privmsg(self, msg):
     # check if a command request was made
     command = parse_command(msg)
     if command:
         # execute the command in a new thread
         start_new_thread(self.serve_command, (command, msg,))