Fixes for memory leaks

This commit is contained in:
Joan Marin 2019-01-01 21:35:34 -06:00
parent 5859a58b2b
commit 6cc2edbb46
Signed by untrusted user: joan
GPG key ID: 750B6742D9C69D6E
15 changed files with 294 additions and 248 deletions

View file

@ -30,43 +30,54 @@ class autoresponseCommand extends Command {
let text = args.text;
let all = args.all;
let autoresponse = {}
let json = JSON.stringify(autoresponse)
let autoresponse = {};
let json = JSON.stringify(autoresponse);
if (all == 'all') {
const guild = this.client.guilds.get(message.guild.id);
if (all == 'all') {
const guild = this.client.guilds.get(message.guild.id);
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data) {
if (err) {
fs.close();
console.log(err);
} else {
autoresponse = JSON.parse(data); //now it an object
guild.channels.forEach(channel => autoresponse [channel] = text)
guild.channels.forEach(channel => autoresponse[channel] = text);
json = JSON.stringify(autoresponse); //convert it back to json
json = json.replace(/[<#>]/g, '')
fs.writeFile('./json/autoresponse.json', json, 'utf8', function(err) {
if(err) {
json = json.replace(/[<#>]/g, '');
fs.writeFile('./json/autoresponse.json', json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})}});
}
})
}
});
return message.channel.send('Auto response have been disable/enable on every channel')
fs.close();
return message.channel.send('Auto response have been disable/enable on every channel');
} else if (text == 'disable' || 'enable') {
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
} else if (text == 'disable' || 'enable') {
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
autoresponse = JSON.parse(data); //now it an object
autoresponse [message.channel.id] = text
autoresponse[message.channel.id] = text;
json = JSON.stringify(autoresponse); //convert it back to json
fs.writeFile('./json/autoresponse.json', json, 'utf8', function(err) {
if(err) {
fs.writeFile('./json/autoresponse.json', json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})}})};
return message.channel.send(`Autoresponse have been ${text}d`);
}}
}
})
}
})
};
fs.close();
return message.channel.send(`Autoresponse have been ${text}d`);
}
}
module.exports = autoresponseCommand;

View file

@ -19,24 +19,29 @@ class shameboardCommand extends Command {
async exec(message) {
let shameboardChannel = message.channel.id;
fs.readFile(`./starboard/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err){
fs.writeFile(`./starboard/${message.guild.id}.json`, `{"shameboard": "${shameboardChannel}"}`, function (err) {
if (err){
console.log(err);
}
return message.channel.send(`This channel have been set as the shameboard`);
})
} else {
let shameboard = JSON.parse(data); //now it an object
shameboard ['shameboard'] = shameboardChannel;
var json = JSON.stringify(shameboard); //convert it back to json
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function(err) {
if(err) {
return console.log(err);
}
})}});
return message.channel.send(`This channel have been set as the shameboard`);
fs.readFile(`./starboard/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) {
fs.writeFile(`./starboard/${message.guild.id}.json`, `{"shameboard": "${shameboardChannel}"}`, function (err) {
if (err) {
console.log(err);
}
fs.close();
return message.channel.send(`This channel have been set as the shameboard`);
})
} else {
let shameboard = JSON.parse(data); //now it an object
shameboard['shameboard'] = shameboardChannel;
var json = JSON.stringify(shameboard); //convert it back to json
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})
}
});
fs.close();
return message.channel.send(`This channel have been set as the shameboard`);
}
}

View file

@ -19,24 +19,29 @@ class StarBoardCommand extends Command {
async exec(message) {
let starboardChannel = message.channel.id;
fs.readFile(`./starboard/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err){
fs.writeFile(`./starboard/${message.guild.id}.json`, `{"starboard": "${starboardChannel}"}`, function (err) {
if (err){
console.log(err);
}
return message.channel.send(`This channel have been set as the starboard`);
})
} else {
let starboard = JSON.parse(data); //now it an object
starboard ['starboard'] = starboardChannel;
var json = JSON.stringify(starboard); //convert it back to json
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function(err) {
if(err) {
return console.log(err);
}
})}});
return message.channel.send(`This channel have been set as the starboard`);
fs.readFile(`./starboard/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) {
fs.writeFile(`./starboard/${message.guild.id}.json`, `{"starboard": "${starboardChannel}"}`, function (err) {
if (err) {
console.log(err);
}
fs.close();
return message.channel.send(`This channel have been set as the starboard`);
})
} else {
let starboard = JSON.parse(data); //now it an object
starboard['starboard'] = starboardChannel;
var json = JSON.stringify(starboard); //convert it back to json
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})
}
});
fs.close();
return message.channel.send(`This channel have been set as the starboard`);
}
}

View file

@ -31,34 +31,36 @@ class TagCommand extends Command {
let response = args.response;
trigger = trigger.toLowerCase();
do {
trigger = trigger.replace('--', ' ')
} while (trigger.includes('--'))
let customresponse = {}
let json = JSON.stringify(customresponse)
do {
trigger = trigger.replace('--', ' ');
} while (trigger.includes('--'))
let customresponse = {};
let json = JSON.stringify(customresponse);
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err){
fs.writeFile(`./tag/${message.guild.id}.json`, `{"${trigger}":"${response}"}`, function (err) {
if (err){
console.log(err);
}
})
} else {
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) {
fs.writeFile(`./tag/${message.guild.id}.json`, `{"${trigger}":"${response}"}`, function (err) {
if (err) {
fs.close();
console.log(err);
}
})
} else {
customresponse = JSON.parse(data); //now it an object
customresponse [trigger] = response
customresponse[trigger] = response
json = JSON.stringify(customresponse); //convert it back to json
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function(err) {
if(err) {
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})}});
return message.channel.send(`autoresponse have been set to ${trigger} : ${response}`);
}
})
}
});
fs.close();
return message.channel.send(`autoresponse have been set to ${trigger} : ${response}`);
}
}

View file

@ -26,24 +26,28 @@ class UnTagCommand extends Command {
let trigger = args.trigger;
trigger = trigger.toLowerCase();
let customresponse = {}
let json = JSON.stringify(customresponse)
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err){
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
customresponse = JSON.parse(data); //now it an object
delete customresponse[trigger]
json = JSON.stringify(customresponse); //convert it back to json
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function(err) {
if(err) {
return console.log(err);
}
})}});
customresponse = JSON.parse(data); //now it an object
delete customresponse[trigger]
json = JSON.stringify(customresponse); //convert it back to json
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function (err) {
if (err) {
fs.close();
return console.log(err);
}
})
}
});
fs.close();
return message.channel.send(`The following autoresponse have been deleted: ${trigger}`);
}

View file

@ -25,34 +25,37 @@ class TtsCommand extends Command {
async exec(message, args) {
let text = args.text;
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
// Construct the request
const request = {
input: { text: text },
// Select the language and SSML Voice Gender (optional)
voice: { languageCode: 'en-US', ssmlGender: 'NEUTRAL' },
// Select the type of audio encoding
audioConfig: { audioEncoding: 'MP3' },
};
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
if (err) {
fs.close();
console.error('ERROR:', err);
return;
}
// Write the binary audio content to a local file
await fs.writeFile('tts.mp3', response.audioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
return;
}
// Write the binary audio content to a local file
fs.writeFile('tts.mp3', response.audioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
message.channel.send('An error has occured, the message is probably too long')
message.channel.send('An error has occured, the message is probably too long');
fs.close();
return;
}
console.log('Audio content written to file: tts.mp3');
message.channel.send({files: ['./tts.mp3']})
});
});
}
console.log('Audio content written to file: tts.mp3');
message.channel.send({ files: ['./tts.mp3'] })
});
fs.close();
});
}
}
module.exports = TtsCommand;

View file

@ -29,50 +29,53 @@ class TtsvcCommand extends Command {
const { voiceChannel } = message.member;
// Construct the request
const request = {
input: {text: text},
// Construct the request
const request = {
input: { text: text },
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
voice: { languageCode: 'en-US', ssmlGender: 'NEUTRAL' },
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
audioConfig: { audioEncoding: 'MP3' },
};
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
if (err) {
console.error('ERROR:', err);
return;
console.error('ERROR:', err);
return;
}
// Write the binary audio content to a local file
fs.writeFile('ttsvc.mp3', response.audioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
message.channel.send('An error has occured, the message is probably too long')
return;
}
console.log('Audio content written to file: ttsvc.mp3');
if (err) {
console.error('ERROR:', err);
message.channel.send('An error has occured, the message is probably too long');
fs.close();
return;
}
console.log('Audio content written to file: ttsvc.mp3');
// If not in voice channel ask user to join
if (!voiceChannel) {
return message.reply('please join a voice channel first!');
} else
// If user say "stop" make the bot leave voice channel
if (text == 'stop') {
voiceChannel.leave();
message.channel.send('I leaved the channel');
} else
voiceChannel.join().then(connection => {
const dispatcher = connection.playStream('./ttsvc.mp3');
// End at then end of the audio stream
dispatcher.on('end', () => setTimeout(function(){
voiceChannel.leave();
}, 2000));
});
// If not in voice channel ask user to join
if (!voiceChannel) {
return message.reply('please join a voice channel first!');
} else { // you should be careful in what is included in your scopes, you didn't use the {}
// If user say "stop" make the bot leave voice channel
if (text == 'stop') {
voiceChannel.leave();
message.channel.send('I leaved the channel');
} else { // you should be careful in what is included in your scopes, you didn't use the {}
voiceChannel.join().then(connection => {
const dispatcher = connection.playStream('./ttsvc.mp3');
// End at then end of the audio stream
dispatcher.on('end', () => setTimeout(function () {
voiceChannel.leave();
}, 2000));
});
}
}
});
});
});
}
}
module.exports = TtsvcCommand;

View file

@ -28,29 +28,30 @@ class IdubbbzCommand extends Command {
let image = args.image;
if (!Attachment[0] && !image)
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
else if (Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.channel.send('Gif dosent work, sorry')
else if (!image)
image = Attachment[0].url
else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(2000))
.then(loadingmsg => loadingmsg.delete(2000))
const canvas = createCanvas(1281, 627)
const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d');
// Declare a base size of the font
let fontSize = 50;
do {
// Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 700 - 300);
// Return the result to use in the actual canvas
return ctx.font;
};
}
const ctx = canvas.getContext('2d')
const background = await loadImage(image);

View file

@ -27,29 +27,30 @@ class IdubbbzPaintCommand extends Command {
let image = args.image;
if (!Attachment[0] && !image)
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
else if (Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.channel.send('Gif dosent work, sorry')
else if (!image)
image = Attachment[0].url
else if (!image) { // // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(2000))
.then(loadingmsg => loadingmsg.delete(2000))
const canvas = createCanvas(1024, 544)
const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d');
// Declare a base size of the font
let fontSize = 100;
do {
// Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 800 - 300);
// Return the result to use in the actual canvas
return ctx.font;
};
}
const ctx = canvas.getContext('2d')
const background = await loadImage(image);

View file

@ -22,13 +22,14 @@ class LikeCommand extends Command {
let image = args.image;
if (!Attachment[0] && !image)
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
else if (Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.channel.send('Gif dosent work, sorry')
else if (!image)
image = Attachment[0].url
else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(1000))
.then(loadingmsg => loadingmsg.delete(1000));
}
const canvas = createCanvas(386, 399)
const ctx = canvas.getContext('2d')
@ -39,7 +40,7 @@ class LikeCommand extends Command {
})
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'like.png');
message.channel.send(attachment).catch(error => {

View file

@ -22,13 +22,14 @@ class UglyCommand extends Command {
let image = args.image;
if (!Attachment[0] && !image)
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
else if (Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.channel.send('Gif dosent work, sorry')
else if (!image)
image = Attachment[0].url
else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(1000))
.then(loadingmsg => loadingmsg.delete(1000));
}
const canvas = createCanvas(323, 400)
const ctx = canvas.getContext('2d')
@ -39,7 +40,7 @@ class UglyCommand extends Command {
const { body: buffer } = await superagent.get(image);
const bg = await loadImage(buffer);
ctx.drawImage(bg, 40, 100, 250, 250);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'ugly.png');
message.channel.send(attachment).catch(error => {

View file

@ -20,7 +20,7 @@ class AvatarCommand extends Command {
}
async exec(message, args) {
if (!args.user)
if (!args.user) // While these kind of statments work you really should use {}
return message.channel.send(`Your avatar:\n${message.author.displayAvatarURL}`);
else
return message.channel.send(`${args.user.username}'s avatar:\n${args.user.displayAvatarURL}`);

View file

@ -17,35 +17,38 @@ class DownloadCommand extends Command {
],
clientPermissions: ['ATTACH_FILES'],
description: {
content: 'Download videos from different website from the link you provided',
usage: '[link]',
examples: ['https://www.youtube.com/watch?v=6n3pFFPSlW4']
}
content: 'Download videos from different website from the link you provided',
usage: '[link]',
examples: ['https://www.youtube.com/watch?v=6n3pFFPSlW4']
}
});
}
async exec(message,args) {
async exec(message, args) {
let link = args.link;
if(link.includes("http") || link.includes("www")) {
if (link.includes("http") || link.includes("www")) {
message.channel.send('Downloading <a:loadingmin:527579785212329984>').then(msg => {
video.on('end', function() {
msg.delete()
})
})
let video = youtubedl(link, [`--username=${fbuser}`,`--password=${fbpasswd}`])
video.pipe(fs.createWriteStream('./video.mp4'))
video.on('end', function () {
msg.delete()
});
});
let video = youtubedl(link, [`--username=${fbuser}`, `--password=${fbpasswd}`])
video.pipe(fs.createWriteStream('./video.mp4'));
video.on('error', function error(err) {
console.log('error 2:', err);
message.channel.send("An error has occured, i can't download from the link you provided.")
});
video.on('end', function() {
message.channel.send("An error has occured, I can't download from the link you provided.")
});
video.on('end', function () {
message.delete();
message.channel.send(`Downloaded by ${message.author.username}`, {files: ["./video.mp4"]})
.catch(() => message.channel.send('File too big'))
})
} else
message.channel.send("You need to input a valid link")
message.channel.send(`Downloaded by ${message.author.username}`, { files: ["./video.mp4"] })
.catch(() => message.channel.send('File too big'));
fs.close();
});
} else {
fs.close();
message.channel.send("You need to input a valid link");
}
}
}

View file

@ -10,10 +10,10 @@ class taglistCommand extends Command {
category: 'utility',
channelRestriction: 'guild',
description: {
content: 'Show the list of tag for this server.',
usage: '',
examples: ['']
}
content: 'Show the list of tag for this server.',
usage: '',
examples: ['']
}
});
}
@ -21,25 +21,31 @@ class taglistCommand extends Command {
try {
let customresponse = new SelfReloadJSON(`./tag/${message.guild.id}.json`);
let count = Object.keys(customresponse).length
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err) {
console.log(err);
}
let json = JSON.stringify(data)
json = json.replace(/[{}"\\]+/g, '')
json = json.replace(/,+/g, '\n')
const tagEmbed = new Discord.RichEmbed()
await fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
/* do you need it to end here on error? if so uncomment the following code:
fs.close();
return;
*/
}
let json = JSON.stringify(data)
json = json.replace(/[{}"\\]+/g, '')
json = json.replace(/,+/g, '\n')
const tagEmbed = new Discord.RichEmbed()
.setColor("#ff9900")
.setTitle('Tags list')
.setDescription(`Trigger:Response\n\n${json}`)
.setFooter(`You have ${count} tags on this server`)
message.channel.send(tagEmbed);
});
message.channel.send(tagEmbed);
});
fs.close();
} catch {
message.channel.send('An error has occured, do you have any tags on the server?')
fs.close();
message.channel.send('An error has occured, do you have any tags on the server?');
}
}
}

View file

@ -22,40 +22,40 @@ class TranslationCommand extends Command {
}
],
description: {
content: 'Translate what you send in your desired language. You can find the language code here: https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/',
usage: '[language code] [Text to translate]',
examples: ['fr What are we doing today?', 'en Que faisons-nous aujourd\'hui?']
}
content: 'Translate what you send in your desired language. You can find the language code here: https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/',
usage: '[language code] [Text to translate]',
examples: ['fr What are we doing today?', 'en Que faisons-nous aujourd\'hui?']
}
});
}
async exec(message, args) {
let language = args.language;
let text = args.text;
let textURI = encodeURI(text)
fetch(`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandexAPI}&text=${textURI}&lang=${language}&options=1`,{
fetch(`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandexAPI}&text=${textURI}&lang=${language}&options=1`, {
}).then((response) => {
return response.json();
return response.json();
}).then((response) => {
if (response.code == '502')
return message.channel.send(`${response.message}, you probably didin't input the correct language code, you can check them here! https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/`)
else if (response.code != '200')
return message.channel.send('An error has occured')
const translationEmbed = new Discord.RichEmbed()
.setColor('#0099ff')
.setTitle('Asked for the following translation:')
.setAuthor(message.author.username)
.setDescription(response.text[0])
.addField('Original text', text)
.addField('Translated from', response.detected.lang)
.setTimestamp()
.setFooter('Powered by Yandex.Translate ');
message.channel.send(translationEmbed)
});
if (response.code == '502')
return message.channel.send(`${response.message}, you probably didin't input the correct language code, you can check them here! https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/`)
else if (response.code != '200')
return message.channel.send('An error has occured')
const translationEmbed = new Discord.RichEmbed()
.setColor('#0099ff')
.setTitle('Asked for the following translation:')
.setAuthor(message.author.username)
.setDescription(response.text[0])
.addField('Original text', text)
.addField('Translated from', response.detected.lang)
.setTimestamp()
.setFooter('Powered by Yandex.Translate ');
message.channel.send(translationEmbed)
});
}
}