Search code examples
pythonpython-3.xbotsslackslack-api

Getting additional input from SlackClient using python


One of the issues is I’m running into is getting additional data from a command in slack. I️ don’t want to use Slash commands because I️ can’t expose my localhost to the world.

Example:

@mybot do

Will return, let’s say “I’m doing something”. However I️ want to be able to do something like

@mybot do 2

Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I️ have found where I️ can make it match the exact “do” command, though I️ can’t get it to read the follow on data. I️ was following this tutorial. Any help will be great.

if you see weird symbols it’s because I’m doing this from an iPhone and I️ have that stupid bug where the turns I️ (eye) into I️


Solution

  • You need to use regular expressions to extract arguments from text. I hope this will help.

    import re
    
    
    def handle_command(command, channel):
        response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
                   "* command with numbers, delimited by spaces."
    
        match = re.match("do (?P<arg>\S+)", command)
        if match:
            arg = match.groupdict('arg')
            response = "Wow! My argument is: " + arg
    
        slack_client.api_call("chat.postMessage", channel=channel,
                              text=response, as_user=True)