Skip to content

Instantly share code, notes, and snippets.

@nqbao
Created February 6, 2020 21:46
Show Gist options
  • Save nqbao/e568a3a3de3cb0b12367ea251023ddfb to your computer and use it in GitHub Desktop.
Save nqbao/e568a3a3de3cb0b12367ea251023ddfb to your computer and use it in GitHub Desktop.
Snippet for integration slack with lambda
import json
import os
import urllib3
bot_token = os.environ.get('SLACK_BOT_TOKEN')
def send_slack_message(channel, message, blocks=[], attachments=[]):
http = urllib3.PoolManager()
body = {
"channel": channel,
}
if isinstance(message, dict):
body['message'] = message
else:
body['text'] = message
if blocks:
body['blocks'] = blocks
if attachments:
body['attachments'] = attachments
response = http.request(
"POST", "https://slack.com/api/chat.postMessage",
body=json.dumps(body).encode('utf8'), headers={
'Content-Type': 'application/json; charset=utf8',
'Authorization': 'Bearer ' + bot_token,
}
)
result = json.loads(response.data.decode('utf8'))
if not result['ok']:
raise Exception("Unable to post message: {}".format(result['error']))
def lambda_handler(event, context):
send_slack_message(
event.get('channel'),
event.get('message'),
event.get('blocks'),
event.get('attachments')
)
return {
"status": "ok"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment