コード例 #1
0
def command_show(sender, other_text=''):
    """
    :param sender: Person who sent the message. This is force-fed to the
      function when called by handle_command(). Does nothing with it.

    :param other_text: String containing any other text in the message that
      was issued after the 'show' command. Compared to other list commands,
      `show` as a very simple syntax:

    "show lists ..."

    * lists is a folder containing all of the lists. While this function was
      originally designed to display a bunch of text files in a folder, it is
      also possible to look at other folders (if you know the correct path)
    * ... is text that comes after lists that will be ignored.

    :returns: The contents of the folder, or a failure message if no folder
      exists.
    """
    logging.debug('command_show() evaluated.')

    text_no_punc = list_remove_punctuation(other_text).split()
    if text_no_punc == []: path = 'lists'  # Default to directory 'lists'
    else: path = text_no_punc[0]

    path_exists = os.path.isdir(path)
    if path_exists:
        files = '\n'.join(os.listdir(path))
        response = "Here are the files stored in *{}*: \n{}".format(
            path, files)
    else:
        response = ("ಠ_ಠ  There is no directory named *{}*.".format(path))

    return response
コード例 #2
0
def command_delete(sender, other_text=''):
    """
    :param sender: Person who sent the message. This is force-fed to the
      function when called by handle_command(). Does nothing with it.

    :param other_text: String containing any other text in the message that
      was issued after the 'delete' command. Function will look for certain keywords
      based on the syntax:

    "delete ... (___) list ..."

    * [__] represent list items (things to be added to the list; e.g., 'eggs')
    * List items must be separated by designated delimiters: 'and' ',' ';'
    * ... are any words that can exist in between key words but are ignored.
    * '(__) list' (__) is the name of the list and signals to the bot to look up
      that file in the directory.

    :returns: Deletes the file if the file exists and is empty. If the file does
      not exist or is not empty, a failure message is returned.
    """
    logging.debug('command_delete() evaluated.')
    text_no_punc = list_remove_punctuation(other_text)

    if not list_basic_syntax(text_no_punc):
        return ("(⊙_☉)7 Sorry... I didn't understand that syntax."
                " Try this: 'delete my grocery list.'")
    else:
        i = text_no_punc.split().index('list')
        list_name = ' '.join(text_no_punc.split()[i - 1:i + 1])
        # Check if a file under the name '____ list.txt' exists.
        path = os.path.join('./lists/', list_name) + '.txt'
        file_exists = os.path.isfile(path)

        if file_exists:
            with open(path, mode='r') as file:
                contents = file.read()
            if contents != '':
                response = ("Your *{a}* is not empty. For safety reasons, "
                            "Make sure you *remove all items from the {a}* "
                            "before deleting it".format(a=list_name))
            else:
                os.remove(path)
                response = ("(҂◡_◡)  I've deleted your {}.".format(list_name))
        else:
            response = ("You don't have a list named *{}*.".format(list_name))

    return response
コード例 #3
0
ファイル: list_read.py プロジェクト: seantibor/challenges
def command_read(sender, other_text=''):
    """
    :param sender: Person who sent the message. This is force-fed to the
      function when called by handle_command(). Does nothing with it.

    :param other_text: String containing any other text in the message that
      was issued after the 'read' command. Function will look for certain
      keywords based on the syntax:

    "read  ... (___) list ..."

    * [__] represent list items (things to be added to the list; e.g., 'eggs')
    * List items must be separated by designated delimiters: 'and' ',' ';'
    * ... are any words that can exist in between key words but are ignored.
    * '(__) list' (__) is the name of the list and signals to the bot to look up
      that file in the directory.

    :returns: The contents of the list with each item on a new line, or a
      failure message if no file exists.
    """
    logging.debug('command_read() evaluated.')
    text_no_punc = list_remove_punctuation(other_text)

    if not list_basic_syntax(text_no_punc):
        return ("(⊙_☉)7 Sorry... I didn't understand that syntax."
                " Try this: 'read me my grocery list.'")
    else:
        i = text_no_punc.split().index('list')
        list_name = ' '.join(text_no_punc.split()[i - 1:i + 1])
        # Check if a file under the name '____ list.txt' exists.
        path = os.path.join('./lists/', list_name) + '.txt'
        file_exists = os.path.isfile(path)
    if file_exists:
        with open(path, mode='r') as file:
            list_items = str(file.read())
            logging.debug('items in file.read() in command_read(): ' +
                          list_items)
        response = "Here's what's on your *{}*: \n{}".format(
            list_name, list_items)
    else:
        response = ("You don't have a list named *{}*.".format(list_name))

    return response
コード例 #4
0
ファイル: list_remove.py プロジェクト: seantibor/challenges
def command_remove(sender, other_text=''):
    """
    :param sender: Person who sent the message. This is force-fed to the
      function when called by handle_command(). Does nothing with it.

    :param other_text: String containing any other text in the message that
      was issued after the 'add' command. Function will look for certain keywords
      based on the syntax:

    "remove [__], [__], [__] and [__] from ... (___) list ..."

    * 'remove' is required to call command_remove()
      through handle_command(), but is not actually required inside of
      command_remove.
    * [__] represent list items (things to be removed from the list;
      e.g., 'eggs'). If 'All' is supplied as the only list item, then all of the
      items are removed.
    * ',', 'and', ';' are all delimiters that will separate list items
    * 'from' signals the end of the list items. Anything before 'from' will be
      removed from the list, while everything after will be ignored.
    * ... are any words that can exist in between key words but are ignored.
    * '(__) list' (__) is the name of the list and signals to the bot to look up
      that file in the directory.

    :returns: Opens the file and removes the items from the list. Returns:

    * a message that includes the name of the items removed from the list.
    * If file is empty after deletions, mention that.
    * If no file exists under that name, provide an error message
    * If any items are not in the file, list them.
    """
    logging.debug('command_remove() evaluated.')
    text_no_punc = list_remove_punctuation(other_text)
    logging.debug('text_no_punc in command_remove(): ' + text_no_punc)

    # Check for syntax errors. If none, parse the string to get the list items
    # and the list name
    if not command_remove_correct_syntax(text_no_punc):
        return ("(⊙_☉)7 Sorry... I didn't understand that syntax."
                " Try this: 'remove ___, ___, and ___ from my ___ list.'")
    else:
        # Parse the text by splitting the string at delimiters.
        parsed = [
            s.strip() for s in re.split(DELIMITERS, text_no_punc) if s.strip()
        ]
        logging.debug('parsed in command_remove(): ' + str(parsed))
        list_items = parsed[:-1]
        # Find the word 'list' and join it to the word directly in front.
        i = parsed[-1].split().index('list')
        list_name = ' '.join(parsed[-1].split()[i - 1:i + 1])

    # Check if a file under the name '____ list.txt' exists.
    path = os.path.join('./lists/', list_name) + '.txt'
    logging.debug('path in command_remove(): ' + str(path))
    if not os.path.isfile(path):
        return "¯\_(ツ)_/¯ Sorry, *{}* doesn't exist.".format(list_name)
    elif os.path.isfile(path):
        passed, failed = command_remove_edit_file(path, list_items)

    # Return message based on conditions below.
    if passed != []:
        removed = ', '.join(passed)
        # All items were in list
        if failed == []:
            response = ("I've removed *{}* from the *{}*!".format(
                removed, list_name))
        # Some items were in the list
        else:
            not_present = ', '.join(failed)
            response = ("I've removed *{}* from your *{}*, but the following "
                        "were never in the list to start with: *{}*".format(
                            removed, list_name, not_present))
    # None of the items were in the list
    elif failed != []:
        not_present = ', '.join(failed)
        response = ("None of the items you mentioned were on your *{}*. "
                    "You asked to remove: *{}*".format(list_name, not_present))
    # Both lists are empty ('all' or 'everything' was the only list item).
    # See command_remove_edit_file())
    else:
        response = "I've removed all of the items on your {}".format(list_name)

    return response
コード例 #5
0
ファイル: list_add.py プロジェクト: seantibor/challenges
def command_add(sender, other_text=''):
    """
    **Note to future self: Implement a way to not write in duplicates**

    :param sender: Person who sent the message. This is force-fed to the
      function when called by handle_command(). Does nothing with it.

    :param other_text: String containing any other text in the message that
      was issued after the 'add' command. Function will look for certain keywords
      based on the syntax:

    "add [__], [__], [__] and [__] to ... (___) list ..."

    * 'add' is required to call command_add() through handle_command(), but is
      not actually required inside of command_add.
    * [__] represent list items (things to be added to the list; e.g., 'eggs')
    * ',', 'and', ';' are all delimiters that will separate list items
    * 'to' signals the end of the list items. Anything before 'to' will be added
      to the list, while everything after will be ignored.
    * ... are any words that can exist in between key words but are ignored.
    * '(__) list' (__) is the name of the list and signals to the bot to look up
      that file in the directory.

    :returns: Writes the list items to the specified file as a new line. Returns
      a message that includes all of the items in the list.
      If no file exists under that name, create one and provide a message that a
      new file was created.
    """
    logging.debug('command_add() evaluated.')
    text_no_punc = list_remove_punctuation(other_text)
    logging.debug('text_no_punc in command_add(): ' + text_no_punc)

    if not command_add_correct_syntax(text_no_punc):
        return ("(⊙_☉)7 Sorry... I didn't understand that syntax."
                " Try this: 'add eggs, milk, and cheese to my grocery list.'")
    else:
        # Parse the text by splitting the string at delimiters.
        parsed = [
            s.strip() for s in re.split(DELIMITERS, text_no_punc) if s.strip()
        ]
        logging.debug('parsed in command_add(): ' + str(parsed))
        list_items = parsed[:-1]
        # Find the word 'list' and join it to the word directly in front.
        i = parsed[-1].split().index('list')
        list_name = ' '.join(parsed[-1].split()[i - 1:i + 1])

    # Check if a file under the name '____ list.txt' exists.
    path = os.path.join('./lists/', list_name) + '.txt'
    file_existed = os.path.isfile(path)

    # Write list items to file
    with open(path, mode='a') as file:
        for item in list_items:
            file.write(item + '\n')

    # Return response based on whether list existed before or not.
    if file_existed:
        response = "I've added these items to your *{}*: *{}*!".format(
            list_name,
            str(list_items)[1:-1])
    else:
        response = (
            "You don't have a list named *{}*. "
            "Don't worry - I've made one and added these items: *{}* \n"
            "If this was a mistake, use *remove* and then "
            "*delete*.".format(list_name,
                               str(list_items)[1:-1]))
    return response