Create your own Slack Bot with Node and JavaScript - Part III
In Part 3 of this article, I will show you how to download, list and delete existing files in a given Slack channel.
Part I is available here: SLACK BOT #1
Part II is available here: SLACK BOT #2
Add the Slack client (current last version is 4) to your project:
Setup OAuth credentials properly:
Initialize the Slack RTM client:
And initialize the Slack Web client:
And that's all, we are ready now to proceed with our specific goals.
The idea is pretty straightforward: once the "connected" event is triggering the execution of the "listFiles()" function.
And to list the existing files in the channel, we will use the "files.list" method provided by the Slack Web API.
You can get the ID of every file available in the Slack channel by doing something similar to this:
The only item to highlight here is that we need to pass the bearer authorization as part of our request headers.
Here it goes:
Slack Developer Kit for Node.js
Part I is available here: SLACK BOT #1
Part II is available here: SLACK BOT #2
Connection settings and requirements
In order to use the Slack API and save the downloaded files to disk we will use both "fs" and "https" modules:var fs = require('fs')
var https = require('https');
Add the Slack client (current last version is 4) to your project:
const { RTMClient, WebClient } = require('@slack/client');
Setup OAuth credentials properly:
const token = 'xobx-.......' ;
const token2 = 'xoxp-......' ;
Initialize the Slack RTM client:
const rtm = new RTMClient(token);
rtm.start();
And initialize the Slack Web client:
const web = new WebClient(token2);
And that's all, we are ready now to proceed with our specific goals.
How to list existing files in a given Slack channel
You can use the "connected" event to trigger the listing process. You can use it as follows:rtm.on('connected', (event) => {
console.log('conectado a SLACK');
listFiles() ;
});
The idea is pretty straightforward: once the "connected" event is triggering the execution of the "listFiles()" function.
And to list the existing files in the channel, we will use the "files.list" method provided by the Slack Web API.
You can get the ID of every file available in the Slack channel by doing something similar to this:
function listFiles() {
web.files.list()
.then((response) => {
// Success!
for(var i=0 ; i < response.files.length ; i++) {
var fileID = response.files[i].id
}
})
.catch((error) => {
//Error!
console.log('files.list error:');
console.log(error);
});
}
How to delete an existing file in a given Slack channel
To delete a given file, we will use the "files.delete" method. We can use the file ID to identify the target file.function deleteFile(fileID) {
web.files.delete({file: fileID})
.then((response) => {
// Success!
console.log('files.delete OK: ' + fileID);
})
firewalls:
.catch((error) => {
// Error
console.log('files.delete error: ' + fileID);
console.log(error);
});
}
Note: You will need to grant "files:write:user" scope to your app.How to download an existing file from a given Slack channel
We will listen to the "message" event in order to download every new file uploaded to the Slack channel.
The "upload" field in the JSON payload helps us to identify the message that represents a file upload operation.
We can also add other specific patterns, for instance, in the following example only "image files" will be downloaded.
The necessary code is something like this:
rtm.on('message', (event) => {
if(event.files) {
var timestamp = event.files[0].timestamp ;
var file = event.files[0].url_private ;
var ext = file.split('.').pop();
var fileName = timestamp + '-0.' + ext ;
var array = file.split('/');
var slackFile = '/files-pri/' + array[4] + '/' + array[5] ;
// only image files will be downloaded
if(event.files[0].mimetype.includes('image') && event.upload) {
downloadfile(slackFile,'images/' + fileName);
}
} else {
console.log('attachment is not a file');
}
});
The download function
And finally, the last piece of code we need.The only item to highlight here is that we need to pass the bearer authorization as part of our request headers.
Here it goes:
function downfile(slackfile,target) {
var options = {
host: 'files.slack.com',
method : 'GET',
path: slackfile,
headers : { Authorization: 'Bearer xoxb-......'}
}
var file = fs.createWriteStream(target);
var request = https.get(options,function(response) {
response.pipe(file);
file.on('finish', () => {
console.log('finish OK');
});
file.on('error', err => {
console.log(err);
});
});
}
Wrapping Up
Just run this code and play around with all existing possibilities.
References:
References:
No comments