Code Optimization for all files

This commit is contained in:
Raven Scott 2023-01-08 09:50:40 +02:00
parent cb8a312d93
commit 85f2d8d04a
10 changed files with 322 additions and 382 deletions

View File

@ -1,43 +1,31 @@
const {
EmbedBuilder
} = require('discord.js');
var giveMeAJoke = require('give-me-a-joke');
const { EmbedBuilder } = require('discord.js');
const giveMeAJoke = require('give-me-a-joke');
module.exports = {
name: "joke",
description: "Gets a funny joke",
run: async (client, interaction) => {
giveMeAJoke.getRandomDadJoke(function (joke) {
async run(client, interaction) {
let joke = await giveMeAJoke.getRandomDadJoke();
if (joke.includes("?")){
let jokeData = joke.split("?")
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Here is your joke...")
.setDescription(jokeData[0] + "?||" + jokeData[1] + "||")
.setTimestamp()
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({
embeds: [embed]
});
} else {
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Here is your joke...")
.setDescription(joke)
.setTimestamp()
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({
embeds: [embed]
});
}
})
if (joke.includes("?")){
let jokeData = joke.split("?");
joke = `${jokeData[0]}?||${jokeData[1]}||`;
}
const embed = createJokeEmbed(joke, interaction.user);
interaction.editReply({ embeds: [embed] });
},
};
};
function createJokeEmbed(joke, user) {
return new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Here is your joke...")
.setDescription(joke)
.setTimestamp()
.setFooter({
text: `Requested by ${user.tag}`,
iconURL: user.displayAvatarURL()
});
}

View File

@ -1,47 +1,40 @@
const {
EmbedBuilder
} = require('discord.js');
var urban = require('urban')
const isNotDefined = require("is-not-defined");
const { EmbedBuilder } = require('discord.js');
const urban = require('urban');
module.exports = {
name: "urban",
description: "Searches Urban Dictionary",
options: [{
"name": "query",
"description": "The thing you want to search for",
"required": true,
"type": 3 // 6 is type USER
name: "query",
description: "The thing you want to search for",
required: true,
type: 3 // 6 is type USER
}],
run: async (client, interaction) => {
async run(client, interaction) {
let searchWord = interaction.options._hoistedOptions[0].value;
let search = urban(searchWord);
let searchWord = interaction.options._hoistedOptions[0].value
search = urban(searchWord);
let data = await search.first();
search.first(function(data) {
if (!isNotDefined(data)) {
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Results for: " + searchWord)
.setDescription("Definition: " + data.definition)
.addFields({
name: 'Example',
value: data.example
})
.setTimestamp()
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({
embeds: [embed]
});
} else {
return interaction.editReply("Sorry, no results were found!")
}
});
if (data) {
const embed = createUrbanEmbed(data, searchWord, interaction.user);
interaction.editReply({ embeds: [embed] });
} else {
interaction.editReply("Sorry, no results were found!");
}
},
};
};
function createUrbanEmbed(data, searchWord, user) {
return new EmbedBuilder()
.setColor("#FF0000")
.setTitle(`Results for: ${searchWord}`)
.setDescription(`Definition: ${data.definition}`)
.addFields({ name: 'Example', value: data.example })
.setTimestamp()
.setFooter({
text: `Requested by ${user.tag}`,
iconURL: user.displayAvatarURL()
});
}

View File

@ -4,49 +4,40 @@ module.exports = {
name: "8ball",
description: "Ask a question, get a response.",
options: [{
"name": "question",
"description": "The question you would like to ask.",
"required": true,
"type": 3 // 6 is type USER
}],
name: "question",
description: "The question you would like to ask.",
required: true,
type: 3 // 6 is type USER
}],
run: async (client, interaction) => {
let question = interaction.options._hoistedOptions[0].value
let question = interaction.options._hoistedOptions[0].value;
function send(question, message){
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle(question)
.setDescription(message)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
const responses = [
"It is certain",
"It is decidedly so",
"Reply hazy try again",
"Cannot predict now",
"Do not count on it",
"My sources say no",
"Outlook not so good",
"Signs point to yes"
];
const response = responses[Math.floor(Math.random() * responses.length)];
const embed = create8BallEmbed(question, response, interaction.user);
interaction.editReply({ embeds: [embed] });
}
var answer = Math.floor(Math.random() * 8);
if (answer === 0) {
send(question, "it is certain")
}
else if (answer === 1) {
send(question, "It is decidedly so");
}
else if (answer === 2) {
send(question, "Reply hazy try again");
}
else if (answer === 3) {
send(question, "Cannot predict now");
}
else if (answer === 4) {
send(question, "Do not count on it");
}
else if (answer === 5) {
send(question, "My sources say no");
}
else if (answer === 6) {
send(question, "Outlook not so good");
}
else if (answer === 7) {
send(question, "Signs point to yes");
}
},
};
function create8BallEmbed(question, response, user) {
return new EmbedBuilder()
.setColor("#FF0000")
.setTitle(question)
.setDescription(response)
.setTimestamp()
.setFooter({
text: `Requested by ${user.tag}`,
iconURL: user.displayAvatarURL()
});
}

View File

@ -1,26 +1,31 @@
const { EmbedBuilder } = require('discord.js');
var unirest = require('unirest');
const unirest = require('unirest');
module.exports = {
name: "bored",
description: "Find an activity to do when you are bored.",
run: async (client, interaction) => {
unirest
async run(client, interaction) {
let response = await unirest
.get('https://www.boredapi.com/api/activity')
.headers({
'Accept': 'application/json', 'Content-Type': 'application/json',
})
.then((response) => {
let data = response.body
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Here is something to do!")
.setDescription(data.activity)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
interaction.followUp({ embeds: [embed] });
})
});
let data = response.body;
const embed = createBoredEmbed(data, interaction.user);
interaction.followUp({ embeds: [embed] });
},
};
function createBoredEmbed(data, user) {
return new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Here is something to do!")
.setDescription(data.activity)
.setTimestamp()
.setFooter({
text: `Requested by ${user.tag}`,
iconURL: user.displayAvatarURL()
});
}

View File

@ -1,124 +1,82 @@
const {
EmbedBuilder
} = require('discord.js');
const {
AttachmentBuilder
} = require('discord.js');
var download = require('download-file')
const { EmbedBuilder, AttachmentBuilder } = require('discord.js');
const unirest = require('unirest');
const download = require('download-file');
const notDefined = require("is-not-defined");
let phonetic
var unirest = require('unirest');
let meaningsArray = []
function createDictionaryEmbed(word, phonetic, meaningsArray, user) {
return new EmbedBuilder()
.setColor("#FF0000")
.setTitle(word + ": " + phonetic)
.addFields(meaningsArray)
.setTimestamp()
.setFooter({
text: `Requested by ${user.tag}`,
iconURL: `${user.displayAvatarURL()}`
});
}
module.exports = {
name: "dictionary",
description: "Returns information about a word",
options: [{
"name": "word",
"description": "The data you would like inside of the QR",
"required": true,
"type": 3 // 6 is type USER
name: "word",
description: "The data you would like inside of the QR",
required: true,
type: 3 // 6 is type USER
}],
run: async (client, interaction) => {
let rand = Math.floor(Math.random() * 99999).toString();
let word = interaction.options._hoistedOptions[0].value
async run(client, interaction) {
let rand = Math.floor(Math.random() * 99999).toString();
let word = interaction.options._hoistedOptions[0].value;
let meaningsArray = [];
unirest
.get('https://api.dictionaryapi.dev/api/v2/entries/en/' + word)
.headers({
'Accept': 'application/json',
'Content-Type': 'application/json',
})
.then((response) => {
let data = response.body[0]
if (notDefined(data)) {
return interaction.editReply("Sorry, nothing was found!")
}
let response = await unirest
.get(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
.headers({
'Accept': 'application/json',
'Content-Type': 'application/json',
});
if (notDefined(data.phonetics[1])) {
phonetic = ""
} else {
phonetic = data.phonetics[1].text
}
let data = response.body[0];
if (notDefined(data)) {
return interaction.editReply("Sorry, nothing was found!");
}
let audio = data.phonetics[0].audio
if (!audio) {
data.meanings.forEach(wordData => {
if (wordData.definitions[0].example) {
meaningsArray.push({
"name": wordData.partOfSpeech,
"value": wordData.definitions[0].definition + "\nExample: " + wordData.definitions[0].example
})
} else {
meaningsArray.push({
"name": wordData.partOfSpeech,
"value": wordData.definitions[0].definition
})
}
});
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle(word + ": " + phonetic)
.addFields(meaningsArray)
.setTimestamp()
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({
embeds: [embed]
});
meaningsArray = []
rand = Math.floor(Math.random() * 99999).toString();
} else {
// Options for Audio Download
var options = {
directory: "./audio/",
filename: rand + ".mp3"
}
download(audio, options, function(err) {
if (err) throw err
console.log("audio downloaded")
console.log(data.meanings)
data.meanings.forEach(wordData => {
if (wordData.definitions[0].example) {
meaningsArray.push({
"name": wordData.partOfSpeech,
"value": wordData.definitions[0].definition + "\nExample: " + wordData.definitions[0].example
})
} else {
meaningsArray.push({
"name": wordData.partOfSpeech,
"value": wordData.definitions[0].definition
})
}
});
const file = new AttachmentBuilder('./audio/' + rand + ".mp3");
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle(word + ": " + phonetic)
.addFields(meaningsArray)
.setTimestamp()
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({
embeds: [embed],
files: [file]
});
meaningsArray = []
rand = Math.floor(Math.random() * 99999).toString();
})
}
})
},
};
let phonetic = data.phonetics[1] ? data.phonetics[1].text : "";
let audio = data.phonetics[0].audio;
if (!audio) {
for (let wordData of data.meanings) {
let definition = wordData.definitions[0];
meaningsArray.push({
name: wordData.partOfSpeech,
value: `${definition.definition}\nExample: ${definition.example || ""}`
});
}
let embed = createDictionaryEmbed(word, phonetic, meaningsArray, interaction.user);
interaction.editReply({ embeds: [embed] });
meaningsArray = [];
rand = Math.floor(Math.random() * 99999).toString();
} else {
// Options for Audio Download
let options = {
directory: "./audio/",
filename: rand + ".mp3"
}
download(audio, options, function(err) {
if (err) throw err;
for (let wordData of data.meanings) {
let definition = wordData.definitions[0];
meaningsArray.push({
name: wordData.partOfSpeech,
value: `${definition.definition}\nExample: ${definition.example || ""}`
});
}
let file = new AttachmentBuilder(`./audio/${rand}.mp3`);
let embed = createDictionaryEmbed(word, phonetic, meaningsArray, interaction.user);
interaction.editReply({ files: [file], embeds: [embed] });
meaningsArray = [];
rand = Math.floor(Math.random() * 99999).toString();
});
}
}
}

View File

@ -1,33 +1,33 @@
const { EmbedBuilder } = require('discord.js');
var generator = require('generate-password');
const generator = require('generate-password');
module.exports = {
name: "password-generator",
description: "Generates a random secure password",
private: true,
options: [{
"name": "length",
"description": "Provide a number for how long to make the password.",
"required": true,
"type": 3 // 6 is type USER
}],
name: "length",
description: "Provide a number for how long to make the password.",
required: true,
type: 3 // 6 is type USER
}],
run: async (client, interaction) => {
let length = interaction.options._hoistedOptions[0].value
var password = generator.generate({
length: length,
const { value: length } = interaction.options._hoistedOptions[0];
const password = generator.generate({
length,
numbers: true,
symbols: true,
excludeSimilarCharacters: true
});
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Password Generated!")
.setDescription("Click to reveal: " + "||" + password + "||")
.setDescription(`Click to reveal: ||${password}||`)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
.setFooter({
text: `Requested by ${interaction.user.tag}`,
iconURL: `${interaction.user.displayAvatarURL()}`
});
interaction.editReply({ embeds: [embed] });
},
}
};

View File

@ -1,7 +1,8 @@
const { EmbedBuilder } = require('discord.js');
const { AttachmentBuilder } = require('discord.js');
const { MessageEmbed, Attachment, TextChannel } = require('discord.js');
const { AwesomeQR } = require("awesome-qr");
const fs = require("fs");
const fs = require("fs").promises;
let fileName;
module.exports = {
name: "qr",
@ -14,32 +15,36 @@ module.exports = {
}],
run: async (client, interaction) => {
if (!fileName) {
fileName = Math.floor(Math.random() * 99999).toString();
}
(async () => {
let rand = Math.floor(Math.random() * 99999).toString();
let text = interaction.options._hoistedOptions[0].value
const text = interaction.options._hoistedOptions[0].value;
const background = Buffer.from(fs.readFileSync("Terminal-icon.png"));
const buffer = await new AwesomeQR({
text: text,
size: 500,
backgroundImage: background,
}).draw();
const background = fs.readFileSync("Terminal-icon.png");
await fs.writeFile(`./images/${fileName}.png`, buffer);
const file = new Attachment(`./images/${fileName}.png`);
const buffer = await new AwesomeQR({
text: text,
size: 500,
backgroundImage: background,
}).draw();
fs.writeFileSync("./images/" + rand + ".png", buffer);
const file = new AttachmentBuilder('./images/' + rand + ".png");
const embed = new EmbedBuilder()
const embed = new MessageEmbed()
.setColor("#FF0000")
.setTitle("Your Generated QR Code")
.setTimestamp()
.setImage('attachment://images/' + rand + ".png")
.setImage(`attachment://images/${fileName}.png`)
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
interaction.editReply({ embeds: [embed], files: [file] });
})();
try {
const message = await interaction.channel.send({ embeds: [embed], files: [file] });
setTimeout(async () => {
// await message.delete();
console.log(message)
await fs.unlink(`./images/${fileName}.png`);
}, 10000);
} catch (error) {
console.error(error);
}
},
};

View File

@ -1,6 +1,6 @@
const { EmbedBuilder } = require('discord.js');
const fs = require('fs');
const { exec } = require("child_process");
const fs = require('fs').promises;
const { spawn } = require("child_process");
module.exports = {
name: "short-url",
@ -13,43 +13,50 @@ module.exports = {
}],
run: async (client, interaction) => {
let rand = Math.floor(Math.random() * 99999).toString();
let URL = interaction.options._hoistedOptions[0].value
let URL = interaction.options._hoistedOptions[0].value;
var dir = '/var/www/html/short/' + rand;
const content = "<?php\nheader(\"Location: " + URL + "\")\n?>";
console.log(content)
console.log(content);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log("Created: " + '/var/www/html/short/' + rand)
try {
fs.writeFileSync('/var/www/html/short/' + rand + "/index.php", content);
// file written successfully
exec("chown -R www-data:www-data /var/www/html/short/", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("The URL has been shrunk!")
.setDescription("https://short.ssh.surf/" + rand)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
interaction.followUp({ embeds: [embed] });
rand = Math.floor(Math.random() * 99999).toString();
});
} catch (err) {
console.error(err);
try {
const stats = await fs.stat(dir);
if (!stats.isDirectory()) {
throw new Error(`${dir} is not a directory`);
}
} catch (error) {
if (error.code === 'ENOENT') {
console.log(`${dir} does not exist`);
} else {
throw error;
}
await fs.mkdir(dir);
console.log(`Created: ${dir}`);
await fs.writeFile(`${dir}/index.php`, content);
console.log(`Wrote ${dir}/index.php`);
const chown = spawn("chown", ["-R", "www-data:www-data", `/var/www/html/short/${rand}`]);
chown.on("exit", (code) => {
console.error(`chown exited with code ${code}`);
});
chown.stdout.on("data", (data) => {
console.log(`chown stdout: ${data}`);
});
chown.stderr.on("data", (data) => {
console.error(`chown stderr: ${data}`);
});
chown.on("error", (error) => {
console.error(`chown error: ${error.message}`);
});
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("The URL has been shrunk!")
.setDescription(`https://short.ssh.surf/${rand}`)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
interaction.followUp({ embeds: [embed] });
rand = Math.floor(Math.random() * 99999).toString();
}
},
};

View File

@ -1,63 +1,35 @@
const client = require("../index");
require("dotenv").config();
const { glob } = require("glob");
const { promisify } = require("util");
const globPromise = promisify(glob);
const fs = require("fs").promises;
client.on("interactionCreate", async (interaction) => {
// Slash Commands
const slashCommands = await globPromise(`${process.cwd()}/commands/*/*.js`);
const arrayOfSlashCommands = [];
slashCommands.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
const slashCommands = await fs.readdir(`${process.cwd()}/commands/*/*.js`);
const arrayOfSlashCommands = slashCommands.map((filename) => {
const file = require(`${process.cwd()}/commands/${filename}`);
if (!file?.name) return;
const properties = { directory, ...file };
client.slashCommands.set(file.name, properties);
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
arrayOfSlashCommands.push(file);
return file;
});
// Slash Command Handling
if (interaction.isChatInputCommand()) {
let commandData = []
await arrayOfSlashCommands.forEach(command => {
console.log(command.name)
if (command.name == interaction.commandName) {
commandData.push(command)
}
});
let dataToProcess = JSON.stringify(commandData[0])
let parsedData = JSON.parse(dataToProcess)
if (parsedData.private == true) {
await interaction.deferReply({ ephemeral: true }).catch(() => { });
} else {
await interaction.deferReply({ ephemeral: false }).catch(() => { });
}
const commandData = arrayOfSlashCommands.find(
(command) => command.name === interaction.commandName
);
if (!commandData) return;
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occurred " });
if (!cmd) return interaction.followUp({ content: "An error has occurred " });
const args = [];
for (let option of interaction.options.data) {
const args = interaction.options.data.map((option) => {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
if (option.name) return option.name;
return option.options?.map((x) => x.value).filter((x) => x);
}
return option.value;
});
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
@ -69,5 +41,4 @@ client.on("interactionCreate", async (interaction) => {
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});

View File

@ -1,38 +1,60 @@
require("dotenv").config();
const { glob } = require("glob");
const { promisify } = require("util");
const globPromise = promisify(glob);
const fs = require("fs").promises;
module.exports = async (client) => {
// Slash Commands
const slashCommands = await globPromise(`${process.cwd()}/commands/*/*.js`);
const arrayOfSlashCommands = [];
slashCommands.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
const slashCommands = await fs.readdir(`${process.cwd()}/commands/*/*.js`);
const arrayOfSlashCommands = slashCommands.map((filename) => {
const file = require(`${process.cwd()}/commands/${filename}`);
if (!file?.name) return;
const properties = { directory, ...file };
client.slashCommands.set(file.name, properties);
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
arrayOfSlashCommands.push(file);
return file;
});
// Events
const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
eventFiles.map((value) => require(value));
const eventFiles = await fs.readdir(`${process.cwd()}/events/*.js`);
eventFiles.forEach((filename) => require(`${process.cwd()}/events/${filename}`));
// Slash Commands Register
client.on("ready", async () => {
// // Register for a single guild
// await client.guilds.cache.get("GUIDIDHERE").commands.set(arrayOfSlashCommands);
console.log(arrayOfSlashCommands)
// Register for all the guilds the bot is in
await client.application.commands.set(arrayOfSlashCommands);
});
};
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isChatInputCommand()) {
let commandData = arrayOfSlashCommands.find((command) => command.name === interaction.commandName);
if (!commandData) return interaction.followUp({ content: "An error has occurred " });
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd) return interaction.followUp({ content: "An error has occurred " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
if (commandData.private) {
await interaction.deferReply({ ephemeral: true }).catch(() => { });
} else {
await interaction.deferReply({ ephemeral: false }).catch(() => { });
}
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenuCommand()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});
}