Using python decorators for registration


Using decorators for registration

Using python decorators for registering command for a help-function in a slackbot. (with example)

This implementation uses a global var as database for the commands.

A decorator is run at import-time and basicly returns the new function to run. A decorator with arguments runs a decorator factory which returns a decorator, and then the decorator is run.
The return func on this code is the definition of what will run on every call. The cmds_reg.add() is only run once on import-time. All actual calls to show_help will do a call to func which happens to be show_help()

cmds_reg is a set of listscontaining the command and the help-text for that command. Then the help-function simply iterates over the list sorted on cmd and displays a formated list of cmd and helptext

Final Code

cmds_reg = set()

def help_command(cmd, helptext):
    def decorate(func):
        cmds_reg.add((cmd, helptext))
        return func
    return decorate

@help_command("help", "displays all commands")
@respond_to('help')
def show_help(message):
    out = ("SlackBot is still beta,\n"
        "This is a list of my commands:\n```")
    for c, h in sorted(cmds_reg, key=itemgetter(0)):  # Sort on 'cmd'
        out += f"{c:15} - {h}\n"
    out += "```"
    message.react('+1')
    return message.reply(out)