Rでslack上の画像を保存してPDFにしてgoogle driveに保存する

タカヤナギ=サンアドベントカレンダー21日目の記事です。

ホクソエム社にはタカヤナギ=サン謹製の画像がアップロードされるチャンネルがあり、他メンバーはアップロードされる画像を黙々とダウンロード、そしてPDFに変換しているわけですが、こんなことは人間がやる仕事ではない。
ついでに言うとRでやる仕事でもない気がするが、せっかくなのでRでやる。

googledrive::drive_upload()の初回利用時に認証を求められる点に注意されたし。

library(httr)
library(lubridate)
library(googledrive)

# 指定したURLの画像を指定のgoogledriveのフォルダにアップロードする関数
saveImage <- function(obj, filetype, token){
  download_url <- obj$files[[1]]$url_private
  title <- gsub("[[:punct:]]|[[:space:]]", "_", obj$files[[1]]$title)
  response_image <- GET(download_url, add_headers(Authorization = paste("Bearer", token, sep = " ")))
  image <- content(response_image, "raw")
  f_temp <- tempfile()
  writeBin(image, con = glue("{f_temp}.{filetype}"))
  # ImageMagickでPDFに変換する
  system(glue("convert {f_temp}.{filetype} {f_temp}.pdf"))
  drive_upload(glue("{f_temp}.pdf"), 
               path = as_id("送り先のgoogledriveのURL"),
               name = glue("{title}.pdf")
  )
}


# slackから直近24時間の履歴を取得する
oldest <- as.numeric(Sys.time() -hours(24))
latest <- as.numeric(Sys.time())
token <- "トークン"
channel <- "タカヤナギ=サンの画像がアップされるチャンネルID" 

params <- list(
  token = token,
  channel = channel,
  count = 10000,
  latest = latest,
  oldest = oldest
)
endPoint.history <- 'https://slack.com/api/channels.history'
response <- POST(endPoint.history, 
             body = params,
             encode = "multipart",
             content_type = "application/x-www-form-urlencoded"
             )
response_json <- content(response, "parsed")

# jpg、ong、gif画像をPDFに変換し、google driveにアップロードする
for(i in seq_len(length(response_json$messages))){
  trg <- response_json$messages[[i]]
  if(!is.null(trg$files)){
    if(trg$files[[1]]$filetype %in% c("jpg","png","gif")){
      saveImage(trg, filetype = trg$files[[1]]$filetype, token = token)
    }}else{
      next
    }
}