Python 2.7 为什么从一行中提取变量时,将数据发送到SlackWebHook的Python脚本不起作用?
语言:Python 2.7 大家好。我在这里找到了一个非常有用的脚本: 这显示了如何将消息发送到松弛的web钩子Python 2.7 为什么从一行中提取变量时,将数据发送到SlackWebHook的Python脚本不起作用?,python-2.7,io,with-statement,slack-api,Python 2.7,Io,With Statement,Slack Api,语言:Python 2.7 大家好。我在这里找到了一个非常有用的脚本: 这显示了如何将消息发送到松弛的web钩子 import json import requests # Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/ webhook_url = 'https://hooks.s
import json
import requests
# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
slack_data = {"text": "<https://alert-system.com/alerts/1234|Click here> for details!"}
response = requests.post(
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
现在,如果我在这之后立即执行打印slack_数据
,信息会准确地返回到屏幕上,因此我认为这是好的。我还没有开始让它在每一行工作,因为它甚至没有在第一行工作
当我运行它时,我得到一个无效的有效负载400
编辑:Slack support表示,由于某种原因,他们收到的内容中插入了转义字符
“{\“text\”:\“有关详细信息!”}\n“
感谢您的指导或帮助
谢谢 如果将代码更改为:
with open('export.txt', 'r') as e:
slack_data = e.read()
您仍然可以使用400吗?因为我已经在文件中将数据预先格式化为JSON,所以只需从代码中删除JSON.dumps即可 旧版:
#response = requests.post(webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
response = requests.post(webhook_url, data=slack_data, headers={'Content-Type': 'application/json'})
新建:
#response = requests.post(webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
response = requests.post(webhook_url, data=slack_data, headers={'Content-Type': 'application/json'})
一旦我做到了这一点,一切都像一种魅力。只是发布,因为它可能会帮助别人。对我来说,下面的片段很管用:
data = json.dumps(slack_data)
response = requests.post(
URL, json={"text": data},
headers={'Content-Type': 'application/json'}
)
正如@Geo指出的,我们将要发送的最终有效负载应该有关键字“text”,否则它将失败
此外,在post方法中,我必须将数据=替换为json=,否则它会不断为无效负载抛出错误400我得到“ValueError:混合迭代和读取方法将丢失数据”错误等等,我在with/for语句中得到了这一点。。让我把它拿出来试试,直到无效为止。你是按原样发送
slack\u数据
,还是按slack\u数据={“text”:slack\u数据}
发送?从你的第一个例子,我猜它是在期待一个口述。很抱歉刚才看到你的评论。它应该是slack_data={“text”:“