浜松のWEBシステム開発・スマートフォンアプリ開発・RTK-GNSS関連の開発はお任せください
株式会社シーポイントラボ
TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:静岡県浜松市中区富塚町1933-1 佐鳴湖パークタウンサウス2F

【Python】【Slack】webhookAPIでリッチなテキストを送る

 SlackにはAPI、URLに特定のパラメータを入れてアクセスするだけでメッセージを送る仕組みがあります。これをプログラミング様にラッピングしたライブラリがしばしばあります。例えばPythonのslackwebです。
slackweb · PyPI
【Python】PythonでSlackの通知を送る – 株式会社シーポイントラボ | 浜松のシステム開発会社
 これでなにかしら起きる度にSlackへ通知を投げることができます。単に文字列を送るだけならば次でOKです。

import slackweb


slack = slackweb.Slack(url="Incoming Webhookで発行したURL")
slack.notify(text="python to slack")


 これだけでも便利なのですが送る対象が巨大になってくると構造化したメッセージを送りたくなります。slackwebを利用した時に便利に使えるのが添付機能、attachmentsです。例えば次のように送れます。

import slackweb

_slack_url = 'https://hooks.slack.com/services/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'

slack = slackweb.Slack(url=_slack_url)
attachments = [
    {
        "fallback": "Plain-text summary of the attachment.",
        "color": "#2eb886",
        "pretext": "Optional text that appears above the attachment block",
        "author_name": "Bobby Tables",
        "author_link": "http://flickr.com/bobby/",
        "author_icon": "http://flickr.com/icons/bobby.jpg",
        "title": "Slack API Documentation",
        "title_link": "https://api.slack.com/",
        "text": "Optional text that appears within the attachment",
        "fields": [
            {
                "title": "Priority",
                "value": "High",
                "short": False
            }
        ],
        "image_url": "http://my-website.com/path/to/image.jpg",
        "thumb_url": "http://example.com/path/to/thumb.png",
        "footer": "Slack API",
        "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
        "ts": 123456789
    },
    {
        "title": "二つ目"
    }
]
slack.notify(text="python to slack", attachments=attachments)


 けっこう色々できますのでドキュメントにすぐアクセスできる環境で記述するのが楽です。
Creating rich message layouts | Slack#attachments
Slack API attachmentsチートシート – Qiita
 例はかなりがっつりでしたが、単に配列にして箇条書き的にAPIに情報を渡すだけでもわりと便利です。

  • この記事いいね! (2)