LoginSignup
1
1

More than 1 year has passed since last update.

SlackでCHにfileをアップロードする方法

Posted at

Slack Appの作り方はある程度知っていることを前提とした情報になります。

Slackでのファイルアップロード

いくつか方法はあります。

詳しくはここにSlack APIの記載があります。

  1. JenkinsのPlugin、Slack Notification Plugin を使った方法
  2. Slack APIを使ったアップロード方法

で、やり方は色々あるんですが1は結構簡単です。
ただし問題点は、どこのURLにあがったのか、ファイルのアップロードURLとかは取れません。
responseとかね。
そういうのがとりたい場合は、2が必要。

JenkinsのPlugin、Slack Notification Plugin を使った方法

取り急ぎこの方法。

slackUploadFile channel: '#hoge',
    credentialId: 'slack_token',
    filePath: './test.png'

こんな感じ。credentialsIdはslack appとかのtoken。

Slack APIを使ったアップロード方法

さっきのこれに色々記載がある。

  • HTTP
  • JavaScript
  • Python
  • Java

python的にだとーを説明すると。

もちろん前提としてpipでslack入れておく。

%pip3 install slackclient

色々あるのだけど、Python的にはこういう。

hoge.py
import os
import sys
from slack import WebClient
from slack_webhook import Slack
from slack.errors import SlackApiError

# params
channel = sys.argv[1] # アップロード先CH
botToken = sys.argv[2] # slack App Token
filePath = sys.argv[3] # ファイル指定

##
## ファイルのアップロード
##
client = WebClient(token=botToken)
url = ''

try:
    response = client.files_upload(
        channels=channel,
        file=filepath,
        initial_comment='Hey! finished upload.',
        filename=filePath,
        filetype="png") # 用途に応じて

    assert response["file"]
    url = response["file"]["url_private"] # urlが返ってくる
except SlackApiError as e:
    assert e.response["ok"] is False
    assert e.response["error"]
    print(f"Faied To Upload!!!: {e.response['error']}")

# 出力
print(url)

こうすると、urlにupload先のurlが返ってくる。
filePathとfilenameかぶってんけど・・(はしょったYO)

jenkinsで使うときはこんな感じ

withCredentials([string(credentialsId:'bot_token', variable: 'token')]) {
                    
    def command = "python3 hoge.py ${url} ${token} ${filePath}"
    def url = sh(script:command, returnStdout:true)
    println "url : " + url
}
1
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
1
1