简体   繁体   English

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

[英]slack api calls through python request library

I was making slack api calls through python library slackclient which is a wrapper around slack api. 我正在通过python库slackclient进行slack api调用,这是slack api的包装。 However, for some cases I need to make conventional api calls also with url and get/post method. 但是,在某些情况下,我还需要使用url和get / post方法进行常规的api调用。 I was trying to open a direct message channel with another user by my bot. 我试图由我的机器人与另一个用户打开直接消息通道。 The documentation - https://api.slack.com/methods/im.open says to "Present these parameters as part of an application/x-www-form-urlencoded querystring or POST body. application/json is not currently accepted." 文档-https : //api.slack.com/methods/im.open表示要“将这些参数作为application / x-www-form-urlencoded查询字符串或POST正文的一部分呈现。当前不接受application / json。 ”

Now in python, I can write, 现在在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 

The message I get is {"ok":false,"error":"not_authed"} 我收到的消息是{"ok":false,"error":"not_authed"}

I know the message is "not authed" although I use my bot token and another user id, my hunch is that I'm sending the request in wrong format because I just wrote it some way reading the documentation. 我知道消息是“未认证”,尽管我使用了我的机器人令牌和另一个用户ID,但我的直觉是我以错误的格式发送了请求,因为我只是以某种方式编写了阅读文档的方式。 I'm not sure how to exactly send these requests. 我不确定如何准确发送这些请求。

Any help? 有什么帮助吗?

The second parameter in requests.post is used for data , so in your request you're actually posting the headers dictionary. 在第二个参数requests.post用于data ,所以在你的要求,你实际上张贴headers字典。 If you want to use headers you can pass arguments by name. 如果要使用headers ,则可以按名称传递参数。

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

However this is not necessary in this case because 'x-www-form-urlencoded' is the default when posting form data. 但是,在这种情况下这不是必需的,因为在发布表单数据时默认为'x-www-form-urlencoded'

since the Content-Type header is x-www-form-urlencoded sending data in form of dictionary does not work. 由于Content-Type标头是x-www-form-urlencoded ,因此无法以字典形式发送数据。 you can try something like this. 您可以尝试这样的事情。

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