Slack Incoming Webhook
学習に時間がかかるAIモデルの学習時に,学習の進捗を通知したいという動機でSlack Incoming Webhookの使用を考えた.
上のURLからSlackチャネルのWebhookURLを取得して,指定する.
import socket
import requests
from datetime import datetime
class slack_channel():
def __init__(self, url, channel):
self.url = url
self.channel = channel
self.hostname = socket.gethostname()
self.icon_emoji = ":desktop_computer:"
self.current_time = datetime.now().strftime("%Y/%m/%d-%H時%M分")
def send(self, title, message):
payload = {
"channel": self.channel,
"username": self.hostname,
"icon_emoji": self.icon_emoji,
"attachments": [
{
"fallback": "Fallback text for older clients",
"pretext": None,
"color": "#36a64f",
"title": title,
"text": message,
"footer": self.current_time,
}
]
}
response = requests.post(self.url, json=payload)
# エラーが出たらプリント
if response.status_code == 200:
pass
else:
print(f"エラーが発生しました: {response.status_code}")
slack = slack_channel(url='https://yourwebhookurl', channel='#your_channel_or_yourpersonalID')
slack.send(title='TEST SEND', message='this is test sending')
- 以下のような感じで通知できます.