Discord.JS Purge.js command issue - module

Ok so my bot got rebuilt with a somewhat different code.
I'm using a somewhat more simplified fs command and events handler. My command works as intended.
But I'm wanting to add the amount pruned into the fields for the richEmbed and it keeps erroring out.
Here is my purge.js file
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", "missing code here", false)
.addField("User Pins Purged", "missing code here", false)
.addField("User Messages Purged", "missing code here", false)
.addField("Total Messages Purged", "missing code here", false)
message.channel.send({ embed });
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};
If it helps this i my index.js
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./token.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
console.log(file,command)
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if(!file.endsWith('.js')) return;
const eventFunction = require(`./events/${file}`);
console.log(eventFunction)
eventFunction.execute(client)
});
});
client.login(token);
and this is my message.js
const { prefix } = require('./prefix.json');
module.exports = {
name: 'message',
description: '',
execute:function(client) {
client.on('message',message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
}};
Basically I'm trying to figure out what to place into the "missing code here" sections. Also any way to lock it to people with Administrator permissions only would be useful as well. I attempted that but it failed to work with the embed.

If I understand you right you want to know how to get the amount of the purged pins, bot msgs and user msgs. For this you need to put your embed after you deleted the messages.
purge.js
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).then(deletedMessages => {
// Filter the deleted messages with .filter()
var botMessages = deletedMessages.filter(m => m.author.bot);
var userPins = deletedMessages.filter(m => m.pinned);
var userMessages = deletedMessages.filter(m => !m.author.bot);
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", botMessages.size, false)
.addField("User Pins Purged", userPins.size, false)
.addField("User Messages Purged", userMessages.size, false)
.addField("Total Messages Purged", deletedMessages.size, false);
message.channel.send(embed);
}).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};

Related

Converting a docx Node.js buffer into pdf file

I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.
`
exports.Resolution = functions.https.onCall(async (data, context) => {
const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
const templateRef = await admin.storage().bucket()
.file(file_name);
const template_content = (await templateRef.download())[0];
const zip = new PizZip(template_content);
let doc;
try {
doc = new Docxtemplater(zip, { linebreaks: true });
} catch (error) {
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
errorHandler(error);
}
doc.setData({
date: data.date,
investorName: data.investorName,
companyName: data.companyName,
regNo: data.regNo,
agreements: data.agreements,
governmentEntity: data.governmentEntity,
directors: data.directors,
equityStake: data.equityStake,
governmentEntityName: data.governmentEntityName,
fccp: data.fccp,
investorDirector:data.investorDirector,
equity: data.equity
});
try {
doc.render();
} catch (error) {
errorHandler(error);
}
const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });
const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
const printer = new PdfPrinter(fontss);
const chunks = [];
const pdfDoc = printer.createPdfKitDocument(contentBuffer);
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('end', async () => {
const result = Buffer.concat(chunks);
function mail (){
const dest = context.auth.token.email;
const mailOptions = {
from: 'MPC <mypocketcounsel#gmail.com>',
to: dest,
cc:data.extraEmail,
subject: 'Resolution Approving Transaction',
text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
attachments: [
{
filename: nameofFile+'.docx',
content: contentBuffer
},
{
filename: nameofFile +'.pdf',
contentType: 'application/pdf',
content: result
}
]
};
// returning result
return transporter.sendMail(mailOptions);
}
return mail();
});
pdfDoc.on('error', (err) => {
return functions.logger.log('An error occured!');
});
pdfDoc.end();
});
`
This is the function that generates both the docx file and the pdf for me.

Getting "spc message cannot be null" as response

Getting "spc message cannot be null" as response every time while providing implementation of Shaka player to play fairplay content on safari browser.Tried many ways to provide spc message in body and header also and we are actually sending it that i can see in network tab nut still cant find a solution. Here is the code below.
if (this.platform.getBrowserPlatform() === Constants.PLATFORMS.SAFARI_WEB) {
this.shakaPlayer.configure({
drm: {
servers: {
'com.apple.fps.1_0': `${this.config.baseUrl}${Constants.DRM_FAIRPLAY_LICENSE}`,
},
advanced: {
'com.apple.fps.1_0': {
serverCertificate: cert,
},
},
},
});
let that = this //,licenseUri;
this.shakaPlayer.configure('drm.initDataTransform', (initData) => {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
var contentId = skdUri.substring(skdUri.indexOf('skd://') + 6);
// licenseUri = skdUri.replace('skd://', 'https://');
const url = new URL(contentId);
const urlParams = new URLSearchParams(url.search);
const cert = that.shakaPlayer.drmInfo().serverCertificate;
let id = urlParams.get('contentId');
that.id = id;
return shaka.util.FairPlayUtils.initDataTransform(initData, id, cert);
// let skdUrl = shaka.util.StringUtils.fromBytesAutoDetect(initData);
// licenseUri = skdUrl.replace('skd://', 'https://');
// const cert = that.shakaPlayer.drmInfo().serverCertificate;
// return shaka.util.FairPlayUtils.initDataTransform(initData, licenseUri, cert);
});
this.shakaPlayer.getNetworkingEngine().registerRequestFilter((type, request) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
let token = localStorage.getItem('auth');
let testToken = JSON.parse(token);
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = `{ "spc": "${base64Payload}", "assetId":"${that.id}"}`;
request.body = shaka.util.StringUtils.toUTF8(params);
request.headers['Content-Type'] = 'application/json';
request.headers['Authorization'] = `JWT ${testToken.access_token}`
console.log("request.body", request.body)
});
this.shakaPlayer.getNetworkingEngine().registerResponseFilter((type, response) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
console.log("license passed")
let responseText = shaka.util.StringUtils.fromUTF8(response.data);
responseText = responseText.trim();
if (responseText.substr(0, 5) === '<ckc>' &&
responseText.substr(-6) === '</ckc>') {
responseText = responseText.slice(5, -6);
}
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
});
this.shakaPlayer.load(this.getProgramUrl(channel, program, restart)).then(() => {
console.log('1', this.shakaPlayer.isTextTrackVisible());
console.log('2', this.shakaPlayer.getTextTracks());
console.log('3', this.shakaPlayer.getTextLanguages());
}).catch((error) => {
console.log(error);
});
Smooth play of fairplay content on safari or some advise what can i do in this case

Message event broken ( quick.db )

So i wanna get started with quick.db for my discord.js bot. I asked someone to help me solve this issue but they seem to be unable to. So if theres anyone here that can help could you tell me whats wrong with my code
module.exports = (client) => client.on('messageCreate', async (message) => {
const prefix = [].concat(client.config.prefix);
const ms = require('ms');
if (
message.author.bot ||
!message.guild ||
!prefix.some((x) => message.content.toLowerCase().startsWith(x))
)
return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
}); 
the above code is the working one but whenever i use this
module.exports = (client) => client.on('messageCreate', async (message) => {
const ms = require('ms');
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const prefix = db.get(`newprefix_${message.guild.id}`) || config.prefix
if (!prefix) return; 
if (!message.content.startsWith(prefix) || message.author.bot) return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
});  
it doesn't work, meaning my bot doesn't reply

Discord.JS Announce Command Issue

I'm trying to build an announce command for my bot using a rich embed.
Here is my announce.js file:
const Discord = require('discord.js');
module.exports = {
name: 'announce',
description: 'Send an announcement.',
guildOnly: true,
execute(message, args) {
console.log("embedding")
const embed = new Discord.RichEmbed()
.setTitle("Announcement")
.setDescription("A Staff member has sent an announcement")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addBlankField(true)
.addField("Announcement", "message contents here", false))
message.channel.send({ embed });
}
};
I rebuilt it since the post it and took me a while to get back to this post. I'm trying to rebuild all of my messages from my bot into rich embeds. Thus the different code. I've also simplified my fs command and events handler.
indexjs
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./token.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
console.log(file,command)
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if(!file.endsWith('.js')) return;
const eventFunction = require(`./events/${file}`);
console.log(eventFunction)
eventFunction.execute(client)
});
});
client.login(token);
message.js
const { prefix } = require('./prefix.json');
module.exports = {
name: 'message',
description: 'client message event.',
execute:function(client) {
client.on('message',message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
}};
Basically I need to know what to put for "message contents here" to make it post the message typed into the #announcements channel.
My question is how to I make it place the announcement message into the .addField section of the richEmbed?
Would it be something along the lines of this?
const Discord = require('discord.js');
module.exports = {
name: 'announce',
description: 'Send an announcement to the specified channel.',
guildOnly: true,
execute(message, args) {
console.log("embedding")
enter code here
if(args.length < 2) return /* error message */;
let channel = message.mentions.channels.first();
if(!channel) return ;
let announcement = args.slice(1).join(" ");
const embed = new Discord.RichEmbed()
.setTitle("Notice!")
.setDescription("Announcememnt from PhantomDEV Staff!")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addBlankField(true)
.addField("Message", "", false);
message.channel.send({ embed });
.catch(console.error);
};
At the end of your message event, use this line to call the execution of the command...
command.execute(message, args);
Define your execute function to use the args parameter that you need. Also, Collection.first() is the method you're looking for when declaring channel. Your function should look like so...
execute: function(message, args) {
if (args.length < 2) return /* error message */;
// Careful using this; if just an announcement is provided
// and it mentions a channel, that channel will be used.
let channel = message.mentions.channels.first();
if (!channel) return /* error message */;
let announcement = args.slice(1).join(" ");
channel.send(announcement)
.catch(console.error);
}
There's no need to check that the command is "announce" in the execution function, because it'll only be called if it is.

Get password from input using node.js

How to get password from input using node.js? Which means you should not output password entered in console.
You can use the read module (disclosure: written by me) for this:
In your shell:
npm install read
Then in your JS:
var read = require('read')
read({ prompt: 'Password: ', silent: true }, function(er, password) {
console.log('Your password is: %s', password)
})
Update 2015 Dec 13: readline has replaced process.stdin and node_stdio was removed from Node 0.5.10.
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
getPassword('Password: ', (ok, password) => { console.log([ok, password]) } );
To do this I found this excellent Google Group post
Which contains the following snippet:
var stdin = process.openStdin()
, stdio = process.binding("stdio")
stdio.setRawMode()
var password = ""
stdin.on("data", function (c) {
c = c + ""
switch (c) {
case "\n": case "\r": case "\u0004":
stdio.setRawMode(false)
console.log("you entered: "+password)
stdin.pause()
break
case "\u0003":
process.exit()
break
default:
password += c
break
}
})
Here is my tweaked version of nailer's from above, updated to get a callback and for node 0.8 usage:
/**
* Get a password from stdin.
*
* Adapted from <http://stackoverflow.com/a/10357818/122384>.
*
* #param prompt {String} Optional prompt. Default 'Password: '.
* #param callback {Function} `function (cancelled, password)` where
* `cancelled` is true if the user aborted (Ctrl+C).
*
* Limitations: Not sure if backspace is handled properly.
*/
function getPassword(prompt, callback) {
if (callback === undefined) {
callback = prompt;
prompt = undefined;
}
if (prompt === undefined) {
prompt = 'Password: ';
}
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch + "";
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
How to use read without a callback
With async/await, we can get rid of the annoying callback with the following standard pattern:
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
if (err) {
reject(err)
} else {
resolve(line)
}
})
})
}
;(async () => {
const password = await read({ prompt: 'Password: ', silent: true })
console.log(password)
})()
The annoyance is that then you have to propagate async/await to the entire call stack, but it is generally the way to go, as it clearly marks what is async or not.
Tested on "read": "1.0.7", Node.js v14.17.0.
TODO how to prevent EAGAIN error if you try to use stdin again later with fs.readFileSync(0)?
Both read and https://stackoverflow.com/a/10357818/895245 cause future attempts to read from stdin with fs.readFileSync(0) to break with EAGAIN. Not sure how to fix that. Reproduction:
const fs = require('fs')
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read({ prompt: 'Password: ', silent: true })
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
or:
#!/usr/bin/env node
const fs = require('fs')
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
async function read(opts) {
return new Promise((resolve, reject) => {
getPassword(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read('Password: ')
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
Error:
fs.js:614
handleErrorFromBinding(ctx);
^
Error: EAGAIN: resource temporarily unavailable, read
at Object.readSync (fs.js:614:3)
at tryReadSync (fs.js:383:20)
at Object.readFileSync (fs.js:420:19)
at /home/ciro/test/main.js:70:18
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
errno: -11,
syscall: 'read',
code: 'EAGAIN'
}
Asked at: https://github.com/npm/read/issues/39