When someone uses the command !uploadfile and uploads an attachment, it will download the provided attachment and replace all the 'hi' word to 'hello' word and then send attachment of updated version in the chat and gets the url of new attachment and uploads it to airtable using that url and deleting that previous message. The Airtable must have a table named "files" and two fields named "fileName" and "fileUrl"
console.log(context.params.event.content);
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const axios = require('axios'); // To download provided File
let message = context.params.event;
const prefix = '!';
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd == 'uploadfile') {
if (!message.attachments[0]) {
// If No File Provided Lets Return A Respond
return await lib.discord.users['@0.1.5'].dms.create({
recipient_id: message.author.id,
content: '',
tts: false,
embeds: [
{
type: 'rich',
title: `** No File Provided **`,
color: 0xff0000,
},
],
});
}
const response = await axios.get(message.attachments[0].url); // Download the provided Attachment
if (response.data) {
let data = response.data;
data = data.replace(/hi/g, 'hello'); // Lets use that to replace all 'hi' word in the data to 'hello'
let buffer = Buffer.from(data, 'utf-8'); // lets turn it into buffer
let msg = await lib.discord.users['@0.1.5'].dms.create({
recipient_id: message.author.id,
tts: false,
content: `** Uploading This File **`,
file: buffer,
filename: `${message.attachments[0].filename}`,
});
let url = msg.attachments[0].url;
await lib.airtable.query['@1.0.0'].insert({
// lets upload it to airtable
table: `files`,
fieldsets: [
{
fileName: `${message.attachments[0].filename}`,
fileUrl: `${url}`,
},
],
});
await lib.discord.channels['@0.2.2'].messages.destroy({
// lets delete the message that we sent before
message_id: `${msg.id}`,
channel_id: `${msg.channel_id}`,
});
return await lib.discord.users['@0.1.5'].dms.create({
recipient_id: message.author.id,
tts: false,
content: `** Success **`,
});
} else {
// if we had an error downloading the file
return await lib.discord.users['@0.1.5'].dms.create({
recipient_id: message.author.id,
content: '',
tts: false,
embeds: [
{
type: 'rich',
title: `** Error **`,
description: `Error happened While Downloading Provided Attachment`,
color: 0xff0000,
},
],
});
}
}