我正在尝试使用网络 Hook 将图像发布到 Slack channel 。这个基本设置允许我向 channel 发布文本,但我无法发布图像。这是我的代码:
def posting():
import requests
import json
url = 'https://webhook'
image = {'media': open('trial.jpg', 'rb')}
r = requests.post(url, files=image)
r.json
当我发布文本时,网络 Hook 机器人会出现在 channel 中并发布它。我需要进一步的身份验证才能发布吗?还是 Slack 有自己的上传 API 并希望我通过它?或者机器人无权发布图片的东西?
我在这里查看了其他一些问题,但它们似乎没有使用网络 Hook 或机器人,所以我不确定我的问题是否涉及这些问题。
最佳答案
您可以使用他们的 files.upload 方法通过 Slack API 执行此操作:https://api.slack.com/methods/files.upload
您需要一个 API 授权 token 才能正常工作。您可以设置测试 token 或按照说明注册您的程序以获得长期 token :https://api.slack.com/web#basics
此外,'media' 似乎不是用于文件上传的正确 json 键:
http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
这是一个使用请求将图像发送到 channel 的示例。如果您希望将图像发送给特定用户,请使用“@username”。我已经包括了内容类型和标题,但没有它们它也应该工作。 这将打印来自 Slack 的响应。
import requests
def post_image(filename, token, channels):
f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})}
response = requests.post(url='https://slack.com/api/files.upload', data=
{'token': token, 'channels': channels, 'media': f},
headers={'Accept': 'application/json'}, files=f)
return response.text
print post_image(filename='path/to/file.png', token='xxxxx-xxxxxxxxx-xxxx',
channels ='#general')
关于python - 无法使用 Python 请求通过网络 Hook 将图像发布到 Slack channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283111/