Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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すんなり動きました!

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away