1

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 in except block of my code-

    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)

My send_message() looks like below-

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

I saw the following link slack webhook post But I am confused here how to use my send_message() in my except block of code?

Can anyone please help me how to achieve this?

AnalyticsPy
  • 245
  • 2
  • 14

2 Answers2

3

The data in the request needs to be in the correct format, so..

logger.info(msg)
slackmsg = {"text": msg}
send_message(self, slackmsg)
Zak
  • 48
  • 5
1

your payload must have a key named "text" in it.

def send_message(self, message):
    payload = {"text": message}
    try:
        return requests.post(self.url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
    except requests.exceptions.RequestException as e:
        print e.message
        return False

And to your question how to use it, you can format your message like this:

{
    "message": ex.message

}

Also take a look on this tool Sentry

Amir Gohar
  • 58
  • 6