Skip to main content
 首页 » 编程设计

python之将附件添加到 slack 聊天消息

2025年05月04日15xxx_UU

我正在尝试使用用于 Slack 消息的 slacker python api 发布消息 我无法将链接附加到我的消息,因为我的代码如下:

    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) 

在 slacker 代码中,看起来我们正在寻找一个“列表”类型的变量:

https://github.com/os/slacker/blob/master/slacker/init.py 第 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 
                     }) 

我的代码有问题吗?

仅供引用:这是我在 slack api 文档 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", 
        } 
    ] 
}  

请您参考如下方法:

好的,我已经找到了, 我需要一个 list 的 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)