Skip to content

Instantly share code, notes, and snippets.

@fgimian
Forked from jamescmartinez/slack_delete.rb
Created May 30, 2018 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgimian/d403865a5abb8bfb505bb76ea5aac509 to your computer and use it in GitHub Desktop.
Save fgimian/d403865a5abb8bfb505bb76ea5aac509 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(days)
params = {
token: @token,
ts_to: (Time.now - days * 24 * 60 * 60).to_i,
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)
body = JSON.parse(response.body)
if body['ok']
puts "#{file_id}: OK"
else
error = body['error']
puts "#{file_id}: ERROR (#{error})"
end
# Sleep a little to ensure no rate limiting
sleep 0.5
end
end
files = list_files(days = 30)
puts 'Files that would be deleted:'
files.each do |file|
created_datestamp = Time.at(file["created"])
puts "#{created_datestamp}: #{file["title"]} (#{file["name"]})"
end
print 'Would you like to proceed? (y/N):'
proceed = gets.chomp
if proceed.downcase == 'y'
file_ids = files.map { |f| f['id'] }
delete_files(file_ids)
puts 'Done!'
else
puts 'User cancelled operation, exiting'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment