通过python请求库调用slack api

通过python请求库调用slack api,python,python-requests,slack-api,Python,Python Requests,Slack Api,我通过python库slackclient进行SlackAPI调用,slackclient是SlackAPI的包装器。然而,在某些情况下,我还需要使用url和get/post方法进行常规api调用。我试图通过我的机器人打开一个与另一个用户的直接消息通道。该文档表示“将这些参数作为应用程序/x-www-form-urlencoded querystring或POST body的一部分呈现。当前不接受application/json。” 现在用python,我可以写 url = 'https://s

我通过python库slackclient进行SlackAPI调用,slackclient是SlackAPI的包装器。然而,在某些情况下,我还需要使用url和get/post方法进行常规api调用。我试图通过我的机器人打开一个与另一个用户的直接消息通道。该文档表示“将这些参数作为应用程序/x-www-form-urlencoded querystring或POST body的一部分呈现。当前不接受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_authoted”}

我知道消息是“未授权的”,尽管我使用了我的bot令牌和另一个用户id,但我的直觉是,我以错误的格式发送请求,因为我只是以阅读文档的方式编写了请求。我不知道如何准确地发送这些请求


有什么帮助吗?

请求中的第二个参数。post用于
数据
,因此在请求中实际上是发布
标题
字典。如果要使用
标题
,可以按名称传递参数

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

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

请求中的第二个参数。post用于
数据
,因此在请求中实际上是发布
标题
字典。如果要使用
标题
,可以按名称传递参数

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

但是,在这种情况下不需要这样做,因为发布表单数据时,
'x-www-form-urlencoded'
是默认设置。

因为内容类型标题是
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

由于内容类型标题是
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

尝试将
data
设置为
[('token',BOT_token),('user',user_id),…]
,然后
response=requests.post(url,data,**headers)
成功了。谢谢@ARPITGOYAL我应该发布一个答案以便你可以投票吗?是的,我很乐意这样做@ARPITGOYAL尝试将
data
设置为
[('token',BOT\u token),('user',user\u id),…]
,然后
响应=请求。发布(url,数据,**标题)
成功了。谢谢@ArpitGoyal我应该发布一个答案,这样你就可以投票了吗?是的,我很乐意@ArpitGoyal这样做