1 python bots webhooks python-requests slack-api
我正在尝试使用网络挂钩将图像发布到 Slack 频道。这个基本设置允许我将文本发布到频道,但我无法发布图像。这是我的代码:
def posting():
import requests
import json
url = 'https://webhook'
image = {'media': open('trial.jpg', 'rb')}
r = requests.post(url, files=image)
r.json
Run Code Online (Sandbox Code Playgroud)
当我发布文本时,频道中会出现一个网络钩子机器人并将其发布。我需要进一步的身份验证才能发布吗?或者是 Slack 拥有自己的上传 API 并希望我完成该操作?或者机器人无权发布图像的东西?
我在这里查看了其他一些问题,但它们似乎没有使用网络挂钩或机器人,所以我不确定我的问题是否涉及这些问题。
小智 5
您可以通过 Slack API 使用其 files.upload 方法来执行此操作: https: //api.slack.com/methods/files.upload
您将需要一个 API 身份验证令牌才能正常工作。您可以设置测试令牌或按照说明注册您的程序以获得长期令牌: https: //api.slack.com/web#basics
另外,“media”似乎不是用于文件上传的正确 json 键:
http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-文件
以下是使用请求将图像发送到通道的示例。如果您希望将图像发送给特定用户,请使用“@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')
Run Code Online (Sandbox Code Playgroud)