yoshiislandblog.net
元営業の駆け出しアラサーSEが、休日にMACと戯れた際の殴り書きメモ。日々勉強。日々進歩。

この記事は3年以上前に書かれた記事で内容が古い可能性があります

Python3でSlackの複数チャンネルにAPI経由でPostする

2016-10-10

複数のチャンネルに一気にpostしたい場合はループを追加

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
# ================================================
### modules
import urllib.request, urllib.error, urllib.parse #python3
 
# ================================================
### set variables
token = "<token>"
ChannelID = ["<channelID1>",
			"<channelID2>",
			"<channelID3>"
			]

PostMessage = "hey\r\n`hey`\r\n```\r\ntest\r\ntest\r\n```"
 
# ================================================
### post slack message
def PostSlackMessage(token, ChannelID, PostMessage):
	url = "https://slack.com/api/chat.postMessage"

	for c in ChannelID:
		params = {'token': token, # token
				'channel': c, # channel ID
				'text': PostMessage, # text
				'username': 'bot-test',
				'icom_emoji': ':smiley_cat:'
				}
		 
		### url request
		#req = urllib2.Request(url) #python2
		req = urllib.request.Request(url) #python3
		 
		### add header
		req.add_header('Content-Type', 'application/x-www-form-urlencoded')
		 
		## encode
		#params = urllib.urlencode(params) #python2
		params = urllib.parse.urlencode(params).encode("utf-8") #python3
		 
		## post
		with urllib.request.urlopen(req, params) as res:
			data = res.read().decode("utf-8")
			print(data)

### Execute
if __name__ == "__main__":
    PostSlackMessage(token, ChannelID, PostMessage)