嘿伙计们,我正在使用 slack 发送警报消息,将发票数据从我的 api 发送到 slack 频道

hey guys, i'm using slack for alert message to send invoice data from my api To slack channel

我已经编写了这个简单的代码来在 Slack 通道中发送消息,现在我想知道如何使用数据中的变量(名称、日期)值并将其发送到 Slack 通道?

import json
import requests
    
    
    webhook_url = 'https://hooks.slack.com/services/*********'
    
    
    date ="2022-2-12"
    name = "SRJ"

    
    data = {
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": "*New Invoice*"
                }
            },
            {
                "type": "divider"
            },
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": " *Date:* date \n*Invoice:* invoice \n*Amount:* amount  \n*Name:* name \n*State:* state \n*Email:* email \n*Email Status:* email status "
                }
            }
        ]
    }
    
    
    
    response = requests.post(
        webhook_url, json = data
    )
    
    if response.status_code != 200:
        raise ValueError(
            'Request to slack returned an error %s, the response is:\n%s'
            % (response.status_code, response.text)
        )

我明白了---->

New Invoice
Date: date
Invoice: invoice
Amount: amount  
Name: name
State: state
Email: email
Email Status: email status

但我想要这个--->

New Invoice
Date: 2022-2-12
Invoice: invoice
Amount: amount  
Name: SRJ
State: state
Email: email
Email Status: email status

现在如何在此消息中发送这些变量值,以便我可以在 Slack 频道中获取这些值?

您需要尝试在 Python 中使用 template strings 来替换文本值中的 datename 字符串。

一个示例可能是您拥有的字符串:

dateVar = "2022-2-12"
text = "date: {date}".format(date=dateVar)

您可以使用 f-string

代码:

date = "2022-2-12"
data = {"date": f'{date}'}

print(data)

输出:

{'date': '2022-2-12'}

[Program finished]