Merge branch 'memoryLeaksFixes' into 'master'

Fixes for memory leaks

See merge request LoicBersier/DiscordBot!1
This commit is contained in:
Loïc Bersier 2019-01-02 04:46:37 +00:00
commit e2ddba01c7
15 changed files with 294 additions and 248 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -28,30 +28,33 @@ class TtsCommand extends Command {
// Construct the request // Construct the request
const request = { const request = {
input: {text: text}, input: { text: text },
// Select the language and SSML Voice Gender (optional) // 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 // Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'}, audioConfig: { audioEncoding: 'MP3' },
}; };
// Performs the Text-to-Speech request // Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => { gclient.synthesizeSpeech(request, (err, response) => {
if (err) { if (err) {
fs.close();
console.error('ERROR:', err); console.error('ERROR:', err);
return; return;
} }
// Write the binary audio content to a local file // Write the binary audio content to a local file
fs.writeFile('tts.mp3', response.audioContent, 'binary', err => { await fs.writeFile('tts.mp3', response.audioContent, 'binary', err => {
if (err) { if (err) {
console.error('ERROR:', 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; return;
} }
console.log('Audio content written to file: tts.mp3'); console.log('Audio content written to file: tts.mp3');
message.channel.send({files: ['./tts.mp3']}) message.channel.send({ files: ['./tts.mp3'] })
}); });
fs.close();
}); });
} }
} }

View file

@ -31,11 +31,11 @@ class TtsvcCommand extends Command {
// Construct the request // Construct the request
const request = { const request = {
input: {text: text}, input: { text: text },
// Select the language and SSML Voice Gender (optional) // 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 // Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'}, audioConfig: { audioEncoding: 'MP3' },
}; };
// Performs the Text-to-Speech request // Performs the Text-to-Speech request
@ -49,7 +49,8 @@ class TtsvcCommand extends Command {
fs.writeFile('ttsvc.mp3', response.audioContent, 'binary', err => { fs.writeFile('ttsvc.mp3', response.audioContent, 'binary', err => {
if (err) { if (err) {
console.error('ERROR:', 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; return;
} }
console.log('Audio content written to file: ttsvc.mp3'); console.log('Audio content written to file: ttsvc.mp3');
@ -58,19 +59,21 @@ class TtsvcCommand extends Command {
if (!voiceChannel) { if (!voiceChannel) {
return message.reply('please join a voice channel first!'); return message.reply('please join a voice channel first!');
} else } 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 user say "stop" make the bot leave voice channel
if (text == 'stop') { if (text == 'stop') {
voiceChannel.leave(); voiceChannel.leave();
message.channel.send('I leaved the channel'); message.channel.send('I leaved the channel');
} else } else { // you should be careful in what is included in your scopes, you didn't use the {}
voiceChannel.join().then(connection => { voiceChannel.join().then(connection => {
const dispatcher = connection.playStream('./ttsvc.mp3'); const dispatcher = connection.playStream('./ttsvc.mp3');
// End at then end of the audio stream // End at then end of the audio stream
dispatcher.on('end', () => setTimeout(function(){ dispatcher.on('end', () => setTimeout(function () {
voiceChannel.leave(); voiceChannel.leave();
}, 2000)); }, 2000));
}); });
}
}
}); });
}); });
} }

View file

@ -28,10 +28,10 @@ class IdubbbzCommand extends Command {
let image = args.image; let image = args.image;
if (!Attachment[0] && !image) if (!Attachment[0] && !image)
image = message.author.displayAvatarURL 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') return message.channel.send('Gif dosent work, sorry')
else if (!image) else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>') message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(2000)) .then(loadingmsg => loadingmsg.delete(2000))
@ -51,6 +51,7 @@ class IdubbbzCommand extends Command {
// Return the result to use in the actual canvas // Return the result to use in the actual canvas
return ctx.font; return ctx.font;
}; };
}
const ctx = canvas.getContext('2d') const ctx = canvas.getContext('2d')
const background = await loadImage(image); const background = await loadImage(image);

View file

@ -27,10 +27,10 @@ class IdubbbzPaintCommand extends Command {
let image = args.image; let image = args.image;
if (!Attachment[0] && !image) if (!Attachment[0] && !image)
image = message.author.displayAvatarURL 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') return message.channel.send('Gif dosent work, sorry')
else if (!image) else if (!image) { // // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>') message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(2000)) .then(loadingmsg => loadingmsg.delete(2000))
@ -50,6 +50,7 @@ class IdubbbzPaintCommand extends Command {
// Return the result to use in the actual canvas // Return the result to use in the actual canvas
return ctx.font; return ctx.font;
}; };
}
const ctx = canvas.getContext('2d') const ctx = canvas.getContext('2d')
const background = await loadImage(image); const background = await loadImage(image);

View file

@ -22,13 +22,14 @@ class LikeCommand extends Command {
let image = args.image; let image = args.image;
if (!Attachment[0] && !image) if (!Attachment[0] && !image)
image = message.author.displayAvatarURL 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') return message.channel.send('Gif dosent work, sorry')
else if (!image) else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>') message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(1000)) .then(loadingmsg => loadingmsg.delete(1000));
}
const canvas = createCanvas(386, 399) const canvas = createCanvas(386, 399)
const ctx = canvas.getContext('2d') const ctx = canvas.getContext('2d')

View file

@ -22,13 +22,14 @@ class UglyCommand extends Command {
let image = args.image; let image = args.image;
if (!Attachment[0] && !image) if (!Attachment[0] && !image)
image = message.author.displayAvatarURL 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') return message.channel.send('Gif dosent work, sorry')
else if (!image) else if (!image) { // you should be careful in what is included in your scopes, you didn't use the {}
image = Attachment[0].url image = Attachment[0].url;
message.channel.send('Processing <a:loadingmin:527579785212329984>') message.channel.send('Processing <a:loadingmin:527579785212329984>')
.then(loadingmsg => loadingmsg.delete(1000)) .then(loadingmsg => loadingmsg.delete(1000));
}
const canvas = createCanvas(323, 400) const canvas = createCanvas(323, 400)
const ctx = canvas.getContext('2d') const ctx = canvas.getContext('2d')

View file

@ -20,7 +20,7 @@ class AvatarCommand extends Command {
} }
async exec(message, args) { 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}`); return message.channel.send(`Your avatar:\n${message.author.displayAvatarURL}`);
else else
return message.channel.send(`${args.user.username}'s avatar:\n${args.user.displayAvatarURL}`); return message.channel.send(`${args.user.username}'s avatar:\n${args.user.displayAvatarURL}`);

View file

@ -24,28 +24,31 @@ class DownloadCommand extends Command {
}); });
} }
async exec(message,args) { async exec(message, args) {
let link = args.link; 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 => { message.channel.send('Downloading <a:loadingmin:527579785212329984>').then(msg => {
video.on('end', function() { video.on('end', function () {
msg.delete() msg.delete()
}) });
}) });
let video = youtubedl(link, [`--username=${fbuser}`,`--password=${fbpasswd}`]) let video = youtubedl(link, [`--username=${fbuser}`, `--password=${fbpasswd}`])
video.pipe(fs.createWriteStream('./video.mp4')) video.pipe(fs.createWriteStream('./video.mp4'));
video.on('error', function error(err) { video.on('error', function error(err) {
console.log('error 2:', err); console.log('error 2:', err);
message.channel.send("An error has occured, i can't download from the link you provided.") message.channel.send("An error has occured, I can't download from the link you provided.")
}); });
video.on('end', function() { video.on('end', function () {
message.delete(); message.delete();
message.channel.send(`Downloaded by ${message.author.username}`, {files: ["./video.mp4"]}) message.channel.send(`Downloaded by ${message.author.username}`, { files: ["./video.mp4"] })
.catch(() => message.channel.send('File too big')) .catch(() => message.channel.send('File too big'));
}) fs.close();
} else });
message.channel.send("You need to input a valid link") } else {
fs.close();
message.channel.send("You need to input a valid link");
}
} }
} }

View file

@ -23,9 +23,13 @@ class taglistCommand extends Command {
let count = Object.keys(customresponse).length let count = Object.keys(customresponse).length
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){ await fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data) {
if (err) { if (err) {
console.log(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) let json = JSON.stringify(data)
json = json.replace(/[{}"\\]+/g, '') json = json.replace(/[{}"\\]+/g, '')
@ -38,8 +42,10 @@ class taglistCommand extends Command {
message.channel.send(tagEmbed); message.channel.send(tagEmbed);
}); });
fs.close();
} catch { } 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

@ -34,7 +34,7 @@ class TranslationCommand extends Command {
let text = args.text; let text = args.text;
let textURI = encodeURI(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) => { }).then((response) => {
return response.json(); return response.json();
}).then((response) => { }).then((response) => {