Search code examples
pythonpython-3.xslack

Parsing domain from Slack message


What is the best way to parse the domain from a Slack message? I have a Slack bot that is used to perform lookups on any hostname that is provided. When the bot receives the payload from Slack the domain is in this format: <http://example.com|example.com>. For this application I simply need example.com.

One method to parse this would be to split the string using the '|' character and removing the "< >" characters and simply use the 2nd element.

msg = slack_response
strip1 = msg.replace(">", "")
strip2 = strip1.replace("<", "")

str_arr = strip2.split("|")

domain = str_arr[1]

Are there any better methods/libraries that can be used to parse the domain out? The bot will not always receive a domain and it can sometimes be in the form of an IP as well such as 8.8.8.8. I would prefer to perform this in a way that can deal for both scenarios.


Solution

  • You could use regex but since the response from slack is predictable I think it's probably overkill.

    If you wanted a one liner you could do

    msg.split("|")[-1][:-1]
    

    However, because readability counts I would recommend something like

    start = msg.find("|") + 1
    stop = msg.find{">")
    domain = msg[start:stop]