Search code examples
pythonslackslack-api

Python - Adding Links in Slack API


Currently I have a Python Script sending a message to slack. I want to add in extra links but cant figure out how. This is my current code.

def post_slack():
    """Post slack message."""
    try:
        token = 'xoxp-67503713541-67496795984-216701772021-c23bdfbe9635f1f63a4c802697147dfc'
        slack = Slacker(token)

        obj = slack.chat.post_message(
            channel='#dataworksapp',
            as_user= 'false',
            username = 'DataWorksBot',
            attachments=[
        {
            "color": "033E96",
            "title": "Pressure Transducer Weekly Information",
            "title_link": "https://console.cloud.google.com/storage/browser/firebase_results/?project=dataworks-356fa",
            "author_name": "Master Table",
            "author_link": "https://bigquery.cloud.google.com/table/dataworks-356fa:FirebaseArchive.PT_MasterTable?tab=preview",
            "text": "https://bigquery.cloud.google.com/table/dataworks-356fa:FirebaseArchive.PT_MasterTable?tab=preview",
            "fields": [
                {
                    "title": "Amount Used:",
                    "value": "countPTserial1",
                    "short": 'true'
                },{
                    "title": "Distinct Device ID's:",
                    "value": "countPTid1",
                    "short": 'true'
                },{
                    "title": "Total Connection Time (hr):",
                    "value": "sumPTct2",
                    "short": 'true'
                }
            ]

I have not been able to find any other field categories that would be similar to "author_link" that I could set equal to a link. I can set "text" equal to a link but if I were to do it this way I would prefer to have the link just as a single word instead of the whole ugly link being sent in the message.

Also, I can not set the link equal to a variable and then set "text" equal to that variable. When I do this is still shows the whole link. Thanks for the help!


Solution

  • I see a couple of options here. In the text field you can change the display of your link by wrapping it in < > symbols and adding a | delimiter:

    "text": "Click me: <https://foo.com|foo>"

    Which would display as "Click me: foo"

    Or you could create additional fields for each link like so:

    "fields": [
                {
                    "title": "Link 1",
                    "value": "<http://foo.com|foo>",
                    "short": false
                },
                                {
                    "title": "Link 2",
                    "value": "<http://bar.com|bar>",
                    "short": false
                }
            ]