From 6cc2edbb46cf36fdfc467d0c578892931269030a Mon Sep 17 00:00:00 2001 From: Joan Marin Date: Tue, 1 Jan 2019 21:35:34 -0600 Subject: [PATCH] Fixes for memory leaks --- commands/admin/autoresponse.js | 67 ++++++++++++++++++------------- commands/admin/shameboard.js | 41 ++++++++++--------- commands/admin/starboard.js | 41 ++++++++++--------- commands/admin/tag.js | 48 +++++++++++----------- commands/admin/untag.js | 30 ++++++++------ commands/general/tts.js | 53 ++++++++++++------------ commands/general/ttsvc.js | 71 +++++++++++++++++---------------- commands/images/idubbbz.js | 15 +++---- commands/images/idubbbzpaint.js | 17 ++++---- commands/images/like.js | 11 ++--- commands/images/ugly.js | 11 ++--- commands/utility/avatar.js | 2 +- commands/utility/download.js | 43 ++++++++++---------- commands/utility/taglist.js | 42 ++++++++++--------- commands/utility/translate.js | 50 +++++++++++------------ 15 files changed, 294 insertions(+), 248 deletions(-) diff --git a/commands/admin/autoresponse.js b/commands/admin/autoresponse.js index c6f78f7a..0639cbe8 100644 --- a/commands/admin/autoresponse.js +++ b/commands/admin/autoresponse.js @@ -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; \ No newline at end of file diff --git a/commands/admin/shameboard.js b/commands/admin/shameboard.js index ffab6b08..b43240a8 100644 --- a/commands/admin/shameboard.js +++ b/commands/admin/shameboard.js @@ -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`); } } diff --git a/commands/admin/starboard.js b/commands/admin/starboard.js index c49fd346..9249859b 100644 --- a/commands/admin/starboard.js +++ b/commands/admin/starboard.js @@ -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`); } } diff --git a/commands/admin/tag.js b/commands/admin/tag.js index c5cf319d..e7bcd61f 100644 --- a/commands/admin/tag.js +++ b/commands/admin/tag.js @@ -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}`); } } diff --git a/commands/admin/untag.js b/commands/admin/untag.js index d2be14d0..0a7ee196 100644 --- a/commands/admin/untag.js +++ b/commands/admin/untag.js @@ -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}`); } diff --git a/commands/general/tts.js b/commands/general/tts.js index 188c25c9..a9e87b58 100644 --- a/commands/general/tts.js +++ b/commands/general/tts.js @@ -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; \ No newline at end of file diff --git a/commands/general/ttsvc.js b/commands/general/ttsvc.js index e1388019..4b762415 100644 --- a/commands/general/ttsvc.js +++ b/commands/general/ttsvc.js @@ -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!'); - // 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)); - }); + } 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; \ No newline at end of file diff --git a/commands/images/idubbbz.js b/commands/images/idubbbz.js index 8a77377f..7fea85e3 100644 --- a/commands/images/idubbbz.js +++ b/commands/images/idubbbz.js @@ -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 ') - .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); diff --git a/commands/images/idubbbzpaint.js b/commands/images/idubbbzpaint.js index 336ca334..1115e64a 100644 --- a/commands/images/idubbbzpaint.js +++ b/commands/images/idubbbzpaint.js @@ -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 ') - .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); diff --git a/commands/images/like.js b/commands/images/like.js index d7307f42..e26496bd 100644 --- a/commands/images/like.js +++ b/commands/images/like.js @@ -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 ') - .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 => { diff --git a/commands/images/ugly.js b/commands/images/ugly.js index 5cbad486..0792b981 100644 --- a/commands/images/ugly.js +++ b/commands/images/ugly.js @@ -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 ') - .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 => { diff --git a/commands/utility/avatar.js b/commands/utility/avatar.js index a6372da7..012a5e35 100644 --- a/commands/utility/avatar.js +++ b/commands/utility/avatar.js @@ -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}`); diff --git a/commands/utility/download.js b/commands/utility/download.js index 8632b645..a0d409d0 100644 --- a/commands/utility/download.js +++ b/commands/utility/download.js @@ -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 ').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"); + } } } diff --git a/commands/utility/taglist.js b/commands/utility/taglist.js index 89c55c15..28d03317 100644 --- a/commands/utility/taglist.js +++ b/commands/utility/taglist.js @@ -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?'); } } } diff --git a/commands/utility/translate.js b/commands/utility/translate.js index 105a21d6..34c584b5 100644 --- a/commands/utility/translate.js +++ b/commands/utility/translate.js @@ -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) + }); } }