通过 python 脚本寻找 post 长文本的方法

Looking for approach to post long text to slack through python script

我在 python 中编写了一个代码来从数据库中获取大量(80 行)数据,现在我想 post 通过 webhook 将这些数据放在 slack 中。我尝试 post 直接读取数据,但它对我不起作用,所以我决定将数据保存在 txt/.png 文件中,post 将其保存在 slack

在 report.txt 文件中保存数据后,我在 python 中尝试了以下代码,但它对我没有帮助

headers = {
    'Content-type': 'application/json',
}

data = open('\results\report.txt')

response = requests.post('https://jjjjjjj.slack.com/services/mywebhook', headers=headers, data=data)

请与我分享 Curl 命令,它适合 python 脚本到 post 松弛的附件,或者请建议我更好的方法 post 超过 50 行的数据放松

我建议将长文本上传为文本文件。这样 Slack 会自动将其格式化为预览,用户可以单击它查看全部内容。

要上传文件,您需要使用 files_upload API 方法。有了它,您还可以在上传时包含一条初始消息。

这是一个使用标准 Slack 库的示例。在这里,我正在从文件中读取数据,但您当然会改用您的数据:

import slack
import os

# init slack client with access token
slack_token = os.environ['SLACK_TOKEN']
client = slack.WebClient(token=slack_token)

# fetch demo text from file
with open('long.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# upload data as file
response = client.files_upload(    
    content=text,
    channels='general',
    filename='long.txt',
    title='Very long text',
    initial_comment='Here is the very long text as requested:'
)
assert response['ok']

诀窍是使用 content 而不是 file 来传递数据。如果您使用 file,API 将尝试从您的文件系统加载文件。

下面的代码对我来说很好..... :)


headers = { 'Authorization': 'Bearer xxxx-XXXXX-XXXXX', #Bot Token } 

files = { 
   'file': ('LocationOfthefile\report.txt', open('LocationOfthefile\report.txt', 'rb')), 
   'initial_comment': (None, 'Some Text For Header'), 
   'channels': (None, 'Channel_Names'),
 } 

response = requests.post('slack.com/api/files.upload', headers=headers, files=files)