繁体   English   中英

通过python请求库的松弛api调用

[英]slack api calls through python request library

我正在通过python库slackclient进行slack api调用,这是slack api的包装。 但是,在某些情况下,我还需要使用url和get / post方法进行常规的api调用。 我试图由我的机器人与另一个用户打开直接消息通道。 文档-https : //api.slack.com/methods/im.open表示要“将这些参数作为application / x-www-form-urlencoded查询字符串或POST正文的一部分呈现。当前不接受application / json。 ”

现在在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"}

我知道消息是“未认证”,尽管我使用了我的机器人令牌和另一个用户ID,但我的直觉是我以错误的格式发送了请求,因为我只是以某种方式编写了阅读文档的方式。 我不确定如何准确发送这些请求。

有什么帮助吗?

在第二个参数requests.post用于data ,所以在你的要求,你实际上张贴headers字典。 如果要使用headers ,则可以按名称传递参数。

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

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

由于Content-Type标头是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM