1

Basically, I want to leave open the option for any of the following commands directed at my slackbot:

@torbot

@torbot [command]

@torbot [command] [arguments]

Below is what I've been using for now, but it looks ugly. From my experience, usually when something looks ugly, it means there's likely a more intuitive way to do the same thing.

class TorbotCommand(object):
def __init__(self, input):
    self.__input = input

    # TODO: There has to be a better way..
    try:
        self.__command_string = self.__input['text'].split(' ', 1)[1].strip().lower()
    except:
        self.__command_string = None
        pass

    try:
        self.__command = self.__command_string.split(' ', 1)[0]
    except:
        self.__command = None
        pass

    try:
        self.__text = self.__command_string.split(' ', 1)[1]
    except: 
        self.__text = None
        pass

def getCommand(self): return self.__command
def getText(self): return self.__text
def getInput(self): return self.__input
Community
  • 1
  • 1
MrDuk
  • 16,578
  • 18
  • 74
  • 133

1 Answers1

6

Just split once, and test if the list is long enough:

def __init__(self, input):
    self.__input = input

    parts = input['text'].split(None, 1)
    self.__command = parts[0] if parts else None
    self.__command_string = parts[1].lower() if len(parts) > 1 else None

    self.__text = None
    if self.__command_string:
        self.__text = self.__command_string.partition(' ')[-1]

I used None as the first argument to str.split() to have it split on arbitrary whitespace; this gives you an automatic strip as well.

If you do still need to handle exceptions, do not use a blanket except: block. Catch specific exceptions only, like IndexError for an indexing expression where the list might not be long enough.

Also, I'd recommend against using __ double-underscore names. Use those only if you are aiming to have your class subclassed by 3rd-party code where it is important that the internal implementation is not accidentally affected by whatever the subclass defines.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343