基本上,我希望为以下针对slackbot的命令保留选项:
@torbot
@torbot [command]
@torbot [command] [arguments]
下面是我一直在用的,但是看起来很难看。根据我的经验,通常当事情看起来很难看时,这意味着可能有更直观的方法来做同样的事情。在
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
只需将拆分一次,然后测试列表是否足够长:
我使用
None
作为str.split()
的第一个参数,以便在任意空格上拆分它;这也为您提供了一个自动剥离。在如果您仍然需要处理异常,请使用blanket
except:
块。只捕获特定的异常,如IndexError
对于列表可能不够长的索引表达式。在另外,我建议不要使用
__
双下划线名称。只有当你的目标是让你的类被第三方代码子类化时,才使用这些方法,这很重要,即内部实现不会意外地受到子类定义的任何影响。在相关问题 更多 >
编程相关推荐