【问题标题】:How to upload file using Slack API as user?如何以用户身份使用 Slack API 上传文件?
【发布时间】:2017-03-01 11:49:06
【问题描述】:

现在,通过files.upload 上传文件时使用的令牌与我的 Slack 用户帐户相关联。因此,使用此令牌执行的任何上传似乎都是由我完成的。

但是,我想指定 as_user 之类的内容(使用 chat.PostMessage 时可用),这将使上传看起来好像是由指定的 Slack 用户上传的。这可能吗?

我有这个:

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

下面是被调用的函数:

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

我确实找到了this existing question,但我完全没有找到明确的答案,可以做些什么来完成这项工作。

【问题讨论】:

    标签: python slack-api


    【解决方案1】:

    没有用于通过 API 上传和共享文件的 as_user 选项。如果您想通过 files.upload 以其他用户身份将文件上传到 Slack 频道,您有两种选择:

    1. 创建一个bot user 并使用该机器人用户的访问令牌
    2. 为此目的创建一个新的 Slack 用户(例如“slackadmin”)并使用 该用户上传文件的令牌。

    您可以通过自定义或作为 Slack 应用程序的一部分创建机器人用户。

    【讨论】:

    • 如何获取用户(不是机器人)的令牌?我一直在尝试使用 oauth,但一直失败。我需要通过脚本来完成。
    • 有两种方法: 1.让用户创建一个legacy token,然后手动给你。 2. 让用户通过 Oauth 安装您的 Slack 应用程序并以编程方式收集它。方法二是推荐的。
    猜你喜欢
    • 2022-12-07
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多