Can't attach uploaded file to message using slack api via python

Viewed 1032

I'm trying to upload a local file I have to slack, and then attach it to a message that I am sending, but when I run my script I just get the message text, no file. Any help would be appreciated.

Thanks.

client = slack_sdk.WebClient(token=SLACK_TOKEN)
response=client.files_upload(file='1.jpg')
payoff=response['file']['permalink']
attachment='[{"text": "r", "image_url": "'+payoff+'"}]'
client.chat_postMessage(channel='#testChannel', text="Sample Text", username='Bot name', attachment=attachment, icon_emoji=':emoji:')
2 Answers

So this is the best solution I've found to date, and it supports any file type, and it doesn't need to be supported.

def postMessageWithFiles(message,fileList,channel):
    import slack_sdk
    SLACK_TOKEN = "slackTokenHere"
    client = slack_sdk.WebClient(token=SLACK_TOKEN)
    for file in fileList:
        upload=client.files_upload(file=file,filename=file)
        message=message+"<"+upload['file']['permalink']+"| >"
    outP = client.chat_postMessage(
        channel=channel,
        text=message
    )
postMessageWithFiles(
    message="Here is my message",
    fileList=["1.jpg", "1-Copy1.jpg"],
    channel="myFavoriteChannel",
)

This is pretty much the method outlined here Send multiple files to Slack via API

I do it like this:

client.chat_postMessage(channel=channel_id, text="Image", blocks=[{"type": "image", "image_url": photo, "alt_text": "Image"}])

but of course this requires the photo to be hosted somewhere. Slack support told me that I can't use a file ID or anything else like that here: https://github.com/slackapi/bolt-python/issues/305

Related