How to upload file using Slack API as user?

别来无恙 提交于 2020-03-03 03:05:52

问题


Right now, the token used when uploading files via files.upload is associated with my Slack user account. So any uploads performed using this token appears to have been made by me.

However, I'd like to specify something like as_user (which is available when using chat.PostMessage), which will make the upload appear as if it was uploaded by specified Slack user. Is this possible?

I have this:

 upload_file(filepath='/path/to/file.jpg',
             channels='#uploads',
             title='my image',
             initial_comment='pls give me some feedback!')

And here's the function being called:

import os
import requests

TOKEN = your_token_here

def upload_file(
        filepath,
        channels,
        filename=None,
        content=None,
        title=None,
        initial_comment=None):
    """Upload file to channel

    Note:
        URLs can be constructed from:
        https://api.slack.com/methods/files.upload/test
    """

    if filename is None:
        filename = os.path.basename(filepath)

    data = {}
    data['token'] = TOKEN
    data['file'] = filepath
    data['filename'] = filename
    data['channels'] = channels

    if content is not None:
        data['content'] = content

    if title is not None:
        data['title'] = title

    if initial_comment is not None:
        data['initial_comment'] = initial_comment

    filepath = data['file']
    files = {
        'file': (filepath, open(filepath, 'rb'), 'image/jpg', {
            'Expires': '0'
        })
    }
    data['media'] = files
    response = requests.post(
        url='https://slack.com/api/files.upload',
        data=data,
        headers={'Accept': 'application/json'},
        files=files)

    return response.text

I did find this existing question, but I don't find the answer clear at all on what could be done to make this work.


回答1:


There is no as_user option for uploading and sharing files via API. If you want to upload files to a Slack channel as a different user via files.upload you have two options:

  1. Create a bot user and use the access token of that bot user
  2. Create a new Slack user for that purpose (e.g. "slackadmin") and use the token of that user to upload the file.

You can create bot users through customization or as part of a Slack app.



来源:https://stackoverflow.com/questions/42530945/how-to-upload-file-using-slack-api-as-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!