Search code examples
pythonchatmessageslack

Adding attachements to slacker chat message


I'm trying to post a message using slacker python api for Slack messages I'm not able to attach a link to my messages as my code below :

    attachments = [title, link_to_events, "More details"]

    print type(attachments) # this is a list 

    slack = Slacker(slack_api_token)

    # Send a message to #general channel
    slack.chat.post_message(slack_channel, message, attachments=attachments)

In the slacker code, it looks like we are looking for a "list" type of variable:

https://github.com/os/slacker/blob/master/slacker/init.py line 241:

    # Ensure attachments are json encoded
    if attachments:
        if isinstance(attachments, list):
            attachments = json.dumps(attachments)

    return self.post('chat.postMessage',
                     data={
                         'channel': channel,
                         'text': text,
                         'username': username,
                         'as_user': as_user,
                         'parse': parse,
                         'link_names': link_names,
                         'attachments': attachments,
                         'unfurl_links': unfurl_links,
                         'unfurl_media': unfurl_media,
                         'icon_url': icon_url,
                         'icon_emoji': icon_emoji
                     })

is there a problem with my code ?

fyi : this is what i've found in the slack api documentation https://api.slack.com/custom-integrations :

{
    "text": "New Help Ticket Received:",
    "attachments": [
        {
            "title": "App hangs on reboot",
            "title_link": "http://domain.com/ticket/123456",
            "text": "If I restart my computer without quitting your app, it stops the reboot sequence.\nhttp://domain.com/ticket/123456",
        }
    ]
} 

Solution

  • All right i've found it, I need a list of dicts

    one_attachement = {
            "title": "App hangs on reboot",
            "title_link": "http://example.com/ticket/123456",
            "text": "If I restart my computer without quitting your app, it stops the reboot sequence.\nhttp://example.com/ticket/123456",
        }
    
    
    attachements = [one_attachement]
    slack.chat.post_message(slack_channel, message, attachments=attachments)