LoginSignup
2
1

More than 5 years have passed since last update.

botでslackに貼られたfileを受け取る(Ruby)

Posted at

やりたきこと

slackに貼られたfileをbotで受け取って処理する
ex)特定チャンネルに貼られたfileをs3にputする

bot本体

以下の何かしら処理のところに色々書けばいろんな機能が実装できます。
fileはdownload用URLとtokenで取ってくることができます。

main.rb
require File.dirname(__FILE__) + '/chatops_file'

begin
  chatops_file = ChatopsFile.new
  chatops_file.slack_bot
rescue StandardError => e
  #エラーハンドリング
end
chatops_file.rb
require 'slack-ruby-client'

class ChatopsFile

  # 初期化
  def initialize
    Slack.configure do |conf|
      conf.token = 'xoxo-***************'
    end
  end

  # botのメイン処理
  def slack_bot
    client = Slack::RealTime::Client.new

    client.on :message do |data|
      file = data.files

      if file
        file = file[0]
        filetype = file.filetype
        mimetype = file.mimetype
        file_name = file.name
        file_url_private_download = file.url_private_download
        event_ts = data.event_ts
        text = data.text
        user_id = data.user
        usr_name = data.display_name

        next if data.user == 'USLACKBOT'
        next if file.user == 'USLACKBOT'

        begin
          # file_url_private_downloadを使って何かしら処理
        rescue => e
          # エラーハンドリング
        end
      end
    end

    client.start!
  end

end

おまけ:fileをS3にputしてみる

処理の部分はbotから切り離してlambdaで実装していたので、
pythonでコードを書いています。

lambda_function.py
import os
import requests
import shutil
import boto3

slack_token = "xoxo-****************"

def handler(event, context):
    # ここはlambdaを起動する時のメッセージをパースしています
    event_dict = json.loads(event["body"])
    channel_name = event_dict["channel_name"]
    req_usr = event_dict["req_usr"]
    file_name = event_dict["file_name"]
    file_url = event_dict["file_url_private_download"]

    try:
        tmp_path = "/tmp/" + file_name
        s3_key = "file_s3_upload/" + file_name
        res = requests.get(file_url, headers={'Authorization': 'Bearer %s' % slack_token}, stream=True)
        with open(tmp_path, 'wb') as file:
            shutil.copyfileobj(res.raw, file)
        s3_client.upload_file(tmp_path, 'test_bucket', s3_key)
    except Exception as e:
        print(e)
        raise e



def s3_client(iam_user_key):
    s3 = boto3.client('s3', region_name="AWS_REGION",
                      aws_access_key_id='AWS_ACCESS_KEY',
                      aws_secret_access_key='AWS_SECRET_KEY'
                      )
    return s3
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