In Slack, you can easily post a message from a Python script by getting the URL for WebHook.
In Slack, there are message
used for relatively simple messages and ʻattachments` that can represent complex message formats.
I will explain how to post to slack in both of the above formats using Python.
Publish the posting URL on Slack's Incoming WebHook Settings Page.
Select a channel and click the ʻAdd Incoming WebHooks Integration` button.
Make a copy of the displayed webhook URL
(Optional) You can change the default post settings if you want.
item | Description |
---|---|
Customize Name | Default user name at the time of posting |
Customize Icon | Default icon when posting |
If you make any corrections, save them with Save Settings
.
Install slack web that allows you to easily post with WebHook via pip.
sudo pip install slackweb
You can send a message as follows by using slackweb. The default fields are used for the fields omitted here.
.python
> import slackweb
> slack = slackweb.Slack(url="<Copyed URL>")
> slack.notify(text="This is a test.")
You can modify the room, icon, username, or use simple markdown notation by modifying the argument of the notify method. (For more information, see Message Formatting.)
.python
> slack.notify(text="This is a *test*.", channel="#coffee", username="coffee-bot", icon_emoji=":coffee", mrkdwn=True)
You can also send complex messages by using the format ʻattachments`.
.python
> attachments = []
> attachment = {"title": "Sushi",
"pretext": "Sushi _includes_ gunkanmaki",
"text": "Eating *right now!*",
"mrkdwn_in": ["text", "pretext"]}
> attachments.append(attachment)
> slack.notify(attachments=attachments)
For more information, see Attachments (https://api.slack.com/docs/attachments).
Recommended Posts