Slack: Upload File (Bots)
Upload files to Slack with Bots.
Configs
  • C1: Slack Bot Token *
  • C2: Slack Channel Name *
  • C3: Data item whose attached files will be uploaded (File) *
Script (click to open)

main();
function main() {
  const token = configs.get("Token");
  const channel = configs.get("ChannelName");
  const filesDef = configs.getObject("File");
//check whether files exist or not
  const files = engine.findData( filesDef );
  if (files === null){
    engine.log ("No File to upload");
    return;
  }
  //check whether number of files is under the limit
  const numOfFiles = files.length;
  if (numOfFiles > httpClient.getRequestingLimit()){
    throw "Number of Files is over the limit.";
  }
  for (let i = 0; i < numOfFiles; i++){
    upload(token,files[i],channel);
  }
}
/**
  * Upload File
  * @param {String} token 
  * @param {QfileView} file
  * @param {String} channel
  */  
function upload (token,file,channel){ 
  const response = httpClient.begin()
    .bearer(token)
    .multipart('file',file)
    .multipart('channels',channel)
    .post("https://slack.com/api/files.upload");
    
  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();

  let responseJson;
  try {
    responseJson = JSON.parse(responseTxt);
  } catch(e) {
    engine.log("failed to parse as json");
    engine.log(`status: ${status}`);
    engine.log(responseTxt);
    throw `Failed to upload. status: ${status}`;
  }
  if (responseJson.ok !== true) {
    const filename = file.getName();
    const error = `Failed to upload\n filename: ${filename}`;
    engine.log(`status: ${status}`);
    engine.log(responseTxt);
    throw error;
  }

}

Download

2021-03-08 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/slack-file-upload-bots
The Addon-import feature is available with Professional or Enterprise edition.

Notes

  1. If you specify more than one channel to upload to, the channel name is comma-separated.

Capture

See also

%d bloggers like this: