Created
August 9, 2018 09:01
-
-
Save munky69rock/f93ce752c9fee08ac7a07cf68a76ecdb to your computer and use it in GitHub Desktop.
Search and download slack files from cli
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
require 'json' | |
require 'net/https' | |
require 'optparse' | |
require 'uri' | |
# token: https://api.slack.com/custom-integrations/legacy-tokens | |
# Usage: | |
# ruby ./retrieve_slack_image.rb --token "YOUR_SLACK_TOKEN" --query "in:#random type:images (IMG OR Slack OR iOS)" | |
class SlackImageDownloader | |
attr_reader :token, :dir | |
URL_FORMAT = 'https://slack.com/api/search.files?token=%<token>s&query=%<query>s&count=%<count>i&page=%<page>i' | |
def initialize(token, dir = nil) | |
@token = token | |
@dir = dir ? dir : "." | |
end | |
def search_and_download(query) | |
page = 1 | |
loop do | |
slack_url = build_url(query, page) | |
res = get(slack_url) | |
res = JSON.parse res.body | |
raise "Something wrong #{res.body}" unless res['ok'] | |
res['files']['matches'].each do |m| | |
url = m['url_private_download'] | |
timestamp = m['timestamp'] | |
download url, timestamp | |
end | |
break if res['files']['pagination']['page_count'] == page | |
page += 1 | |
end | |
rescue => e | |
puts e | |
end | |
private | |
def build_url(query, page) | |
URI.escape(format URL_FORMAT, token: self.token, | |
query: query, | |
count: 20, | |
page: page) | |
end | |
def get(url, headers = {}) | |
url = URI.parse url | |
req = Net::HTTP::Get.new(url) | |
headers.each_pair { |k, v| req[k] = v } | |
https = Net::HTTP.new(url.host, url.port) | |
https.use_ssl = true | |
https.start { |http| http.request(req) } | |
end | |
def download(url, timestamp) | |
basename = File.basename url | |
path = File.join(self.dir, "#{timestamp_to_time timestamp}-#{basename}") | |
if File.exist?(path) | |
puts "Already exists: #{url} => #{path}" | |
else | |
res = get url, 'Authorization': "Bearer #{self.token}" | |
File.open(path, 'wb') do |f| | |
f.write res.body | |
end | |
puts "Download: #{url} => #{path}" | |
end | |
end | |
def timestamp_to_time(timestamp) | |
DateTime.strptime(timestamp.to_s, '%s').strftime('%Y%m%d-%H%M%S') | |
end | |
end | |
def main | |
opt = OptionParser.new | |
args = {} | |
opt.on('--token=TOKEN') | |
opt.on('--query=QUERY') | |
opt.on('--dir=[DIR]') | |
opt.parse! ARGV, into: args | |
SlackImageDownloader.new(args[:token], args[:dir]).search_and_download(args[:query]) | |
end | |
if __FILE__ == $0 | |
main | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment