LoginSignup
8
12

More than 5 years have passed since last update.

PythonスクリプトからSlackにファイルを投稿する

Last updated at Posted at 2018-04-25

Python と Slack API の学習がてら、サンプルプログラムを書いてみました。

解決したい課題

サーバ上の Pythonスクリプトを実行して、SlackのChannelに添付ファイルを投稿したい

実装例

# coding:utf-8
import requests

TOKEN = 'Bot用のAPI token を入れてください'
CHANNEL = 'Channel IDを入れてください'

files = {'file': open("送りたいファイルをフルパスで記載", 'rb')}
param = {
    'token':TOKEN,
    'channels':CHANNEL,
    'filename':"filename",
    'initial_comment': "initial_comment",
    'title': "title"
}
requests.post(url="https://slack.com/api/files.upload",params=param, files=files)

実行例

$ python server2slack.py

その他

pip を使って requests を導入しておきましょう

$ curl -kL https://bootstrap.pypa.io/get-pip.py | python
$ pip install requests

・Bot用のAPI token は App ディレクトリ から Botsを作成して、Botsの管理画面から取得してください

・Channelをブラウザで開いて、https://xxx.slack.com/messages/{ChannelID} が Chennel ID です。

・Private Channelに投稿したい時は、BotをそのChannelに /invite するのを忘れずに。

参考

プログラムからSlackに画像投稿する方法まとめ
pipのインストール方法

8
12
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
8
12