2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Slackに投稿されたファイルを自動削除する方法

Posted at

はじめに

中規模のチームでSlackを無料枠で使っていると、ストレージが5GBまでという制約に苦戦することになるかと思います。特に、Slackの仕様についてあまり理解していない人は、サイズが大きいAIファイルなどをチャンネルで送ったりします。(Slack管理者としてはやめてーと言ってるんですが、、)

そこで、今回はSlackに投稿されたファイルを自動削除するスプリクトを作成しました。

環境

Slack

Tokenの取得

推奨Tokenの取得については、上記記事を参考にしました。

スコープの設定

スクリーンショット (223).png

スクリーンショット (224).png

今回必要なスコープは、

  • files:read
  • files:write:user

の二種類です。

設定が完了したら、「Install App」をクリックして、OAuth Access Tokenを取得しましょう。

GAS


var SLACK_TOKEN = PropertiesService.getScriptProperties().getProperty("SLACK_TOKEN");

function DaysToUnixTime(days){  
  var date = new Date();
  var now = Math.floor(date.getTime()/ 1000);
  return now - 8.64e4 * days + '';
}

function getFileList(day){
  var count = 100 //一度に削除できるファイル数
  var params = {
    'token': SLACK_TOKEN,
    'ts_to': DaysToUnixTime(day),
    'count': count
  }
  var options = {
    'method': 'POST',
    'payload': params
  }
  var url = 'https://slack.com/api/files.list';
  var res = UrlFetchApp.fetch(url,options);
  var FileList = JSON.parse(res.getContentText());
  FileList.files.forEach(function(val){
    var del = fileDelete(val.id);
  });
}

function fileDelete(id){
  var url = 'https://slack.com/api/files.delete?token='+SLACK_TOKEN+'&file='+id;
  var res = UrlFetchApp.fetch(url);
  return res;
}

function OneWeekDelete(){
  var day = 7 //指定した日数以前のファイルを削除する
  getFileList(day);
}

function ImmediateDelete(){
  var day = 0 //指定した日数以前のファイルを削除する
  getFileList(day);
}

スプリクトのプロパティ

先ほど取得した、SlackのTokenを「スプリクトのプロパティ」に追加します。

↑追加方法

  • プロパティ: SLACK_TOKEN
  • 値: 先ほど取得したToken

実行

関数OneWeekDeleteImmediateDeleteを実行すると、ファイルが削除されます。なお、前者は投稿から一週間経過したファイル、後者はすべてのファイルを消します。
僕は、前者を1日ごとにトリガーで実行させています。(後者は使いたいときに手動で実行するようにしている)

まとめ

  • Slackに投稿されたファイルを無差別に削除する。
  • このチャンネルの投稿は消したくないというのがあれば、下記参考サイトを見れば実装できるはず。
  • ただし、プライベートチャンネルやDMは(自分が参加しているものを除き)対象外。

参考サイト

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?