LoginSignup
2
1

SlackにAPI経由でファイルをアップロードする(Python)

Last updated at Posted at 2024-01-23

背景

  • SlackにAPI経由でファイルをアップロードし、ユーザーにダウンロードさせたいケースです
  • 既存のincoming webhook 経由ではファイルのアップロードできないようです

Please note: it's not possible to send files via webhook. The files.upload API method is the method of choice for this task.

  • Slackアプリを使ったfile uploadをpythonで実装していきます

まずはSlack Appを作成

  • こちらの手順通りに作成していきます
  • ファイルのuploadをする場合は files:write の権限を付与することを忘れないようにしてください
  • 作成の設定が面倒な場合は、以下のリンクページに用意されている create app ボタンから作成すると、デフォルトで色々な権限がついた状態でアプリを作成できるので楽です(※強めの権限なので注意してください)

File Uploadの実装

  • TokenはSlackアプリの設定から取得できます
    68747470733a2f2f71696974612d696d6167652d73746f72652e73332e61702d6e6f727468656173742d312e616d617a6f6e6177732e636f6d2f302f31343035332f33346262633731372d313562622d613463382d383436362d3834333631636662663963612e706e67.png

実装

import requests

# Slack APIトークン
token = 'xoxb-xxxxxxxxxx'

# アップロードするファイルのパス
file_path = './hoge.csv'

# アップロード先のチャンネルID
channel_id = 'XXXXX'

# ファイルを開いてアップロード
with open(file_path, 'rb') as file:
    response = requests.post(
        url='https://slack.com/api/files.upload',
        headers={'Authorization': f'Bearer {token}' },
        data={'channels': channel_id},
        files={'file': file}
    )

# レスポンスの確認
print(response.text)

API Reference

参考

2
1
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
2
1