Get public permalink to Slack attachments with files.sharedPublicURL

Andre Dubovskiy

We're working on a Slack bot that lets users clip message threads into markdown files, which are then uploaded to Firebase.

We had a bit of trouble handling attachments in messages and found a nifty feature of the Slack API that lets you export their URLs for public access. Now we can pass a direct reference to the original attachments in our exported markdown without having to host them ourselves.

Let's go over how to set it up.

💡
Slack's sharedPublicURL requires User tokens. You probably have only configured your app for Bot tokens, so make note of this.

To get your User token, first, open the Slack API Dashboard and go to the OAuth section where you'll add files:write under User Token Scopes.

Next, copy the User OAuth Token from the section above the Scopes.

Set the User token as an environment variable.

export SLACK_USER_TOKEN=<slack-user-token>

Then in app.py (or related), you can find the file object and publicize the url in the Slack API like this:

import os
from slack_bolt import App

# Slack App
app = App(
    token=os.environ.get("SLACK_BOT_TOKEN"),
    user_token=os.environ.get("SLACK_USER_TOKEN),
    signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)

def get_conversation_thread(client, channel, ts):
    replies = client.conversations_replies(channel=channel, ts=ts)
    ...
    for message in replies["messages"]:
        ...

        if "files" in message:
            permalinksToAttachments = ""
            for file in message["files"]:
                if not file['public_url_shared']:
                    app.client.files_sharedPublicURL(file=file["id"], user_token)
                permalinkToAttachment = "{file["permalink_public"]}"
            ...
    return messages

Note how we're reading the SLACK_USER_TOKEN from the env variables. These are the key lines:

if not file['public_url_shared']:
	app.client.files_sharedPublicURL(file=file["id"], user_token)
permalinkToAttachment = '{file["permalink_public"]}'
💡
Note that a file can only be given a shared public URL once. If you attempt to call files_sharedPublicURL on a file that has already been made public once, you'll receive an error.

Subscribe to Frindle Blog

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe