So i recently found this google drive script and tried to use it.
The script should normally get file names and url on my google drive folder and copy them in a spreadsheet.
When i click Run, I get no error and nothing happens in my drive.
Is there variables i should change to make it work ?
PS : I'm very new to coding and can't seem to find what is wrong with this code
Thanks in advance for your help !
Here is the code :
function myFunction() {
function listFilesInFolder(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
niceFileType( file.getMimeType() )
];
sheet.appendRow(data);
}
}
}
Two issues. This needs to be ran in a script attached to a spreadsheet and you have a nested function.
Your code:
function myFunction() {
function listFilesInFolder(foldername) {
...
}
}
remove the outer function decleration and its matching closing bracket. The code will run.
It should look like:
function listFilesInFolder(foldername) {
...
}
Try this modified code in spreadsheet instead:
function myfunction(){
//Declaring the function listFolders to temp
var temp = function listFolders(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(data);
}
}
// calls the function listFolders below
temp()
}
Related
I'm trying to make it so that the output of this Discord embed won't be "undefined" for the Bot, Mute, and Deafen part of the embed.
I tried to change some var to "let" or "const"
I've tampered with the aboutuser portion to change it to something different.
I've messed with the if portion of the code.
Here's the code.
async run(message, args){
if (message.channel instanceof discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
var serv = message.guild
if (serv.explicitContentFilter == 0) {
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
var eFC = "Scan for users without a role.";
}
if (serv.explicitContentFilter == 2) {
var eFC = "Scan every message";
}
///////////////////////////////////////////////////////////////////////////////////////////////////
if (serv.verificationLevel == 4) {
var verL = "Intense (Verified Account & Verified Phone linked)";
}
if (serv.verificationLevel == 3) {
var verL = "Secure (Verified Account & Guild member for 10+ minutes)";
}
if (serv.verificationLevel == 2) {
var verL = "Medium (Verified Account for 5 minutes+)";
}
if (serv.verificationLevel == 1) {
var verL = "Low (Verified Account)";
}
if (serv.verificationLevel == 0) {
var verL = "None (No Restriction)";
}
//////////////
if (serv.region == `brazil`) {
var regio = "Brazil";
}
if (serv.region == `eu-central`) {
var regio = "Central Europe";
}
if (serv.region == `hongkong`) {
var regio = "Hong Kong";
}
if (serv.region == `japan`) {
var regio = "Japan";
}
if (serv.region == `russia`) {
var regio = "Russia";
}
if (serv.region == `singapore`) {
var regio = "Singapore";
}
if (serv.region == `southafrica`) {
var regio = "South Africa";
}
if (serv.region == `sydney`) {
var regio = "Sydney";
}
if (serv.region == `us-central`) {
var regio = "Central US";
}
if (serv.region == `us-east`) {
var regio = "East US";
}
if (serv.region == `us-south`) {
var regio = "South US";
}
if (serv.region == `us-west`) {
var regio = "West US";
}
if (serv.region == `eu-west`) {
var regio = "West Europe";
}
//
if (serv.defaultMessageNotifications == `ALL`) {
var defn = "Send all Messages";
}
if (serv.defaultMessageNotifications == `MENTIONS`) {
var defn = "Only #everyone";
}
var myInfo = new discord.RichEmbed()
.setAuthor(`${serv.name}'s guild info`,`${message.guild.iconURL}`)
.addField(`AFK Channel`,`${serv.afkChannel}`,true)
.addField(`AFK Timeout`,`${serv.afkTimeout}s`,true)
.addField(`Channels`,`${serv.channels.size}`,true)
.addField(`Creation of Guild`,`${serv.createdAt}`,true)
.addField(`Default Notification`, defn,true)
.addField(`Explicit Content Filter Level`, eFC,true)
.addField(`Guild ID`,`${serv.id}`,true)
.addField(`How much members`,`${serv.memberCount}`,true)
.addField(`Owner`,`${serv.owner}`,true)
.addField(`Region`, regio,true)
.addField('Roles', `Please do s!roles to find server roles!`, true)
/* serv.roles.map(r => `${r}`).join(' | ') */
.addField(`Verification Level`, verL,true)
.setColor(0x511fdd)
.setFooter('Aboutserver command')
.setThumbnail(`${message.guild.iconURL}`)
message.channel.sendEmbed(myInfo);
}
}
expected result : The bot will say Yes or No instead of undefined, or true or false.
actual result : The bot's output is just undefined.
There are a couple of things happening here, but let's focus on the main issue; how you have declared your variables.
To put it simply, variables can only be accessed within the scope in which they are declared in (The scope is all the code between the {}).
I'll explain it with a short example based on your code. In your if statements you declare your variables, meaning they can be used within that if statements' scope. You later want to use those same variables outside of the if statement and in your embed. Because those variables don't exist in that scope, they are undefined.
...
// At this point there is no variable 'eFC' available.
if (serv.explicitContentFilter == 0) {
// Here you create the variable 'eFC' but it can only be used inside this scope, meaning it cannot be accessed outside the 'if' statement.
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here you create another variable with the same name, but it would end up being a different variable.
var eFC = "Scan for users without a role.";
}
// Here there is still no variable 'eFC' available to us.
...
The simple solution is: declare your variables in another scope and assign the values later. Below you can see an example:
...
// Here we create a new variable called 'eFC' which can be used within this scope
var eFC;
if (serv.explicitContentFilter == 0) {
// Here we assign a value to the previously defined variable
eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here we assign a value to the previously defined variable
eFC = "Scan for users without a role.";
}
// Here we can use the variable 'eFC' which will have a value
console.log(eFC);
...
If you do this for all the variables which you use, the code should work fine.
Lastly I want to leave you with some extra help. I see you have created many, many, many if statements to check for e.g. the server region or the server verification level. Javascript (among many other programming languages) has a think called a switch case which basically does the same thing you have with all those if statements, but in a more neater way. Check out the link, I think it will help you make your code look a bit more readable
I'm reading the content of a CSV file in the file cabinet with a user Event Suitelet living on sales orders and trying to reset the content of the file to an empty CSV after I'm done
I can successfully append lines and read the content but nothing about resetting the content in the NetSuite documentation.
I'm just looking for a way to reset the File to an empty CSV.
/**
*
#NApiVersion 2.x
#NModuleScope SameAccount
#NScriptType UserEventScript
#appliedtorecord salesorder
*/
define(['N/file'], function(file) {
function resetCSVFile(context) {
var fileObj = file.load({ id: '104819' });
var iterator = fileObj.lines.iterator();
var idArrays = [];
iterator.each(function(line) {
idArrays.push(line.value);
// the line below is my failed attempt at resetting the line
line.value = ''
return true;
});
log.audit({ title: 'idArrays', details: idArrays });
fileObj.save();
return true;
}
return {
afterSubmit: resetCSVFile
};
});
After you're done processing the file, you'll want to use file.create() to make a new file object with the same name, fileType, and folder property values. Set the contents property of that file object to something (perhaps the header row), and save it. This will overwrite the existing file with an empty file but keep the same internal id of the original file.
Here's an example that captures the header row of the CSV file and creates an empty file with that header row. When you create a file object, the contents property cannot be null or an empty string.
var fileObj = file.load({ id: '5447' });
var currentLine = 0;
var headerRow = '';
fileObj.lines.iterator().each(function(line) {
currentLine++;
if (currentLine === 1) {
headerRow = line.value + '\n';
}
log.debug({ title: 'header', details: line.value });
return true;
});
var newFile = file.create({
name: fileObj.name,
fileType: file.Type.CSV,
folder: fileObj.folder,
contents: headerRow
});
newFile.save();
I'm trying to search for a specific file File1 in a specific folder (named through another variable).
Once I have identified the file, I want to make a copy of the file.
This is what I came up with, with the help of previous posts and many google searches but nothing happens.
var folderName = ConsultName;
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
files.hasNext() && files == "File1" && files.next().makeCopy();
I've tried without the files == "File1" and the makeCopy() function will end up copying whatever file is next.
I've been trying to figure this out for several days, but haven't had any luck.
Any help would be helpful. Thanks!
I use these functions in several ways for loading and saving data in other scripts. If some arguments are omitted defaults are provided automatically. I believe you can use these building blocks to conjure up a copy solution for yourself
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}
Hi there I am using iNotify to detect changes in a directory. The flags I am using are IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE
I am trying to differentiate between a IN_MOVED_FROM when renaming, and the IN_MOVED_FROM when a file is moved out of the folder.
I thought to check if the cookie field is not 0 when user moved the file out. As I thought cookie was only for rename procedure. However even when I move the file out of the directory it still has a cookie.
I also though to check for IN_MODIFY as I was hoping that would be there on rename but not on move, but its not there for either.
Does anyone have any ideas on how to detect if it was just "moved-out" or it is the "renamed-from-oldfilename"?
Thanks
You need to check for the IN_MOVED_FROM event and a following IN_MOVED_TO event. If the cookie is the same, the file has been renamed in the same folder. If you don't receive a IN_MOVED_TO event with the same cookie, the file has been moved outside of the watched folder.
I applied the logic mention by #hek2mgl and its working so big thanks to him. This is js-ctypes code:
while (true) {
let length = ostypes.API('read')(fd, buf, count);
length = parseInt(cutils.jscGetDeepest(length));
if (length == -1) {
throw new Error({
name: 'os-api-error',
message: 'Failed to read during poll',
uniEerrno: ctypes.errno
});
} else if (!length==0) {
// then its > 0 as its not -1
// something happend, read struct
let FSChanges = [];
var i = 0;
var numElementsRead = 0;
length = parseInt(cutils.jscGetDeepest(length));
var _cache_aRenamed_local = {}; // local means per buffer
do {
let iHoisted = i;
numElementsRead++;
var casted = ctypes.cast(buf.addressOfElement(iHoisted), ostypes.TYPE.inotify_event.ptr).contents;
var fileName = casted.addressOfField('name').contents.readString();
var mask = casted.addressOfField('mask').contents;
var len = casted.addressOfField('len').contents;
var cookie = cutils.jscGetDeepest(casted.addressOfField('cookie').contents)
var wd = casted.addressOfField('wd').contents;
var aEvent = convertFlagsToAEventStr(mask);
if (aEvent == 'renamed-to') {
if (cookie in _cache_aRenamed_local) { // assuming that renamed-from must happen before rename-to otherwise its a added
if (_cache_aRenamed_local[cookie].aExtra.aOSPath_parentDir_identifier == wd) { // aOSPath_parentDir_identifier is a wd if its different then the current wd then it was added/removed from that watched dir
var rezObj = {
aFileName: fileName,
aEvent: 'renamed',
aExtra: {
nixInotifyFlags: mask, // i should pass this, as if user did modify the flags, they might want to figure out what exactly changed
aOSPath_parentDir_identifier: wd,
aOld: {
aFileName: _cache_aRenamed_local[cookie].aFileName,
aExtra: {
nixInotifyFlags: _cache_aRenamed_local[cookie].aExtra.nixInotifyFlags
}
}
}
}
FSChanges.push(rezObj);
} else {
// the one in cache was removed from its parent folder, this one here was added to parent folder. so this is detect as file moved from one watched dir to another watched dir
if (_cache_aRenamed_local[cookie].aFileName != fileName) {
console.error('whaaaaa wd\'s are differnt and got renamed-to so names should be same');
_cache_aRenamed_local[cookie].aEvent = 'haaa names are different?? im just going to say REMOVED as a guess i have never encoutnered this situation yet and i dont think we ever should';
FSChanges.push(_cache_aRenamed_local[cookie]);
} else {
_cache_aRenamed_local[cookie].aEvent = 'removed';
FSChanges.push(_cache_aRenamed_local[cookie]);
}
}
delete _cache_aRenamed_local[cookie];
} else {
var rezObj = {
aFileName: fileName,
aEvent: 'added',
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
FSChanges.push(rezObj);
}
} else if (aEvent == 'renamed-from') {
var rezObj = {
aFileName: fileName,
aEvent: aEvent,
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
_cache_aRenamed_local[cookie] = rezObj;
} else {
var rezObj = {
aFileName: fileName,
aEvent: aEvent,
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
FSChanges.push(rezObj);
}
if (len == 0) {
break;
};
i += nixStuff.sizeField0 + nixStuff.sizeField1 + nixStuff.sizeField2 + nixStuff.sizeField3 + parseInt(len);
} while (i < length);
for (var cookieLeft in _cache_aRenamed_local) {
// whatever is left in _cache_aRenamed_local is `removed` things
_cache_aRenamed_local[cookieLeft].aEvent = 'removed';
FSChanges.push(rezObj);
}
console.error('loop ended:', 'numElementsRead:', numElementsRead);
if (FSChanges.length > 0) {
return FSChanges;
} // else dont return and continue loop
}
}
I use this function to convert the flags to a string of like renamed-from or renamed-to
function convertFlagsToAEventStr(flags) {
var default_flags = {
IN_CLOSE_WRITE: 'contents-modified',
IN_MOVED_TO: 'renamed-to', // can also be a added
IN_DELETE: 'removed',
IN_MOVED_FROM: 'renamed-from', // can also be a removed
IN_CREATE: 'added'
};
for (var f in default_flags) {
if (flags & ostypes.CONST[f]) {
return default_flags[f];
}
}
return 'UNKNOWN FLAG';
}
I need to get a count of all selected files using Telerik MVC Upload Control. Can anyone tell me how can i do that. I tried code like this.
var count = e.files.length;
But its counting always as one.
try this code
[function onSelect(e) {
var selectedFiles = e.files.length;
totalFiles += selectedFiles;
}
function UploadRemove(e) {
totalFiles--;
if (totalFiles > 0) {
// Write true block code here.
}
else if (totalFiles == 0) {
// Write your false block code here.
}
}]
You could do this in your upload event handler:
upload: function (e) {
// File Count:
var fileCount = this.wrapper.find(".k-file").length;
// File Index:
var uid = e.files[0].uid;
var file = this.wrapper.find(".k-file[data-uid='" + uid + "']");
var fileIndex = file.index();
}