Search code examples
pythonwebhooksslackslack-api

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


I have written this simple code to send message in a Slack channel and now I want to know that how can I use to variable (name, date) values in data and send it to Slack channel?

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

I'm getting this---->

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

but I want this--->

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

now how can I send these variable values in this message so I can get this in Slack channel?


Solution

  • You will need to try using template strings in Python to substitute the date and name strings in your text value.

    An example might be for the string you have:

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