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) {
console.log(err); fs.close();
} else { console.log(err);
} 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);
} }
})}})}; })
}
return message.channel.send(`Autoresponse have been ${text}d`); })
}} };
fs.close();
return message.channel.send(`Autoresponse have been ${text}d`);
}
}
module.exports = autoresponseCommand; module.exports = autoresponseCommand;

View file

@ -19,24 +19,29 @@ 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);
} }
return message.channel.send(`This channel have been set as the shameboard`); fs.close();
}) return message.channel.send(`This channel have been set as the shameboard`);
} else { })
let shameboard = JSON.parse(data); //now it an object } else {
shameboard ['shameboard'] = shameboardChannel; let shameboard = JSON.parse(data); //now it an object
var json = JSON.stringify(shameboard); //convert it back to json shameboard['shameboard'] = shameboardChannel;
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function(err) { var json = JSON.stringify(shameboard); //convert it back to json
if(err) { fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function (err) {
return console.log(err); if (err) {
} fs.close();
})}}); return console.log(err);
return message.channel.send(`This channel have been set as the shameboard`); }
})
}
});
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) { 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);
} }
return message.channel.send(`This channel have been set as the starboard`); fs.close();
}) return message.channel.send(`This channel have been set as the starboard`);
} else { })
let starboard = JSON.parse(data); //now it an object } else {
starboard ['starboard'] = starboardChannel; let starboard = JSON.parse(data); //now it an object
var json = JSON.stringify(starboard); //convert it back to json starboard['starboard'] = starboardChannel;
fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function(err) { var json = JSON.stringify(starboard); //convert it back to json
if(err) { fs.writeFile(`./starboard/${message.guild.id}.json`, json, 'utf8', function (err) {
return console.log(err); if (err) {
} fs.close();
})}}); return console.log(err);
return message.channel.send(`This channel have been set as the starboard`); }
})
}
});
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; let response = args.response;
trigger = trigger.toLowerCase(); trigger = trigger.toLowerCase();
do { do {
trigger = trigger.replace('--', ' ') trigger = trigger.replace('--', ' ');
} while (trigger.includes('--')) } while (trigger.includes('--'))
let customresponse = {}
let json = JSON.stringify(customresponse)
let 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){ 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);
} }
})}}); })
}
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; let trigger = args.trigger;
trigger = trigger.toLowerCase(); trigger = trigger.toLowerCase();
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){ 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) {
return console.log(err); fs.close();
} 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

@ -25,34 +25,37 @@ class TtsCommand extends Command {
async exec(message, args) { async exec(message, args) {
let text = args.text; let text = args.text;
// 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) {
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) { 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); 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();
});
} }
} }
module.exports = TtsCommand; module.exports = TtsCommand;

View file

@ -29,50 +29,53 @@ class TtsvcCommand extends Command {
const { voiceChannel } = message.member; const { voiceChannel } = message.member;
// 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) {
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('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');
return; fs.close();
} return;
console.log('Audio content written to file: ttsvc.mp3'); }
console.log('Audio content written to file: ttsvc.mp3');
// If not in voice channel ask user to join // If not in voice channel ask user to join
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));
}); });
}
}
}); });
}); });
} }
} }
module.exports = TtsvcCommand; module.exports = TtsvcCommand;

View file

@ -28,29 +28,30 @@ 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))
const canvas = createCanvas(1281, 627) const canvas = createCanvas(1281, 627)
const applyText = (canvas, text) => { const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
// Declare a base size of the font // Declare a base size of the font
let fontSize = 50; let fontSize = 50;
do { do {
// Assign the font to the context and decrement it so it can be measured again // Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`; ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 700 - 300); } while (ctx.measureText(text).width > 700 - 300);
// 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,29 +27,30 @@ 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))
const canvas = createCanvas(1024, 544) const canvas = createCanvas(1024, 544)
const applyText = (canvas, text) => { const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
// Declare a base size of the font // Declare a base size of the font
let fontSize = 100; let fontSize = 100;
do { do {
// Assign the font to the context and decrement it so it can be measured again // Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`; ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 800 - 300); } while (ctx.measureText(text).width > 800 - 300);
// 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')
@ -39,7 +40,7 @@ class LikeCommand extends Command {
}) })
const bg = await loadImage(buffer); const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height); ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'like.png'); const attachment = new Discord.Attachment(canvas.toBuffer(), 'like.png');
message.channel.send(attachment).catch(error => { message.channel.send(attachment).catch(error => {

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')
@ -39,7 +40,7 @@ class UglyCommand extends Command {
const { body: buffer } = await superagent.get(image); const { body: buffer } = await superagent.get(image);
const bg = await loadImage(buffer); const bg = await loadImage(buffer);
ctx.drawImage(bg, 40, 100, 250, 250); ctx.drawImage(bg, 40, 100, 250, 250);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'ugly.png'); const attachment = new Discord.Attachment(canvas.toBuffer(), 'ugly.png');
message.channel.send(attachment).catch(error => { message.channel.send(attachment).catch(error => {

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

@ -17,35 +17,38 @@ class DownloadCommand extends Command {
], ],
clientPermissions: ['ATTACH_FILES'], clientPermissions: ['ATTACH_FILES'],
description: { description: {
content: 'Download videos from different website from the link you provided', content: 'Download videos from different website from the link you provided',
usage: '[link]', usage: '[link]',
examples: ['https://www.youtube.com/watch?v=6n3pFFPSlW4'] examples: ['https://www.youtube.com/watch?v=6n3pFFPSlW4']
} }
}); });
} }
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

@ -10,10 +10,10 @@ class taglistCommand extends Command {
category: 'utility', category: 'utility',
channelRestriction: 'guild', channelRestriction: 'guild',
description: { description: {
content: 'Show the list of tag for this server.', content: 'Show the list of tag for this server.',
usage: '', usage: '',
examples: [''] examples: ['']
} }
}); });
} }
@ -21,25 +21,31 @@ class taglistCommand extends Command {
try { try {
let customresponse = new SelfReloadJSON(`./tag/${message.guild.id}.json`); let customresponse = new SelfReloadJSON(`./tag/${message.guild.id}.json`);
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:
let json = JSON.stringify(data) fs.close();
json = json.replace(/[{}"\\]+/g, '') return;
json = json.replace(/,+/g, '\n') */
const tagEmbed = new Discord.RichEmbed() }
let json = JSON.stringify(data)
json = json.replace(/[{}"\\]+/g, '')
json = json.replace(/,+/g, '\n')
const tagEmbed = new Discord.RichEmbed()
.setColor("#ff9900") .setColor("#ff9900")
.setTitle('Tags list') .setTitle('Tags list')
.setDescription(`Trigger:Response\n\n${json}`) .setDescription(`Trigger:Response\n\n${json}`)
.setFooter(`You have ${count} tags on this server`) .setFooter(`You have ${count} tags on this server`)
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

@ -22,40 +22,40 @@ class TranslationCommand extends Command {
} }
], ],
description: { 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/', 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]', usage: '[language code] [Text to translate]',
examples: ['fr What are we doing today?', 'en Que faisons-nous aujourd\'hui?'] examples: ['fr What are we doing today?', 'en Que faisons-nous aujourd\'hui?']
} }
}); });
} }
async exec(message, args) { async exec(message, args) {
let language = args.language; let language = args.language;
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) => {
if (response.code == '502') 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/`) 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') else if (response.code != '200')
return message.channel.send('An error has occured') return message.channel.send('An error has occured')
const translationEmbed = new Discord.RichEmbed() const translationEmbed = new Discord.RichEmbed()
.setColor('#0099ff') .setColor('#0099ff')
.setTitle('Asked for the following translation:') .setTitle('Asked for the following translation:')
.setAuthor(message.author.username) .setAuthor(message.author.username)
.setDescription(response.text[0]) .setDescription(response.text[0])
.addField('Original text', text) .addField('Original text', text)
.addField('Translated from', response.detected.lang) .addField('Translated from', response.detected.lang)
.setTimestamp() .setTimestamp()
.setFooter('Powered by Yandex.Translate '); .setFooter('Powered by Yandex.Translate ');
message.channel.send(translationEmbed) message.channel.send(translationEmbed)
}); });
} }
} }