2

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:')
xanatos
  • 170
  • 1
  • 8

2 Answers2

2

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

xanatos
  • 170
  • 1
  • 8
0

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

Alexei Masterov
  • 382
  • 2
  • 10
  • See my post below. I think I found a solution that gets around the issue in that github post – xanatos Jun 23 '21 at 20:24
  • that's a good solution, with one caveat: you solution uploads a file every single time. I considered that, but decided against it, because I am going to be sending it to thousands of users, which means thousands of copies of the same file in the slack workspace. Instead, I upload the file once, cache the permalink, and then just send that to the users. But if you are only sending images, the solution I gave is cleaner because it doesn't include the link – Alexei Masterov Jun 25 '21 at 16:01