Python3でSlackにAPI経由でPostする | www.yoshiislandblog.net

Python3でSlackにAPI経由でPostする

■version
python3.5.0
※python2対応の部分はコメントアウトしています。

■トークンを得る
Slack Web API

■チャンネルIDを得る
channels.list

■コード

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# ================================================
### modules
import urllib.request, urllib.parse, urllib.error #python3
import urllib.request, urllib.error, urllib.parse #python3

# ================================================
### set variables
token = "<token>"
ChannelID = "<channelID>"
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"
    params = {'token': token, # token
            'channel': ChannelID, # 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)

■実行結果

■APIの細かい機能はこちら
chat.postMessage
as_userあたりを使うとbotが投稿したとバレない。

%d bloggers like this: