21
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでSlackのWebAPIを使ってメッセージを送る(JSONベース)

Last updated at Posted at 2018-02-01

2017年10月からSlackのWebAPIのchat.postMessageでも、Slackに投稿したい内容をJSONで投げられるようになったそうです。

chat.postMessage

ということで、早速Pythonで試してみました。

import urllib.request
import json

url = 'https://slack.com/api/chat.postMessage'

headers = {
    'Authorization': 'Bearer {ココにSlackのAPIを叩くためのOAuthトークン書いてね}',
    'Content-Type': 'application/json; charset=utf-8'
}

method = 'POST'

data = {
    "channel": "#general",
    "username": "Pythonぼっと",
    "text": "Pythonからメッセージ送るよ!",
    "icon_emoji": ":snake:"
}
                                                                                                                                       
json_data = json.dumps(data).encode("utf-8")

req = urllib.request.Request(url=url, data=json_data, headers=headers, method=method)
res = urllib.request.urlopen(req, timeout=5)
                                                                                                                                       
print("Http status: {0} {1}".format(res.status, res.reason))
print(res.read().decode("utf-8"))

ちゃんと以下のようにSlackにメッセージを投稿できました!(何度かテストしているのでメッセージが複数件有ります)

Screenshot-2018-2-1 notification Exam Slack.png

さすがPythonすんなり動きました!

21
16
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
21
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?