slack api 通过 python 请求库调用

slack api calls through python request library

我正在通过 python 库 slackclient 进行 slack api 调用,它是 slack api 的包装器。但是,在某些情况下,我还需要使用 url 和 get/post 方法进行常规 api 调用。我试图通过我的机器人打开与另一个用户的直接消息通道。文档 - https://api.slack.com/methods/im.open 对 "Present these parameters as part of an application/x-www-form-urlencoded querystring or POST body. application/json is not currently accepted."

现在python,我可以写了,

url = 'https://slack.com/api/im.open'
    headers = {'content-type':'x-www-form-urlencoded'}
    data = {'token':BOT_TOKEN, 'user':user_id, 'include_locale':'true','return_im':'true'}
    r= requests.post(url,headers,data )
    print r.text 

我收到的消息是{"ok":false,"error":"not_authed"}

我知道消息是 "not authed" 尽管我使用了我的 bot 令牌和另一个用户 ID,但我的直觉是我发送的请求格式错误,因为我只是以某种方式编写它来阅读文档。我不确定如何准确发送这些请求。

有什么帮助吗?

requests.post 中的第二个参数用于 data,因此在您的请求中,您实际上是在发布 headers 字典。如果你想使用 headers 你可以按名称传递参数。

r= requests.post(url, data, headers=headers)

然而,在这种情况下这不是必需的,因为 'x-www-form-urlencoded' 是发布表单数据时的默认值。

因为 Content-Type header 是 x-www-form-urlencoded 以字典形式发送数据不起作用。你可以尝试这样的事情。

import requests

url = 'https://slack.com/api/im.open'
headers = {'content-type': 'x-www-form-urlencoded'}
data = [
 ('token', BOT_TOKEN),
 ('user', user_id),
 ('include_locale', 'true'),
 ('return_im', 'true')
]

r = requests.post(url, data, **headers)
print r.text