From edf99b52c0e28381e1374671403e86ea9083d1d1 Mon Sep 17 00:00:00 2001 From: Tom Jowitt Date: Sun, 4 Jun 2017 19:23:29 +1000 Subject: [PATCH] Added the ability to delete lists of files from Slack --- README.md | 9 ++++++- main.go | 76 ++++++++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 69 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4c3b689..c6da9cc 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,11 @@ [![CircleCI](https://circleci.com/gh/madecomfy/slack-cleanup/tree/master.svg?style=svg&circle-token=4aee14214b029ff6bcb7664e8c403ef1288e84f4)](https://circleci.com/gh/madecomfy/slack-cleanup/tree/master) -A program for cleaning up slack files to free up space +A program for cleaning up slack files to free up space. + +## Setup + +You will need to generate an API token that has permission to delete files. If you do not have administrator +privileges you will only be able to delete your own files. Generate an API token at the following link: + +[Legacy Tokens](https://api.slack.com/custom-integrations/legacy-tokens) diff --git a/main.go b/main.go index ea39df4..e658d05 100644 --- a/main.go +++ b/main.go @@ -1,33 +1,79 @@ package main import ( + "encoding/json" "fmt" + "io/ioutil" "log" "net/http" "os" + "time" ) -const apiURL string = "https://slack.com/api/" +// Files contains the list of files we want to clean +type Files struct { + FileList []File `json:"files"` +} + +// File is an individual file we wish to remove from Slack +type File struct { + ID string `json:"id"` +} func main() { - token := os.Getenv("SLACK_API_TOKEN") - fmt.Println(token) - - response, err := http.Get(apiURL + "files.list?token=" + token) + req, err := http.NewRequest("GET", "https://slack.com/api/files.list", nil) if err != nil { log.Fatal(err) } - defer response.Body.Close() - fmt.Println(response.Body) - -} - -func listFiles() { - -} - -func deleteFiles() { + tsNow := time.Now() + tsTo := tsNow.AddDate(0, -14, 0) + tsUnix := tsTo.Unix() + + q := req.URL.Query() + q.Add("token", os.Getenv("SLACK_API_TOKEN")) + q.Add("ts_to", fmt.Sprint(tsUnix)) + q.Add("count", "1000") + req.URL.RawQuery = q.Encode() + + httpClient := &http.Client{} + resp, err := httpClient.Do(req) + if err != nil { + log.Fatal(err) + } + content, err := ioutil.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + var files Files + if err := json.Unmarshal(content, &files); err != nil { + log.Fatal(err) + } + + for _, file := range files.FileList { + req, err := http.NewRequest("GET", "https://slack.com/api/files.delete", nil) + if err != nil { + log.Fatal(err) + } + + q := req.URL.Query() + q.Add("token", os.Getenv("SLACK_API_TOKEN")) + q.Add("file", file.ID) + req.URL.RawQuery = q.Encode() + + httpClient := &http.Client{} + resp, err := httpClient.Do(req) + if err != nil { + log.Fatal(err) + } + _, err = ioutil.ReadAll(resp.Body) + if err != nil { + log.Println(err) + } + + fmt.Println("File", file.ID, "successfully deleted") + } }