通过 API 向 Slack 发送多个文件

Pau*_*ado 6 slack-api slack

根据 Slack 的文档,每次只能通过 API 发送一个文件。方法是这样的:https : //api.slack.com/methods/files.upload

使用 Slack 的桌面和 Web 应用程序,我们可以一次发送多个文件,这很有用,因为文件被分组,当我们有多个具有相同上下文的图像时有助于可视化。请参阅下面的示例:

在此处输入图片说明

你们知道是否可以通过 API 一次发送多个文件或以某种方式实现与上图相同的结果?

提前致谢!

小智 7

这是另一个答案中推荐的过程在 python 中的实现

def post_message_with_files(message, file_list, channel):
    import slack_sdk

    SLACK_TOKEN = "slackTokenHere"
    client = slack_sdk.WebClient(token=SLACK_TOKEN)
    for file in file_list:
        upload = client.files_upload(file=file, filename=file)
        message = message + "<" + upload["file"]["permalink"] + "| >"
    out_p = client.chat_postMessage(channel=channel, text=message)


post_message_with_files(
    message="Here is my message",
    file_list=["1.jpg", "1-Copy1.jpg"],
    channel="myFavoriteChannel",
)
Run Code Online (Sandbox Code Playgroud)


Nik*_*aum 6

使用新推荐的Python解决方案client.files_upload_v2(于2022年12月21日在slack-sdk-3.19.5上测试):

import slack_sdk


def slack_msg_with_files(message, file_uploads_data, channel):
    client = slack_sdk.WebClient(token='your_slack_bot_token_here')
    upload = client.files_upload_v2(
        file_uploads=file_uploads_data,
        channel=channel,
        initial_comment=message,
    )
    print("Result of Slack send:\n%s" % upload)


file_uploads = [
    {
        "file": path_to_file1,
        "title": "My File 1",
    },
    {
        "file": path_to_file2,
        "title": "My File 2",
    },
]
slack_msg_with_files(
    message='Text to add to a slack message along with the files',
    file_uploads_data=file_uploads,
    channel=SLACK_CHANNEL_ID  # can be found in Channel settings in Slack. For some reason the channel names don't work with `files_upload_v2` on slack-sdk-3.19.5
)
Run Code Online (Sandbox Code Playgroud)

(一些额外的错误处理不会造成伤害)


Rom*_*kov 5

我遇到了同样的问题。但我试图用几个 pdf 文件撰写一封邮件。

我是如何解决这个任务的

  1. 上传文件而不设置channel参数(这会阻止发布)并从响应中收集永久链接。请检查文件对象引用。https://api.slack.com/types/file。通过“files.upload”方法,您只能上传一个文件。因此,您需要根据要上传的文件多次调用此方法。
  2. 使用 Slack markdown 撰写消息<{permalink1_from_first_step}| ><{permalink2_from_first_step}| >- Slack 解析链接并自动重新格式化消息

  • 如果人们对此有疑问,我发现这在使用 Block 工具包的 Markdown 消息块中不起作用 - 它仅适用于使用 [消息有效负载](https://api 中的 `text` 参数发送的 Markdown 消息.slack.com/reference/messaging/payload) (3认同)
  • 请注意,“|”后面的空格很重要,否则完整的 URL 将显示在邮件正文以及附加文件中。 (2认同)