Skip to content

Instantly share code, notes, and snippets.

@jamescmartinez
Last active May 28, 2024 15:00
Show Gist options
  • Save jamescmartinez/909401b19c0f779fc9c1 to your computer and use it in GitHub Desktop.
Save jamescmartinez/909401b19c0f779fc9c1 to your computer and use it in GitHub Desktop.
This Ruby script will bulk remove all Slack files older than 30 days. Just add your API token from https://api.slack.com/web#authentication into the token quotes at the top of the file.
require 'net/http'
require 'json'
require 'uri'
@token = ''
def list_files
ts_to = (Time.now - 30 * 24 * 60 * 60).to_i # 30 days ago
params = {
token: @token,
ts_to: ts_to,
count: 1000
}
uri = URI.parse('https://slack.com/api/files.list')
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)['files']
end
def delete_files(file_ids)
file_ids.each do |file_id|
params = {
token: @token,
file: file_id
}
uri = URI.parse('https://slack.com/api/files.delete')
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
p "#{file_id}: #{JSON.parse(response.body)['ok']}"
end
end
p 'Deleting files...'
files = list_files
file_ids = files.map { |f| f['id'] }
delete_files(file_ids)
p 'Done!'
@luisenrike
Copy link

@nandodelauni I had the same error and it was because I was using an invalid token

@nandodelauni
Copy link

thanks @luisenrike!

@ryanckulp
Copy link

here's the new URL for generating Legacy workspace tokens:
https://api.slack.com/custom-integrations/legacy-tokens

@savetrev
Copy link

savetrev commented Jul 17, 2018

Sorry, I'm not a programmer and am having problems figuring out where to run this code.

Edit: Ahh nevermind, a colleague helped me out. I had to download node.js first :-(

@dominikwilkowski
Copy link

I just added a node gist to batch delete files older than a year
https://gist.github.com/dominikwilkowski/76d99ae84848c39e54494f4dbdd4327d

Comes with instructions too :)

@ayhamg
Copy link

ayhamg commented Oct 1, 2018

An easier way is to use, no coding required.

https://delete-slack-files.com/

@halburgiss
Copy link

I get an HTML doc with little helpful error handling, that starts:

400 ERROR

The request could not be satisfied.

@ayhamg Right now that link is 404.

@danibram
Copy link

I just developed a bot that helps you to manage this, any contribution is welcome!
https://github.com/danibram/scrapy-slack-bot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment