Search code examples
slackslack-api

Slack api: files.upload to user channel and display as bot-user?


I am trying to create a slack command that takes params, generate image and return and image back to user, also the image upload should display as the bot user.

I follow this post: Can you upload a file to the Slack API using files.upload as a different user?

I tried creating slack app, a bot user according to it, and slack file upload api as follows:

def send_picture(channel_id, graph_details):
     sender_token = "xoxb-..." # bot-user token
     pic = {
        'file' : ('img.png', open('img.png', 'rb'), 'png')
     }
     payload={
         "title" : "Serverless App Report",
         "channels" : [channel_id]
     }
    r = requests.post("https://slack.com/api/files.upload", params=payload, files=pic)

Whenever the user do the slack command(POST with params), I can parse the channel_id to find out the sender and pass it into the channel_id into the file upload api.

Posting it into public channel is working fine. But posting it back to the user who do the command failed with the error: {"ok":false,"error":"invalid_channel","channel":"DXXXXXXX"}


Solution

  • The reason you get this error is that your bot user is apparently not a member of the private channel in which the user invoked your slash command. Therefore your app can not upload any files to it. This normal behavior and part of Slack's security architecture.

    There are 3 workarounds for this issue:

    1. You can make sure the bot user from your Slack app is added as member to all private channels where your slash command needs to work

    2. You can request every user to "install" your Slack app once. Thereby providing your app with a user specific Slack token which your app can then use to access the private channel.

    3. You can refrain from uploading files and instead reply with a message, which can include images too. A Slack app can always reply to a Slash command, no matter in which kind of channel it is issued.