Python Forum

Full Version: How can I send error message to slack using webhook url in Python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I have several Python functions. In case of any error I want to send the error message to slack. For this I have added below line of code in every except block -

except Exception as ex:
     msg = 'There is a problem with csv generation due to: {}'.format(ex)
     logger.info(msg)
     send_message("web_hook_url",msg)
Now I have written send_message() like below mentioned in this link webhook slack post

def send_message(webhook_url, message):
 response = requests.post(
     webhook_url, data=json.dumps(message),
     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)
     )
But here I don't know how to use this function in my except block properrly. I am also not sure if it is written corrected.

So can anyone please look into this and help me?
(Jul-18-2018, 08:23 AM)PrateekG Wrote: [ -> ]But here I don't know how to use this function in my except block properrly.
Can you test it?
Hi Everyone,
I found my mistake and sharing the actual code so that it may help others-

def send_message(url, message):
    payload = {"text":message, "channel":"#help"}
    try:
        slack_req = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
        logger.info("message sent successfully with status code: {}".format(slack_req.status_code))
        return slack_req
    except requests.exceptions.RequestException as e:
        logger.error("following error occured while posting in slack: {}".format(e.message))
        return False
And in except block need to call send message as below-
    except Exception as ex:
        msg = 'error occured: {}'.format(ex)
        logger.info(msg)
        slackmsg = {"text": msg}
        send_message(webhook_url, slackmsg)