PythonでSlackにメッセージを投稿する(SlackAPI)
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Post message to Slack # using requests # 2020-12-24 (Thu.) import json import requests def slack_postmsg(url, token, channel, text): headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json; charset=utf-8'} payload = {'channel': channel, 'text': text, 'as_user': True,} req = requests.post(url, data=json.dumps(payload), headers=headers) print(req.text) SLACKAPI_URL = 'https://slack.com/api/chat.postMessage' SLACK_USER_TOKEN = "xoxp-881518928711-rrrrrrrrrrrrrrrrrrrr-xxxxxxxxxxx-10458077c9cd0df36681ce0599334ca5" channel_id = 'GSX09FY83' text = "message post from Python" slack_postmsg(SLACKAPI_URL, SLACK_USER_TOKEN, channel_id, text)
実行例:
$ python3 post-write-msg.py
{"ok":true,"channel":"GSX2FKASJ","ts":"1608777828.001500","message":{"bot_id":"B01HK4MEUD8","type":"message","text":"message post from Python","user":"URJ5M7SBV","ts":"1608777828.001500","team":"TRXF8TALX","bot_profile":{"id":"B01HK4MEUD8","deleted":false,"name":"msg-cleaner","updated":1608770884,"app_id":"A01HXN8CAJV","icons":{"image_36":"https:\/\/a.slack-edge.com\/80588\/img\/plugins\/app\/bot_36.png","image_48":"https:\/\/a.slack-edge.com\/80588\/img\/plugins\/app\/bot_48.png","image_72":"https:\/\/a.slack-edge.com\/80588\/img\/plugins\/app\/service_72.png"},"team_id":"TRXF8TALX"}}}