LoginSignup
3
7

More than 5 years have passed since last update.

Python3でSlackにPostする

Last updated at Posted at 2019-01-05

SlackにPython3でMessageをPostするコードを書いたので備忘録です。
Slackにエラーログを送ったり、アラート通知などに活用する。

slack_post.py
import urllib.request
import json

url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxx'

def post_slack(msg):
    set_fileds = [{
        "title": "TITLE",
        "value": msg,
        "short": False
    }]

    data = {
        'attachments':  [{
            #'color': '#FF0000',
            'color': 'danger',
            'fields': set_fileds
        }]
    }

    method = 'POST'
    request_headers = { 'Content-Type': 'application/json; charset=utf-8' }
    body = json.dumps(data).encode("utf-8")
    request = urllib.request.Request(
        url=url, 
        data=body, 
        method=method,
        headers=request_headers 
    )
    urllib.request.urlopen(request)

if __name__ == '__main__':
    msg = "My name is yhidetoshi"
    post_slack(msg)

Slackへの通知結果

python3_slack_post.png

まとめ

Python3を使って、SlackにメッセージをPostしました。これをAWS Lambdaから様々なイベントやログ情報をSlackにPostするために活用していきたいと思います。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7