1
0

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で不要になった昔のファイルを削除する

1
Posted at

TL;DR

  • Slack のストレージ容量が一杯になる前に不要になったファイルを削除したい
  • ほぼ個人的なメモなので、後で書き直す可能性あり
  • やっつけで書いているので、使用等は当然自己責任で

:bulb: 単純に API 叩いてるだけなので、中身を読んで改造してご活用ください

動作

  1. files.list の API を叩いて全ファイル数の当りをつける (その後、3秒程休憩)
  2. 5秒毎に files.list の各ページの API を叩いて削除対象を探す
  3. 4秒毎に、見つかった対象のファイルIDを元に files.delete の API を叩く
  • 削除対象の条件としては LIMIT_DAYS 以上経過したファイル
    • チャンネルだとか、ユーザーだとかは見てないので、必要に応じて入れること
  • 短い時間で API を叩き過ぎないように一応ウェイトを入れている

コード

# !/usr/bin/python3
import requests
import sys
from time import sleep
from datetime import datetime

# Need Legacy Token
TOKEN = '(Slack のレガシートークン)'
LIMIT_DAYS = 30

# ------------------------------------------------------------------------------
# API からページ番号指定でファイル一覧を取得する
# ------------------------------------------------------------------------------
def getFilesFromApi(page):
    url = 'https://slack.com/api/files.list?token={0}&pretty=1&page={1}'.format(TOKEN, page)
    response = requests.get(url)
    data = response.json()
    return data

target_ids = []

# ------------------------------------------------------------------------------
# 対象ファイルを探して対象に追加
# ------------------------------------------------------------------------------
def appendTargetFrom(data):
    now_date = datetime.now()
    files = data['files']
    for file in files:
        target_date = datetime.fromtimestamp(int(file['timestamp']))
        days = (now_date - target_date).days
        if days > LIMIT_DAYS:
            target_ids.append(file['id'])

data = getFilesFromApi(1)
total_pages = data['paging']['pages']
sleep(3)

for page in range(1, total_pages + 1):
    print('検索用API呼び出し中... {0}/{1}'.format(page, total_pages))
    sleep(5)
    appendTargetFrom(getFilesFromApi(page))

# ------------------------------------------------------------------------------
# 指定 ID のファイルを削除
# ------------------------------------------------------------------------------
def deleteFileBy(id):
    url = 'https://slack.com/api/files.delete?token={0}&file={1}&pretty=1'.format(TOKEN, id)
    response = requests.post(url)
    data = response.json()
    print('削除 id={0} ... {1}'.format(id, data['ok']))

print('削除するのは全部で {0} 個'.format(len(target_ids)))
for id in target_ids:
    sleep(4)
    deleteFileBy(id)
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?