为什么从一行中提取变量时,用于将数据发送到 Slack Web 挂钩的 Python 脚本不起作用?

Why does the Python script to send data to Slack web hook not work when variable is pulled from a line?

语言:Python2.7

大家好。我在这里找到了一个非常有用的脚本:Python to Slack Web Hook

展示了如何将消息发送到 Slack 网络挂钩。

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)
    )

当我 运行 .py 文件时,它可以完美运行。

现在,我有一个文件,其中包含我要发送给 Slack 的多行消息。我已经在文件中正确格式化了它,没有空格等。这只是抓住它并传递它的问题所以 slack_data = line1 等..

所以,我用这样的方式修改文件:

with open('export.txt', 'r') as e:
    for line in e:

        slack_data = line

现在,如果我在那之后立即执行 print slack_data,屏幕上的信息 returns 就会完全正常,所以我认为这很好。我还没有开始让它为每一行工作,因为它甚至在第一行都没有工作。

当我 运行 它时,我得到一个无效的负载 400。

编辑:Slack 支持说他们收到的内容出于某种原因插入了转义字符。

"{\"text\": \"<https://alert-system.com/alerts/1234|Click here> for details!"}\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'})

一旦我这样做了,一切都很顺利。

只是 posting 因为它可能对某人有帮助。对我来说,以下代码片段有效:

data = json.dumps(slack_data)
    response = requests.post(
        URL, json={"text": data},
        headers={'Content-Type': 'application/json'}
    )

正如@Geo 指出的,我们要发送的最终负载应该有关键字 "text",否则会失败。

此外,在 post 方法中,我必须将 data= 替换为 json= 否则它会不断抛出无效负载错误 400