Merge pull request #191 from VermiumSifell/177-typescript

Typescript based
This commit is contained in:
Axel Olausson Holtenäs 2022-04-10 03:02:51 +02:00 committed by GitHub
commit f7c5982a86
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
110 changed files with 3833 additions and 3768 deletions

View file

@ -1,16 +0,0 @@
{
"env": {
"es6": true,
"browser": true,
"es2021": true
},
"extends": ["airbnb-base", "prettier"],
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"prettier/prettier": "error"
},
"plugins": ["prettier"]
}

18
.eslintrc.json Normal file
View file

@ -0,0 +1,18 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"rules": {
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-explicit-any": 0,
"no-async-promise-executor": 0,
"prettier/prettier": "error"
}
}

View file

@ -1,7 +0,0 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"tabs": true,
"semi": true,
"singleQuote": true
}

31
.vscode/settings.json vendored
View file

@ -1,22 +1,21 @@
{ {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.wordWrapColumn": 100, "editor.wordWrapColumn": 100,
"editor.tabSize": 2, "editor.tabSize": 2,
"editor.formatOnSave": true, "editor.formatOnSave": true,
"javascript.format.enable": false,
"files.eol": "\n", "files.eol": "\n",
"prettier.endOfLine": "lf", "prettier.endOfLine": "lf",
"prettier.singleQuote": true, "prettier.singleQuote": true,
"prettier.trailingComma": "es5", "prettier.trailingComma": "es5",
"peacock.color": "#369", "peacock.color": "#369",
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": ["source.formatDocument", "source.fixAll.eslint"],
"source.fixAll.eslint": true
},
"cSpell.words": [ "cSpell.words": [
"Controlpanel", "Controlpanel",
"discordjs", "discordjs",
"hoster", "hoster",
"pino", "pino",
"runned", "runned",
"Sifell",
"Timout", "Timout",
"upsert", "upsert",
"uuidv", "uuidv",
@ -28,7 +27,27 @@
"editor.fontFamily": "Cascadia Code", "editor.fontFamily": "Cascadia Code",
"editor.fontLigatures": true, "editor.fontLigatures": true,
"git.enableCommitSigning": true, "git.enableCommitSigning": true,
"files.associations": { "typescript.tsdk": "node_modules\\typescript\\lib",
"*.yaml": "home-assistant" "[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#407fbf",
"activityBar.activeBorder": "#77284f",
"activityBar.background": "#407fbf",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#77284f",
"activityBarBadge.foreground": "#e7e7e7",
"sash.hoverBorder": "#407fbf",
"statusBar.background": "#336699",
"statusBar.foreground": "#e7e7e7",
"statusBarItem.hoverBackground": "#407fbf",
"statusBarItem.remoteBackground": "#336699",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#336699",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#33669999",
"titleBar.inactiveForeground": "#e7e7e799"
} }
} }

View file

@ -2,7 +2,7 @@
"name": "xyter", "name": "xyter",
"version": "3.1.0", "version": "3.1.0",
"description": "Earn credits while chatting! And more", "description": "Earn credits while chatting! And more",
"main": "src/index.js", "main": "src/index.ts",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon | pino-pretty -i pid,hostname -t yyyy-mm-dd HH:MM:s" "start": "nodemon | pino-pretty -i pid,hostname -t yyyy-mm-dd HH:MM:s"
@ -28,6 +28,7 @@
"@discordjs/rest": "^0.3.0", "@discordjs/rest": "^0.3.0",
"axios": "^0.26.0", "axios": "^0.26.0",
"better-sqlite3": "^7.5.0", "better-sqlite3": "^7.5.0",
"common": "^0.2.5",
"dbd-dark-dashboard": "^1.6.45", "dbd-dark-dashboard": "^1.6.45",
"discord-api-types": "^0.31.0", "discord-api-types": "^0.31.0",
"discord-dashboard": "^2.3.14", "discord-dashboard": "^2.3.14",
@ -42,9 +43,15 @@
"uuid": "^8.3.2" "uuid": "^8.3.2"
}, },
"devDependencies": { "devDependencies": {
"@types/node-schedule": "^1.3.2",
"@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"eslint": "8.13.0", "eslint": "8.13.0",
"eslint-config-airbnb-base": "15.0.0", "eslint-config-airbnb-base": "15.0.0",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.5.0",
"eslint-plugin-import": "2.26.0" "eslint-plugin-import": "2.26.0"
"eslint-plugin-prettier": "^4.0.0",
"prettier": "^2.6.0"
} }
} }

View file

@ -1,89 +1,89 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { counters } = require('../../../../helpers/database/models'); import counters from '../../../../helpers/database/models/counterSchema';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
// Check permission // Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
// Create embed object // Create embed object
const embed = { const embed = {
title: 'Admin', title: 'Admin',
color: config.colors.error, color: config.colors.error as any,
description: 'You do not have permission to manage this!', description: 'You do not have permission to manage this!',
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// Get options // Get options
const channel = await interaction.options.getChannel('channel'); const channel = await interaction.options.getChannel('channel');
const word = await interaction.options.getString('word'); const word = await interaction.options.getString('word');
const start = await interaction.options.getNumber('start'); const start = await interaction.options.getNumber('start');
if (channel.type !== 'GUILD_TEXT') { if (channel?.type !== 'GUILD_TEXT') {
// Create embed object // Create embed object
const embed = { const embed = {
title: 'Admin - Counter', title: 'Admin - Counter',
description: `That channel is not supported, it needs to be a text channel.`, description: `That channel is not supported, it needs to be a text channel.`,
timestamp: new Date(), timestamp: new Date(),
color: config.colors.error, color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed] }); return interaction.editReply({ embeds: [embed] });
} }
const counterExist = await counters.findOne({ const counterExist = await counters.findOne({
guildId: member.guild.id, guildId: interaction?.guild?.id,
channelId: channel.id, channelId: channel?.id,
word, word,
}); });
if (!counterExist) { if (!counterExist) {
await counters.create({ await counters.create({
guildId: member.guild.id, guildId: interaction?.guild?.id,
channelId: channel.id, channelId: channel?.id,
word, word,
counter: start || 0, counter: start || 0,
}); });
// Create embed object // Create embed object
const embed = { const embed = {
title: 'Admin - Counter', title: 'Admin - Counter',
description: `${channel} is now counting when hearing word ${word} and it starts at number ${ description: `${channel} is now counting when hearing word ${word} and it starts at number ${
start || 0 start || 0
}.`, }.`,
timestamp: new Date(), timestamp: new Date(),
color: config.colors.success, color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} added ${channel.id} as a counter using word "${word}" for counting.` `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} added ${channel.id} as a counter using word "${word}" for counting.`
); );
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed] }); return interaction.editReply({ embeds: [embed] });
} }
// Create embed object // Create embed object
const embed = { const embed = {
title: 'Admin - Counter', title: 'Admin - Counter',
description: `${channel} is already a counting channel.`, description: `${channel} is already a counting channel.`,
timestamp: new Date(), timestamp: new Date(),
color: config.colors.error, color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed] }); return interaction.editReply({ embeds: [embed] });
}; };

View file

@ -1,4 +0,0 @@
const add = require('./add');
const remove = require('./remove');
module.exports = { add, remove };

View file

@ -0,0 +1,4 @@
import add from './add';
import remove from './remove';
export default { add, remove };

View file

@ -1,40 +0,0 @@
const { Permissions } = require('discord.js');
const config = require('../../../../../config.json');
const logger = require('../../../../handlers/logger');
// Database models
const { counters } = require('../../../../helpers/database/models');
module.exports = async (interaction) => {
// Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) {
// Create embed object
const embed = {
title: 'Admin',
color: config.colors.error,
description: 'You do not have permission to manage this!',
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true });
}
// Get options
const channel = await interaction.options.getChannel('channel');
await counters
.deleteOne({ guildId: member.guild.id, channelId: channel.id })
.then(async () => {
interaction.editReply({ content: 'Removed' });
});
// Send debug message
await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} executed remove counter.`
);
};

View file

@ -0,0 +1,40 @@
import { Permissions, CommandInteraction } from 'discord.js';
import config from '../../../../../config.json';
import logger from '../../../../handlers/logger';
// Database models
import counters from '../../../../helpers/database/models/counterSchema';
export default async (interaction: CommandInteraction) => {
// Destructure member
const { member } = interaction;
// Check permission
if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
// Create embed object
const embed = {
title: 'Admin',
color: config.colors.error as any,
description: 'You do not have permission to manage this!',
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed] });
}
// Get options
const channel = await interaction.options.getChannel('channel');
await counters
.deleteOne({ guildId: interaction?.guild?.id, channelId: channel?.id })
.then(async () => {
interaction.editReply({ content: 'Removed' });
});
// Send debug message
await logger.debug(
`Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} executed remove counter.`
);
};

View file

@ -1,44 +1,46 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import add from './addons/add';
const { add, remove } = require('./addons'); import remove from './addons/remove';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
// Check permission // Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':toolbox: Admin - Counter', title: ':toolbox: Admin - Counter',
color: config.colors.error, color: config.colors.error as any,
description: 'You do not have permission to manage this!', description: 'You do not have permission to manage this!',
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); await interaction.editReply({ embeds: [embed] });
} }
// If subcommand is give // If subcommand is give
if (interaction.options.getSubcommand() === 'add') { if (interaction.options.getSubcommand() === 'add') {
// Execute give addon // Execute give addon
await add(interaction); await add(interaction);
} }
// If subcommand is take // If subcommand is take
else if (interaction.options.getSubcommand() === 'remove') { else if (interaction.options.getSubcommand() === 'remove') {
// Execute take addon // Execute take addon
await remove(interaction); await remove(interaction);
} }
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} executed /${ `Guild: ${interaction?.guild?.id} User: ${
interaction.commandName interaction?.user?.id
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` } executed /${
); interaction.commandName
}; } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
);
};

View file

@ -1,106 +1,107 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { users } = require('../../../../helpers/database/models'); import users from '../../../../helpers/database/models/userSchema';
const creditNoun = require('../../../../helpers/creditNoun'); import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { guild, user } = interaction;
const { guild } = member;
// Check permission
// Check permission if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Create embed object
// Create embed object const embed = {
const embed = { title: ':toolbox: Admin - Credits [Give]',
title: ':toolbox: Admin - Credits [Give]', color: config.colors.error as any,
color: config.colors.error, description: 'You do not have permission to manage this!',
description: 'You do not have permission to manage this!', timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return interaction.editReply({ embeds: [embed] });
return interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// Get options
// Get options const userOption = await interaction.options.getUser('user');
const user = await interaction.options.getUser('user'); const amount = await interaction.options.getInteger('amount');
const amount = await interaction.options.getInteger('amount');
if (amount === null) return;
// If amount is zero or below
if (amount <= 0) { if (amount <= 0) {
// Create embed object // If amount is zero or below
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Give]', const embed = {
description: "You can't give zero or below.", title: ':toolbox: Admin - Credits [Give]',
color: 0xbb2124, description: "You can't give zero or below.",
timestamp: new Date(), color: 0xbb2124,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// Get toUserDB object
const toUserDB = await users.findOne({ // Get toUserDB object
userId: user.id, const toUserDB = await users.findOne({
guildId: interaction.member.guild.id, userId: userOption?.id,
}); guildId: interaction?.guild?.id,
});
// If toUserDB has no credits
if (!toUserDB) { // If toUserDB has no credits
// Create embed object if (!toUserDB) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Give]', const embed = {
description: title: ':toolbox: Admin - Credits [Give]',
'That user has no credits, I can not give credits to the user', description:
color: config.colors.error, 'That userOption has no credits, I can not give credits to the userOption',
timestamp: new Date(), color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// Deposit amount to toUserDB
toUserDB.credits += amount; // Deposit amount to toUserDB
toUserDB.credits += amount;
// Save toUserDB
await toUserDB // Save toUserDB
.save() await toUserDB
.save()
// If successful
.then(async () => { // If successful
// Create embed object .then(async () => {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Give]', const embed = {
description: `Gave ${creditNoun(amount)} to ${user}.`, title: ':toolbox: Admin - Credits [Give]',
color: 0x22bb33, description: `Gave ${creditNoun(amount)} to ${userOption}.`,
timestamp: new Date(), color: 0x22bb33,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send debug message
await logger.debug( // Send debug message
`Administrator: ${interaction.user.username} gave ${ await logger.debug(
amount <= 1 ? `${amount} credit` : `${amount} credits` `Administrator: ${interaction.user.username} gave ${
} to ${user.username}` amount <= 1 ? `${amount} credit` : `${amount} credits`
); } to ${userOption?.username}`
);
// Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
await interaction.editReply({ embeds: [embed] });
// Send debug message
await logger.debug( // Send debug message
`Guild: ${guild.id} User: ${member.id} gave ${user.id} ${creditNoun( await logger.debug(
amount `Guild: ${guild?.id} User: ${user?.id} gave ${
)}.` userOption?.id
); } ${creditNoun(amount)}.`
}); );
}; });
};

View file

@ -1,11 +0,0 @@
const give = require('./give');
const set = require('./set');
const take = require('./take');
const transfer = require('./transfer');
module.exports = {
give,
set,
take,
transfer,
};

View file

@ -0,0 +1,11 @@
import give from './give';
import set from './set';
import take from './take';
import transfer from './transfer';
export default {
give,
set,
take,
transfer,
};

View file

@ -1,105 +1,108 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { users } = require('../../../../helpers/database/models'); import users from '../../../../helpers/database/models/userSchema';
const creditNoun = require('../../../../helpers/creditNoun');
import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => {
// Destructure member export default async (interaction: CommandInteraction) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Set]', const embed = {
color: config.colors.error, title: ':toolbox: Admin - Credits [Set]',
description: 'You do not have permission to manage this!', color: config.colors.error as any,
timestamp: new Date(), description: 'You do not have permission to manage this!',
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// Get options
const user = await interaction.options.getUser('user'); // Get options
const amount = await interaction.options.getInteger('amount'); const user = await interaction.options.getUser('user');
const amount = await interaction.options.getInteger('amount');
// If amount is zero or below
if (amount <= 0) { if (amount === null) return;
// Create embed object
const embed = { // If amount is zero or below
title: ':toolbox: Admin - Credits [Set]', if (amount <= 0) {
description: "You can't give zero or below.", // Create embed object
color: 0xbb2124, const embed = {
timestamp: new Date(), title: ':toolbox: Admin - Credits [Set]',
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: "You can't give zero or below.",
}; color: 0xbb2124,
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
}
// Send interaction reply
// Get toUserDB object return interaction.editReply({ embeds: [embed] });
const toUserDB = await users.findOne({ }
userId: user.id,
guildId: interaction.member.guild.id, // Get toUserDB object
}); const toUserDB = await users.findOne({
userId: user?.id,
// If toUserDB has no credits guildId: interaction?.guild?.id,
if (!toUserDB) { });
// Create embed object
const embed = { // If toUserDB has no credits
title: ':toolbox: Admin - Credits [Set]', if (!toUserDB) {
description: // Create embed object
'That user has no credits, I can not set credits to the user', const embed = {
color: config.colors.error, title: ':toolbox: Admin - Credits [Set]',
timestamp: new Date(), description:
footer: { iconURL: config.footer.icon, text: config.footer.text }, 'That user has no credits, I can not set credits to the user',
}; color: config.colors.error as any,
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
}
// Send interaction reply
// Set toUserDB with amount return interaction.editReply({ embeds: [embed] });
toUserDB.credits = amount; }
// Save toUserDB // Set toUserDB with amount
await toUserDB toUserDB.credits = amount;
.save()
// Save toUserDB
// If successful await toUserDB
.then(async () => { .save()
// Create embed object
const embed = { // If successful
title: ':toolbox: Admin - Credits [Set]', .then(async () => {
description: `You set ${creditNoun(amount)} on ${user}.`, // Create embed object
color: 0x22bb33, const embed = {
timestamp: new Date(), title: ':toolbox: Admin - Credits [Set]',
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: `You set ${creditNoun(amount)} on ${user}.`,
}; color: 0x22bb33,
timestamp: new Date(),
// Send debug message footer: { iconURL: config.footer.icon, text: config.footer.text },
await logger.debug( };
`Administrator: ${interaction.user.username} set ${
amount <= 1 ? `${amount} credit` : `${amount} credits` // Send debug message
} on ${user.username}` await logger.debug(
); `Administrator: ${interaction.user.username} set ${
amount <= 1 ? `${amount} credit` : `${amount} credits`
// Send interaction reply } on ${user?.username}`
await interaction.editReply({ embeds: [embed], ephemeral: true }); );
// Send debug message // Send interaction reply
await logger.debug( await interaction.editReply({ embeds: [embed] });
`Guild: ${member.guild.id} User: ${member.id} set ${
user.id // Send debug message
} to ${creditNoun(amount)}.` await logger.debug(
); `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} set ${
}); user?.id
}; } to ${creditNoun(amount)}.`
);
});
};

View file

@ -1,105 +1,108 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { users } = require('../../../../helpers/database/models'); import users from '../../../../helpers/database/models/userSchema';
const creditNoun = require('../../../../helpers/creditNoun');
import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => {
// Destructure member export default async (interaction: CommandInteraction) => {
const { member } = interaction; // Destructure member
const { guild, user } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Take]', const embed = {
color: config.colors.error, title: ':toolbox: Admin - Credits [Take]',
description: 'You do not have permission to manage this!', color: config.colors.error as any,
timestamp: new Date(), description: 'You do not have permission to manage this!',
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// Get options
const user = await interaction.options.getUser('user'); // Get options
const amount = await interaction.options.getInteger('amount'); const userOption = await interaction.options.getUser('userOption');
const amount = await interaction.options.getInteger('amount');
// If amount is zero or below
if (amount <= 0) { if (amount === null) return;
// Give embed object
const embed = { // If amount is zero or below
title: ':toolbox: Admin - Credits [Take]', if (amount <= 0) {
description: "You can't take zero or below.", // Give embed object
color: 0xbb2124, const embed = {
timestamp: new Date(), title: ':toolbox: Admin - Credits [Take]',
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: "You can't take zero or below.",
}; color: config.colors.error as any,
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
}
// Send interaction reply
// Get toUser object return interaction.editReply({ embeds: [embed] });
const toUser = await users.findOne({ }
userId: user.id,
guildId: interaction.member.guild.id, // Get toUser object
}); const toUser = await users.findOne({
userId: userOption?.id,
// If toUser has no credits guildId: interaction?.guild?.id,
if (!toUser) { });
// Create embed object
const embed = { // If toUser has no credits
title: ':toolbox: Admin - Credits [Take]', if (!toUser) {
description: // Create embed object
'That user has no credits, I can not take credits from the user', const embed = {
color: config.colors.error, title: ':toolbox: Admin - Credits [Take]',
timestamp: new Date(), description:
footer: { iconURL: config.footer.icon, text: config.footer.text }, 'That userOption has no credits, I can not take credits from the userOption',
}; color: config.colors.error as any,
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
}
// Send interaction reply
// Withdraw amount from toUser return interaction.editReply({ embeds: [embed] });
toUser.credits -= amount; }
// Save toUser // Withdraw amount from toUser
await toUser toUser.credits -= amount;
.save()
// Save toUser
// If successful await toUser
.then(async () => { .save()
// Create embed object
const embed = { // If successful
title: ':toolbox: Admin - Credits [Take]', .then(async () => {
description: `You took ${creditNoun(amount)} to ${user}.`, // Create embed object
color: 0x22bb33, const embed = {
timestamp: new Date(), title: ':toolbox: Admin - Credits [Take]',
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: `You took ${creditNoun(amount)} to ${userOption}.`,
}; color: 0x22bb33,
timestamp: new Date(),
// Send debug message footer: { iconURL: config.footer.icon, text: config.footer.text },
await logger.debug( };
`Administrator: ${interaction.user.username} took ${
amount <= 1 ? `${amount} credit` : `${amount} credits` // Send debug message
} from ${user.username}` await logger.debug(
); `Administrator: ${interaction.user.username} took ${
amount <= 1 ? `${amount} credit` : `${amount} credits`
// Send interaction reply } from ${userOption?.username}`
await interaction.editReply({ embeds: [embed], ephemeral: true }); );
// Send debug message // Send interaction reply
await logger.debug( await interaction.editReply({ embeds: [embed] });
`Guild: ${member.guild.id} User: ${member.id} took ${creditNoun(
amount // Send debug message
)} from ${user.id}.` await logger.debug(
); `Guild: ${guild?.id} User: ${user?.id} took ${creditNoun(
}); amount
}; )} from ${user.id}.`
);
});
};

View file

@ -1,135 +1,138 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { users } = require('../../../../helpers/database/models'); import users from '../../../../helpers/database/models/userSchema';
const creditNoun = require('../../../../helpers/creditNoun');
const saveUser = require('../../../../helpers/saveUser'); import creditNoun from '../../../../helpers/creditNoun';
import saveUser from '../../../../helpers/saveUser';
module.exports = async (interaction) => {
// Destructure member export default async (interaction: CommandInteraction) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Transfer]', const embed = {
color: config.colors.error, title: ':toolbox: Admin - Credits [Transfer]',
description: 'You do not have permission to manage this!', color: config.colors.error as any,
timestamp: new Date(), description: 'You do not have permission to manage this!',
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// Get options
const from = await interaction.options.getUser('from'); // Get options
const to = await interaction.options.getUser('to'); const from = await interaction.options.getUser('from');
const amount = await interaction.options.getInteger('amount'); const to = await interaction.options.getUser('to');
const amount = await interaction.options.getInteger('amount');
// Get fromUser object
const fromUser = await users.findOne({ // Get fromUser object
userId: from.id, const fromUser = await users.findOne({
guildId: interaction.member.guild.id, userId: from?.id,
}); guildId: interaction?.guild?.id,
});
// Get toUser object
const toUser = await users.findOne({ // Get toUser object
userId: to.id, const toUser = await users.findOne({
guildId: interaction.member.guild.id, userId: to?.id,
}); guildId: interaction?.guild?.id,
});
// If fromUser has no credits
if (!fromUser) { // If fromUser has no credits
// Create embed object if (!fromUser) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Transfer]', const embed = {
description: title: ':toolbox: Admin - Credits [Transfer]',
'That user has no credits, I can not transfer credits from the user', description:
color: config.colors.error, 'That user has no credits, I can not transfer credits from the user',
timestamp: new Date(), color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// If toUser has no credits
if (!toUser) { // If toUser has no credits
// Create embed object if (!toUser) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Transfer]', const embed = {
description: title: ':toolbox: Admin - Credits [Transfer]',
'That user has no credits, I can not transfer credits to the user', description:
color: config.colors.error, 'That user has no credits, I can not transfer credits to the user',
timestamp: new Date(), color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} return interaction.editReply({ embeds: [embed] });
}
// If amount is zero or below
if (amount <= 0) { if (amount === null) return;
// Create embed object
const embed = { // If amount is zero or below
title: ':toolbox: Admin - Credits [Transfer]', if (amount <= 0) {
description: "You can't transfer zero or below.", // Create embed object
color: config.colors.error, const embed = {
timestamp: new Date(), title: ':toolbox: Admin - Credits [Transfer]',
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: "You can't transfer zero or below.",
}; color: config.colors.error as any,
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
}
// Send interaction reply
// Withdraw amount from fromUser return interaction.editReply({ embeds: [embed] });
fromUser.credits -= amount; }
// Deposit amount to toUser // Withdraw amount from fromUser
toUser.credits += amount; fromUser.credits -= amount;
// Save users // Deposit amount to toUser
await saveUser(fromUser, toUser) toUser.credits += amount;
// If successful
.then(async () => { // Save users
// Create embed object await saveUser(fromUser, toUser)
const embed = { // If successful
title: ':toolbox: Admin - Credits [Transfer]', .then(async () => {
description: `You sent ${creditNoun(amount)} from ${from} to ${to}.`, // Create embed object
color: config.colors.success, const embed = {
fields: [ title: ':toolbox: Admin - Credits [Transfer]',
{ description: `You sent ${creditNoun(amount)} from ${from} to ${to}.`,
name: `${from.username} Balance`, color: config.colors.success as any,
value: `${fromUser.credits}`, fields: [
inline: true, {
}, name: `${from?.username} Balance`,
{ value: `${fromUser.credits}`,
name: `${to.username} Balance`, inline: true,
value: `${toUser.credits}`, },
inline: true, {
}, name: `${to?.username} Balance`,
], value: `${toUser.credits}`,
timestamp: new Date(), inline: true,
footer: { iconURL: config.footer.icon, text: config.footer.text }, },
}; ],
timestamp: new Date(),
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
await interaction.editReply({ embeds: [embed], ephemeral: true }); };
// Send debug message // Send interaction reply
await logger.debug( await interaction.editReply({ embeds: [embed] });
`Guild: ${member.guild.id} User: ${member.id} transferred ${creditNoun(
amount // Send debug message
)} from ${from.id} to ${to.id}.` await logger.debug(
); `Guild: ${interaction?.guild?.id} User: ${
}); interaction?.user?.id
}; } transferred ${creditNoun(amount)} from ${from?.id} to ${to?.id}.`
);
});
};

View file

@ -1,56 +1,61 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import give from './addons/give';
const { give, take, set, transfer } = require('./addons'); import take from './addons/take';
import set from './addons/set';
module.exports = async (interaction) => { import transfer from './addons/transfer';
// Destructure member
const { member } = interaction; export default async (interaction: CommandInteraction) => {
// Destructure member
// Check permission const { user, guild } = interaction;
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) {
// Create embed object // Check permission
const embed = { if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
title: ':toolbox: Admin - Credits', // Create embed object
color: config.colors.error, const embed = {
description: 'You do not have permission to manage this!', title: ':toolbox: Admin - Credits' as string,
timestamp: new Date(), color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, description: 'You do not have permission to manage this!' as string,
}; timestamp: new Date(),
footer: {
// Send interaction reply iconURL: config.footer.icon as string,
await interaction.editReply({ embeds: [embed], ephemeral: true }); text: config.footer.text as string,
} },
};
// If subcommand is give
if (interaction.options.getSubcommand() === 'give') { // Send interaction reply
// Execute give addon await interaction.editReply({ embeds: [embed] });
await give(interaction); }
}
// If subcommand is give
// If subcommand is take if (interaction.options.getSubcommand() === 'give') {
else if (interaction.options.getSubcommand() === 'take') { // Execute give addon
// Execute take addon await give(interaction);
await take(interaction); }
}
// If subcommand is take
// If subcommand is set else if (interaction.options.getSubcommand() === 'take') {
else if (interaction.options.getSubcommand() === 'set') { // Execute take addon
// Execute set addon await take(interaction);
await set(interaction); }
}
// If subcommand is set
// If subcommand is transfer else if (interaction.options.getSubcommand() === 'set') {
else if (interaction.options.getSubcommand() === 'transfer') { // Execute set addon
// Execute transfer addon await set(interaction);
await transfer(interaction); }
}
// If subcommand is transfer
// Send debug message else if (interaction.options.getSubcommand() === 'transfer') {
await logger.debug( // Execute transfer addon
`Guild: ${member.guild.id} User: ${member.id} executed /${ await transfer(interaction);
interaction.commandName }
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
); // Send debug message
}; await logger.debug(
`Guild: ${guild?.id} User: ${user?.id} executed /${
interaction.commandName
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
);
};

View file

@ -1,138 +1,139 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import credits from './credits';
const credits = require('./credits'); import counter from './counter';
const counter = require('./counter');
import { CommandInteraction } from 'discord.js';
module.exports = {
data: new SlashCommandBuilder() export default {
.setName('admin') data: new SlashCommandBuilder()
.setDescription('Admin actions.') .setName('admin')
.addSubcommandGroup((group) => .setDescription('Admin actions.')
group .addSubcommandGroup((group) =>
.setName('credits') group
.setDescription('Manage credits.') .setName('credits')
.addSubcommand((command) => .setDescription('Manage credits.')
command .addSubcommand((command) =>
.setName('give') command
.setDescription('Give credits to a user') .setName('give')
.addUserOption((option) => .setDescription('Give credits to a user')
option .addUserOption((option) =>
.setName('user') option
.setDescription('The user you want to pay.') .setName('user')
.setRequired(true) .setDescription('The user you want to pay.')
) .setRequired(true)
.addIntegerOption((option) => )
option .addIntegerOption((option) =>
.setName('amount') option
.setDescription('The amount you will pay.') .setName('amount')
.setRequired(true) .setDescription('The amount you will pay.')
) .setRequired(true)
) )
.addSubcommand((command) => )
command .addSubcommand((command) =>
.setName('set') command
.setDescription('Set credits to a user') .setName('set')
.addUserOption((option) => .setDescription('Set credits to a user')
option .addUserOption((option) =>
.setName('user') option
.setDescription('The user you want to set credits on.') .setName('user')
.setRequired(true) .setDescription('The user you want to set credits on.')
) .setRequired(true)
.addIntegerOption((option) => )
option .addIntegerOption((option) =>
.setName('amount') option
.setDescription('The amount you will set.') .setName('amount')
.setRequired(true) .setDescription('The amount you will set.')
) .setRequired(true)
) )
.addSubcommand((command) => )
command .addSubcommand((command) =>
.setName('take') command
.setDescription('Take credits from a user') .setName('take')
.addUserOption((option) => .setDescription('Take credits from a user')
option .addUserOption((option) =>
.setName('user') option
.setDescription('The user you want to take credits from.') .setName('user')
.setRequired(true) .setDescription('The user you want to take credits from.')
) .setRequired(true)
.addIntegerOption((option) => )
option .addIntegerOption((option) =>
.setName('amount') option
.setDescription('The amount you will take.') .setName('amount')
.setRequired(true) .setDescription('The amount you will take.')
) .setRequired(true)
) )
.addSubcommand((command) => )
command .addSubcommand((command) =>
.setName('transfer') command
.setDescription('Transfer credits from a user to another user.') .setName('transfer')
.addUserOption((option) => .setDescription('Transfer credits from a user to another user.')
option .addUserOption((option) =>
.setName('from') option
.setDescription('The user you want to take credits from.') .setName('from')
.setRequired(true) .setDescription('The user you want to take credits from.')
) .setRequired(true)
.addUserOption((option) => )
option .addUserOption((option) =>
.setName('to') option
.setDescription('The user you want to give credits to.') .setName('to')
.setRequired(true) .setDescription('The user you want to give credits to.')
) .setRequired(true)
.addIntegerOption((option) => )
option .addIntegerOption((option) =>
.setName('amount') option
.setDescription('The amount you will transfer.') .setName('amount')
.setRequired(true) .setDescription('The amount you will transfer.')
) .setRequired(true)
) )
) )
.addSubcommandGroup((group) => )
group .addSubcommandGroup((group) =>
.setName('counter') group
.setDescription('Manage counters.') .setName('counter')
.addSubcommand((command) => .setDescription('Manage counters.')
command .addSubcommand((command) =>
.setName('add') command
.setDescription('Add a counter') .setName('add')
.addChannelOption((option) => .setDescription('Add a counter')
option .addChannelOption((option) =>
.setName('channel') option
.setDescription('The counter channel.') .setName('channel')
.setRequired(true) .setDescription('The counter channel.')
) .setRequired(true)
.addStringOption((option) => )
option .addStringOption((option) =>
.setName('word') option
.setDescription('The counter word.') .setName('word')
.setRequired(true) .setDescription('The counter word.')
) .setRequired(true)
.addNumberOption((option) => )
option.setName('start').setDescription('Start at number X.') .addNumberOption((option) =>
) option.setName('start').setDescription('Start at number X.')
) )
.addSubcommand((command) => )
command .addSubcommand((command) =>
.setName('remove') command
.setDescription('Remove a counter') .setName('remove')
.addChannelOption((option) => .setDescription('Remove a counter')
option .addChannelOption((option) =>
.setName('channel') option
.setDescription('The counter channel.') .setName('channel')
.setRequired(true) .setDescription('The counter channel.')
) .setRequired(true)
) )
), )
async execute(interaction) { ),
// If subcommand group is credits async execute(interaction: CommandInteraction) {
if (interaction.options.getSubcommandGroup() === 'credits') { // If subcommand group is credits
// Execute credits group if (interaction.options.getSubcommandGroup() === 'credits') {
await credits(interaction); // Execute credits group
} await credits(interaction);
}
// If subcommand group is credits
else if (interaction.options.getSubcommandGroup() === 'counter') { // If subcommand group is credits
// Execute credits group else if (interaction.options.getSubcommandGroup() === 'counter') {
await counter(interaction); // Execute credits group
} await counter(interaction);
}, }
}; },
};

View file

@ -1,48 +1,47 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import counters from '../../../helpers/database/models/counterSchema';
const { counters } = require('../../../helpers/database/models'); import { CommandInteraction } from 'discord.js';
export default async (interaction: CommandInteraction) => {
module.exports = async (interaction) => { try {
try { // Destructure member
// Destructure member const { member } = await interaction;
const { member } = await interaction;
// Get options
// Get options const channel = await interaction.options.getChannel('channel');
const channel = await interaction.options.getChannel('channel');
const counter = await counters.findOne({
const counter = await counters.findOne({ guildId: interaction?.guild?.id,
guildId: member.guild.id, channelId: channel?.id,
channelId: channel.id, });
});
if (!counter) {
if (!counter) { // Create embed object
// Create embed object const embed = {
const embed = { title: 'Counter - View',
title: 'Counter - View', description: `${channel} is not a counting channel.`,
description: `${channel} is not a counting channel.`, timestamp: new Date(),
timestamp: new Date(), color: config.colors.error as any,
color: config.colors.error, footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return await interaction.editReply({ embeds: [embed] });
return await interaction.editReply({ embeds: [embed] }); }
}
// Create embed object
// Create embed object const embed = {
const embed = { title: 'Counter - View',
title: 'Counter - View', color: config.colors.success as any,
color: config.colors.success, description: `${channel} is currently at number ${counter.counter}.`,
description: `${channel} is currently at number ${counter.counter}.`, timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return await interaction.editReply({ embeds: [embed] });
return await interaction.editReply({ embeds: [embed], ephemeral: true }); } catch (e) {
} catch (e) { // Send debug message
// Send debug message await logger.error(e);
await logger.error(e); }
} };
};

View file

@ -1,27 +1,28 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import view from './addons/view';
const view = require('./addons/view');
import { CommandInteraction } from 'discord.js';
module.exports = {
data: new SlashCommandBuilder() export default {
.setName('counter') data: new SlashCommandBuilder()
.setDescription('Manage counters.') .setName('counter')
.addSubcommand((subcommand) => .setDescription('Manage counters.')
subcommand .addSubcommand((subcommand) =>
.setName('view') subcommand
.setDescription('View a counter.') .setName('view')
.addChannelOption((option) => .setDescription('View a counter.')
option .addChannelOption((option) =>
.setName('channel') option
.setDescription('The counter channel you want to view') .setName('channel')
.setRequired(true) .setDescription('The counter channel you want to view')
) .setRequired(true)
), )
async execute(interaction) { ),
// If subcommand is view async execute(interaction: CommandInteraction) {
if (interaction.options.getSubcommand() === 'view') { // If subcommand is view
// Execute view addon if (interaction.options.getSubcommand() === 'view') {
await view(interaction); // Execute view addon
} await view(interaction);
}, }
}; },
};

View file

@ -1,68 +1,68 @@
const config = require('../../../../config.json'); import { CommandInteraction } from 'discord.js';
const logger = require('../../../handlers/logger'); import config from '../../../../config.json';
import logger from '../../../handlers/logger';
const { users } = require('../../../helpers/database/models'); import users from '../../../helpers/database/models/userSchema';
const creditNoun = require('../../../helpers/creditNoun'); import creditNoun from '../../../helpers/creditNoun';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Get options // Get options
const user = await interaction.options.getUser('user'); const user = await interaction.options.getUser('user');
// Get credit object // Get credit object
const userDB = await users.findOne({ const userDB = await users.findOne({
userId: user ? user.id : interaction.user.id, userId: user ? user.id : interaction?.user?.id,
guildId: interaction.member.guild.id, guildId: interaction?.guild?.id,
}); });
// Destructure balance // Destructure balance
const { credits } = userDB; const { credits } = userDB;
// If !userDB // If !userDB
if (!userDB) { if (!userDB) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Balance', title: ':dollar: Credits - Balance',
description: `${ description: `${
user ? `${user} is` : 'You are' user ? `${user} is` : 'You are'
} not found in the database.`, } not found in the database.`,
color: config.colors.error, color: config.colors.error as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// If !credits // If !credits
if (!credits) { if (!credits) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Balance', title: ':dollar: Credits - Balance',
description: `${user ? `${user} has` : 'You have'} no credits.`, description: `${user ? `${user} has` : 'You have'} no credits.`,
color: config.colors.success, color: config.colors.success as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// If credits // If credits
if (credits) { if (credits) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Balance', title: ':dollar: Credits - Balance',
description: `${user ? `${user} has` : 'You have'} ${creditNoun( description: `${user ? `${user} has` : 'You have'} ${creditNoun(
credits credits
)}.`, )}.`,
color: config.colors.success, color: config.colors.success as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
}; };

View file

@ -1,139 +1,140 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import users from '../../../helpers/database/models/userSchema';
const { users } = require('../../../helpers/database/models'); import saveUser from '../../../helpers/saveUser';
const saveUser = require('../../../helpers/saveUser'); import creditNoun from '../../../helpers/creditNoun';
const creditNoun = require('../../../helpers/creditNoun'); import { CommandInteraction } from 'discord.js';
export default async (interaction: CommandInteraction) => {
module.exports = async (interaction) => { // Get options
// Get options const user = await interaction.options.getUser('user');
const user = await interaction.options.getUser('user'); const amount = await interaction.options.getInteger('amount');
const amount = await interaction.options.getInteger('amount'); const reason = await interaction.options.getString('reason');
const reason = await interaction.options.getString('reason');
const { member } = interaction;
const { member } = interaction;
const { guild } = member; // Get fromUserDB object
const fromUserDB = await users.findOne({
// Get fromUserDB object userId: interaction?.user?.id,
const fromUserDB = await users.findOne({ guildId: interaction?.guild?.id,
userId: interaction.user.id, });
guildId: interaction.member.guild.id,
}); // Get toUserDB object
const toUserDB = await users.findOne({
// Get toUserDB object userId: user?.id,
const toUserDB = await users.findOne({ guildId: interaction?.guild?.id,
userId: user.id, });
guildId: interaction.member.guild.id,
}); // If receiver is same as sender
if (user?.id === interaction?.user?.id) {
// If receiver is same as sender // Create embed object
if (user.id === interaction.user.id) { const embed = {
// Create embed object title: ':dollar: Credits - Gift',
const embed = { description: "You can't pay yourself.",
title: ':dollar: Credits - Gift', color: config.colors.error as any,
description: "You can't pay yourself.", timestamp: new Date(),
color: 0xbb2124, footer: { iconURL: config.footer.icon, text: config.footer.text },
timestamp: new Date(), };
footer: { iconURL: config.footer.icon, text: config.footer.text },
}; // Send interaction reply
return interaction.editReply({ embeds: [embed] });
// Send interaction reply }
return interaction.editReply({ embeds: [embed], ephemeral: true });
} if (amount === null) return;
// If amount is zero or below // If amount is zero or below
if (amount <= 0) { if (amount <= 0) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Gift', title: ':dollar: Credits - Gift',
description: "You can't pay zero or below.", description: "You can't pay zero or below.",
color: 0xbb2124, color: config.colors.error as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// If user has below gifting amount // If user has below gifting amount
if (fromUserDB.credits < amount) { if (fromUserDB.credits < amount) {
// Create embed // Create embed
const embed = { const embed = {
title: ':dollar: Credits - Gift', title: ':dollar: Credits - Gift',
description: `You have insufficient credits. Your credits is ${fromUserDB.credits}`, description: `You have insufficient credits. Your credits is ${fromUserDB.credits}`,
color: 0xbb2124, color: config.colors.error as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// If toUserDB has no credits // If toUserDB has no credits
if (!toUserDB) { if (!toUserDB) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Gift', title: ':dollar: Credits - Gift',
description: description:
'That user has no credits, I can not gift credits to the user', 'That user has no credits, I can not gift credits to the user',
color: config.colors.error, color: config.colors.error as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
} }
// Withdraw amount from fromUserDB // Withdraw amount from fromUserDB
fromUserDB.credits -= amount; fromUserDB.credits -= amount;
// Deposit amount to toUserDB // Deposit amount to toUserDB
toUserDB.credits += amount; toUserDB.credits += amount;
// Save users // Save users
await saveUser(fromUserDB, toUserDB).then(async () => { await saveUser(fromUserDB, toUserDB).then(async () => {
// Create interaction embed object // Create interaction embed object
const interactionEmbed = { const interactionEmbed = {
title: ':dollar: Credits - Gift', title: ':dollar: Credits - Gift',
description: `You sent ${creditNoun(amount)} to ${user}${ description: `You sent ${creditNoun(amount)} to ${user}${
reason ? ` with reason: ${reason}` : '' reason ? ` with reason: ${reason}` : ''
}. Your new credits is ${creditNoun(fromUserDB.credits)}.`, }. Your new credits is ${creditNoun(fromUserDB.credits)}.`,
color: 0x22bb33, color: 0x22bb33,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Create DM embed object // Create DM embed object
const dmEmbed = { const dmEmbed = {
title: ':dollar: Credits - Gift', title: ':dollar: Credits - Gift',
description: `You received ${creditNoun(amount)} from ${ description: `You received ${creditNoun(amount)} from ${
interaction.user interaction.user
}${ }${
reason ? ` with reason: ${reason}` : '' reason ? ` with reason: ${reason}` : ''
}. Your new credits is ${creditNoun(toUserDB.credits)}.`, }. Your new credits is ${creditNoun(toUserDB.credits)}.`,
color: 0x22bb33, color: 0x22bb33,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Get DM user object // Get DM user object
const dmUser = await interaction.client.users.cache.get(user.id); const dmUser = await interaction.client.users.cache.get(
interaction?.user?.id
// Send DM to user );
await dmUser.send({ embeds: [dmEmbed] });
// Send DM to user
// Send debug message await dmUser?.send({ embeds: [dmEmbed] });
await logger.debug(
`Guild: ${guild.id} User: ${member.id} gift sent from: ${interaction.user.id} to: ${user.id}` // Send debug message
); await logger.debug(
`Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} gift sent from: ${interaction?.user?.id} to: ${user?.id}`
// Send interaction reply );
return interaction.editReply({
embeds: [interactionEmbed], // Send interaction reply
ephemeral: true, return interaction.editReply({
}); embeds: [interactionEmbed],
}); });
}; });
};

View file

@ -1,6 +0,0 @@
const balance = require('./balance');
const gift = require('./gift');
const top = require('./top');
const work = require('./work');
module.exports = { balance, gift, top, work };

View file

@ -0,0 +1,6 @@
import balance from './balance';
import gift from './gift';
import top from './top';
import work from './work';
export default { balance, gift, top, work };

View file

@ -1,35 +1,35 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
const { users } = require('../../../helpers/database/models'); import users from '../../../helpers/database/models/userSchema';
const creditNoun = require('../../../helpers/creditNoun'); import creditNoun from '../../../helpers/creditNoun';
import { CommandInteraction } from 'discord.js';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Get all users in the guild // Get all users in the guild
const usersDB = await users.find({ guildId: interaction.member.guild.id }); const usersDB = await users.find({ guildId: interaction?.guild?.id });
const topTen = usersDB const topTen = usersDB
// Sort them after credits amount (ascending) // Sort them after credits amount (ascending)
.sort((a, b) => (a.credits > b.credits ? -1 : 1)) .sort((a, b) => (a.credits > b.credits ? -1 : 1))
// Return the top 10 // Return the top 10
.slice(0, 10); .slice(0, 10);
// Create entry object // Create entry object
const entry = (x, index) => const entry = (x: any, index: any) =>
`**Top ${index + 1}** - <@${x.userId}> ${creditNoun(x.credits)}`; `**Top ${index + 1}** - <@${x.userId}> ${creditNoun(x.credits)}`;
// Create embed object // Create embed object
const embed = { const embed = {
title: ':dollar: Credits - Top', title: ':dollar: Credits - Top',
description: `Below are the top ten.\n${topTen description: `Below are the top ten.\n${topTen
.map((x, index) => entry(x, index)) .map((x, index) => entry(x, index))
.join('\n')}`, .join('\n')}`,
color: 0x22bb33, color: config.colors.success as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed] });
}; };

View file

@ -1,93 +1,96 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
const { guilds, users, timeouts } = require('../../../helpers/database/models'); import guilds from '../../../helpers/database/models/guildSchema';
const creditNoun = require('../../../helpers/creditNoun'); import users from '../../../helpers/database/models/userSchema';
import timeouts from '../../../helpers/database/models/timeoutSchema';
module.exports = async (interaction) => { import creditNoun from '../../../helpers/creditNoun';
// Destructure member import { CommandInteraction } from 'discord.js';
const { member } = interaction; export default async (interaction: CommandInteraction) => {
const { guild } = member; // Destructure member
const { member } = interaction;
// Check if user has a timeout
const isTimeout = await timeouts.findOne({ // Check if user has a timeout
guildId: guild.id, const isTimeout = await timeouts.findOne({
userId: member.id, guildId: interaction?.guild?.id,
timeoutId: '2022-03-15-19-16', userId: interaction?.user?.id,
}); timeoutId: '2022-03-15-19-16',
});
const guildDB = await guilds.findOne({
guildId: guild.id, const guildDB = await guilds.findOne({
}); guildId: interaction?.guild?.id,
});
// If user is not on timeout
if (!isTimeout) { // If user is not on timeout
// Make a variable of how much credits user will earn based on random multiplied with work rate if (!isTimeout) {
const creditsEarned = Math.floor(Math.random() * guildDB.credits.workRate); // Make a variable of how much credits user will earn based on random multiplied with work rate
const creditsEarned = Math.floor(Math.random() * guildDB.credits.workRate);
const userDB = await users.findOne({
userId: member.id, const userDB = await users.findOne({
guildId: guild.id, userId: interaction?.user?.id,
}); guildId: interaction?.guild?.id,
});
userDB.credits += creditsEarned;
userDB.credits += creditsEarned;
await userDB.save().then(async () => {
// Send debug message await userDB.save().then(async () => {
await logger.debug(`Credits added to user: ${interaction.member.id}`); // Send debug message
await logger.debug(`Credits added to user: ${interaction?.user?.id}`);
// Create embed object
const embed = { // Create embed object
title: ':dollar: Credits - Work', const embed = {
description: `You have earned ${creditNoun(creditsEarned)}`, title: ':dollar: Credits - Work',
color: config.colors.success, description: `You have earned ${creditNoun(creditsEarned)}`,
timestamp: new Date(), color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
}); return interaction.editReply({ embeds: [embed] });
});
// Create a timeout for the user
await timeouts.create({ // Create a timeout for the user
guildId: guild.id, await timeouts.create({
userId: member.id, guildId: interaction?.guild?.id,
timeoutId: '2022-03-15-19-16', userId: interaction?.user?.id,
}); timeoutId: '2022-03-15-19-16',
});
setTimeout(async () => {
// Send debug message setTimeout(async () => {
await logger.debug( // Send debug message
`Guild: ${guild.id} User: ${member.id} has not worked within the last ${ await logger.debug(
guildDB.work.timeout / 1000 `Guild: ${interaction?.guild?.id} User: ${
} seconds, work can be done` interaction?.user?.id
); } has not worked within the last ${
guildDB.work.timeout / 1000
// When timeout is out, remove it from the database } seconds, work can be done`
await timeouts.deleteOne({ );
guildId: guild.id,
userId: member.id, // When timeout is out, remove it from the database
timeoutId: '2022-03-15-19-16', await timeouts.deleteOne({
}); guildId: interaction?.guild?.id,
}, guildDB.credits.workTimeout); userId: interaction?.user?.id,
} else { timeoutId: '2022-03-15-19-16',
// Create embed object });
const embed = { }, guildDB.credits.workTimeout);
title: ':dollar: Credits - Work', } else {
description: `You have worked within the last ${ // Create embed object
guildDB.credits.workTimeout / 1000 const embed = {
} seconds, you can not work now!`, title: ':dollar: Credits - Work',
timestamp: new Date(), description: `You have worked within the last ${
color: config.colors.error, guildDB.credits.workTimeout / 1000
footer: { iconURL: config.footer.icon, text: config.footer.text }, } seconds, you can not work now!`,
}; timestamp: new Date(),
color: config.colors.error as any,
// Send interaction reply footer: { iconURL: config.footer.icon, text: config.footer.text },
await interaction.editReply({ embeds: [embed] }); };
// Send debug message // Send interaction reply
await logger.debug( await interaction.editReply({ embeds: [embed] });
`Guild: ${guild.id} User: ${member.id} has worked within last day, no work can be done`
); // Send debug message
} await logger.debug(
}; `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} has worked within last day, no work can be done`
);
}
};

View file

@ -1,71 +1,73 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import balance from './addons/balance';
const { balance, gift, top, work } = require('./addons'); import gift from './addons/gift';
import top from './addons/top';
module.exports = { import work from './addons/work';
data: new SlashCommandBuilder() import { CommandInteraction } from 'discord.js';
.setName('credits') export default {
.setDescription('Manage your credits.') data: new SlashCommandBuilder()
.addSubcommand((subcommand) => .setName('credits')
subcommand .setDescription('Manage your credits.')
.setName('balance') .addSubcommand((subcommand) =>
.setDescription("Check a user's balance.") subcommand
.addUserOption((option) => .setName('balance')
option .setDescription("Check a user's balance.")
.setName('user') .addUserOption((option) =>
.setDescription('The user whose balance you want to check.') option
.setRequired(false) .setName('user')
) .setDescription('The user whose balance you want to check.')
) .setRequired(false)
.addSubcommand((subcommand) => )
subcommand )
.setName('gift') .addSubcommand((subcommand) =>
.setDescription('Gift someone credits from your credits.') subcommand
.addUserOption((option) => .setName('gift')
option .setDescription('Gift someone credits from your credits.')
.setName('user') .addUserOption((option) =>
.setDescription('The user you want to pay.') option
.setRequired(true) .setName('user')
) .setDescription('The user you want to pay.')
.addIntegerOption((option) => .setRequired(true)
option )
.setName('amount') .addIntegerOption((option) =>
.setDescription('The amount you will pay.') option
.setRequired(true) .setName('amount')
) .setDescription('The amount you will pay.')
.addStringOption((option) => .setRequired(true)
option.setName('reason').setDescription('Your reason.') )
) .addStringOption((option) =>
) option.setName('reason').setDescription('Your reason.')
.addSubcommand((subcommand) => )
subcommand.setName('top').setDescription('Check the top balance.') )
) .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand.setName('top').setDescription('Check the top balance.')
subcommand.setName('work').setDescription('Work for credits.') )
), .addSubcommand((subcommand) =>
async execute(interaction) { subcommand.setName('work').setDescription('Work for credits.')
// If subcommand is balance ),
if (interaction.options.getSubcommand() === 'balance') { async execute(interaction: CommandInteraction) {
// Execute balance addon // If subcommand is balance
await balance(interaction); if (interaction.options.getSubcommand() === 'balance') {
} // Execute balance addon
await balance(interaction);
// If subcommand is gift }
else if (interaction.options.getSubcommand() === 'gift') {
// Execute gift addon // If subcommand is gift
await gift(interaction); else if (interaction.options.getSubcommand() === 'gift') {
} // Execute gift addon
await gift(interaction);
// If subcommand is top }
else if (interaction.options.getSubcommand() === 'top') {
// Execute top addon // If subcommand is top
await top(interaction); else if (interaction.options.getSubcommand() === 'top') {
} // Execute top addon
await top(interaction);
// If subcommand is work }
else if (interaction.options.getSubcommand() === 'work') {
// Execute work addon // If subcommand is work
await work(interaction); else if (interaction.options.getSubcommand() === 'work') {
} // Execute work addon
}, await work(interaction);
}; }
},
};

View file

@ -1,75 +1,69 @@
const i18next = require('i18next'); import i18next from 'i18next';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import users from '../../../helpers/database/models/userSchema';
const { import { CommandInteraction } from 'discord.js';
users, export default async (interaction: CommandInteraction) => {
credits, try {
experiences, // Destructure member
} = require('../../../helpers/database/models'); const { member } = await interaction;
module.exports = async (interaction) => { // Get options
try { const target = await interaction.options.getUser('target');
// Destructure member
const { member } = await interaction; // Get discord user object
const { guild } = member; const discordUser = await interaction.client.users.fetch(
`${target ? target.id : interaction?.user?.id}`
// Get options );
const target = await interaction.options.getUser('target');
// Get user object
// Get discord user object const userDB = await users.findOne({
const discordUser = await interaction.client.users.fetch( userId: await discordUser?.id,
`${target ? target.id : member.id}` guildId: interaction?.guild?.id,
); });
// Get user object // Create embed object
const userDB = await users.findOne({ const embed = {
userId: await discordUser.id, author: {
guildId: guild.id, name: `${await discordUser.username}#${await discordUser.discriminator}`,
}); icon_url: await discordUser.displayAvatarURL(),
},
// Create embed object color: config.colors.success as any,
const embed = { fields: [
author: { {
name: `${await discordUser.username}#${await discordUser.discriminator}`, name: `:dollar: Credits`,
icon_url: await discordUser.displayAvatarURL(), value: `${userDB.credits || 'Not found'}`,
}, inline: true,
color: config.colors.success, },
fields: [ {
{ name: `:squeeze_bottle: Level`,
name: `:dollar: Credits`, value: `${userDB.level || 'Not found'}`,
value: `${userDB.credits || 'Not found'}`, inline: true,
inline: true, },
}, {
{ name: `:squeeze_bottle: Points`,
name: `:squeeze_bottle: Level`, value: `${userDB.points || 'Not found'}`,
value: `${userDB.level || 'Not found'}`, inline: true,
inline: true, },
}, {
{ name: `:loudspeaker: Reputation`,
name: `:squeeze_bottle: Points`, value: `${userDB.reputation || 'Not found'}`,
value: `${userDB.points || 'Not found'}`, inline: true,
inline: true, },
}, {
{ name: `:rainbow_flag: Language`,
name: `:loudspeaker: Reputation`, value: `${userDB.language || 'Not found'}`,
value: `${userDB.reputation || 'Not found'}`, inline: true,
inline: true, },
}, ],
{ timestamp: new Date(),
name: `:rainbow_flag: Language`, footer: { iconURL: config.footer.icon, text: config.footer.text },
value: `${userDB.language || 'Not found'}`, };
inline: true,
}, // Send interaction reply
], return await interaction.editReply({ embeds: [embed] });
timestamp: new Date(), } catch (e) {
footer: { iconURL: config.footer.icon, text: config.footer.text }, // Send debug message
}; await logger.error(e);
}
// Send interaction reply };
return await interaction.editReply({ embeds: [embed], ephemeral: true });
} catch (e) {
// Send debug message
await logger.error(e);
}
};

View file

@ -1,26 +1,25 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import view from './addons/view';
const view = require('./addons/view'); import { CommandInteraction } from 'discord.js';
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('profile')
.setName('profile') .setDescription('Your profile.')
.setDescription('Your profile.') .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand
subcommand .setName('view')
.setName('view') .setDescription('View a profile.')
.setDescription('View a profile.') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('target')
.setName('target') .setDescription('The profile you wish to view')
.setDescription('The profile you wish to view') )
) ),
), async execute(interaction: CommandInteraction) {
async execute(interaction) { // If subcommand is view
// If subcommand is view if (interaction.options.getSubcommand() === 'view') {
if (interaction.options.getSubcommand() === 'view') { // Execute view addon
// Execute view addon await view(interaction);
await view(interaction); }
} },
}, };
};

View file

@ -1,122 +1,124 @@
const i18next = require('i18next'); import i18next from 'i18next';
const config = require('../../../../config.json'); import { CommandInteraction } from 'discord.js';
const logger = require('../../../handlers/logger'); import config from '../../../../config.json';
import logger from '../../../handlers/logger';
const { users, timeouts } = require('../../../helpers/database/models'); import users from '../../../helpers/database/models/userSchema';
import timeouts from '../../../helpers/database/models/timeoutSchema';
module.exports = async (interaction) => {
// Destructure member export default async (interaction: CommandInteraction) => {
const { member } = interaction; // Destructure member
const { guild } = member; const { member } = interaction;
// Get options // Get options
const target = await interaction.options.getUser('target'); const target = await interaction.options.getUser('target');
const type = await interaction.options.getString('type'); const type = await interaction.options.getString('type');
// Get user object // Get user object
const userDB = await users.findOne({ const userDB = await users.findOne({
userId: member.id, userId: interaction?.user?.id,
guildId: guild.id, guildId: interaction?.guild?.id,
}); });
// Check if user has a timeout // Check if user has a timeout
const isTimeout = await timeouts.findOne({ const isTimeout = await timeouts.findOne({
guildId: guild.id, guildId: interaction?.guild?.id,
userId: member.id, userId: interaction?.user?.id,
timeoutId: 2, timeoutId: 2,
}); });
// If user is not on timeout // If user is not on timeout
if (!isTimeout) { if (!isTimeout) {
// Do not allow self reputation // Do not allow self reputation
if (target.id === interaction.member.id) { if (target?.id === interaction?.user?.id) {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':loudspeaker: Reputation - Give', title: ':loudspeaker: Reputation - Give',
description: 'You can not repute yourself.', description: 'You can not repute yourself.',
timestamp: new Date(), timestamp: new Date(),
color: config.colors.error, color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed] }); return interaction.editReply({ embeds: [embed] });
} }
// If type is positive // If type is positive
if (type === 'positive') { if (type === 'positive') {
userDB.reputation += 1; userDB.reputation += 1;
} }
// If type is negative // If type is negative
if (type === 'negative') { if (type === 'negative') {
userDB.reputation -= 1; userDB.reputation -= 1;
} }
// Save user // Save user
await userDB.save().then(async () => { await userDB.save().then(async () => {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':loudspeaker: Reputation - Give', title: ':loudspeaker: Reputation - Give',
description: `You have given ${target} a ${type} reputation!`, description: `You have given ${target} a ${type} reputation!`,
timestamp: new Date(), timestamp: new Date(),
color: config.colors.success, color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} has given ${target.id} a ${type} reputation.` `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} has given ${target?.id} a ${type} reputation.`
); );
// Create a timeout for the user // Create a timeout for the user
await timeouts.create({ await timeouts.create({
guildId: member.guild.id, guildId: interaction?.guild?.id,
userId: member.id, userId: interaction?.user?.id,
timeoutId: 2, timeoutId: 2,
}); });
}); });
setTimeout(async () => { setTimeout(async () => {
// send debug message // send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${ `Guild: ${interaction?.guild?.id} User: ${
member.id interaction?.user?.id
} has not repute within last ${ } has not repute within last ${
config.reputation.timeout / 1000 config.reputation.timeout / 1000
} seconds, reputation can be given` } seconds, reputation can be given`
); );
// When timeout is out, remove it from the database // When timeout is out, remove it from the database
await timeouts.deleteOne({ await timeouts.deleteOne({
guildId: member.guild.id, guildId: interaction?.guild?.id,
userId: member.id, userId: interaction?.user?.id,
timeoutId: 2, timeoutId: 2,
}); });
}, config.reputation.timeout); }, config.reputation.timeout);
} else { } else {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':loudspeaker: Reputation - Give', title: ':loudspeaker: Reputation - Give',
description: `You have given reputation within the last ${ description: `You have given reputation within the last ${
config.reputation.timeout / 1000 config.reputation.timeout / 1000
} seconds, you can not repute now!`, } seconds, you can not repute now!`,
timestamp: new Date(), timestamp: new Date(),
color: config.colors.error, color: config.colors.error as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
// Send interaction reply // Send interaction reply
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} has repute within last ${ `Guild: ${interaction?.guild?.id} User: ${
config.reputation.timeout / 1000 interaction?.user?.id
} seconds, no reputation can be given` } has repute within last ${
); config.reputation.timeout / 1000
} } seconds, no reputation can be given`
}; );
}
};

View file

@ -1,47 +1,48 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const logger = require('../../handlers/logger'); import logger from '../../handlers/logger';
import give from './addons/give';
const give = require('./addons/give');
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('reputation')
.setName('reputation') .setDescription('Manage reputation.')
.setDescription('Manage reputation.') .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand
subcommand .setName('give')
.setName('give') .setDescription('Give reputation for a user')
.setDescription('Give reputation for a user') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('target')
.setName('target') .setDescription('The user you want to repute.')
.setDescription('The user you want to repute.') .setRequired(true)
.setRequired(true) )
) .addStringOption((option) =>
.addStringOption((option) => option
option .setName('type')
.setName('type') .setDescription('What type of reputation you want to repute')
.setDescription('What type of reputation you want to repute') .setRequired(true)
.setRequired(true) .addChoice('Positive', 'positive')
.addChoice('Positive', 'positive') .addChoice('Negative', 'negative')
.addChoice('Negative', 'negative') )
) ),
), async execute(interaction: CommandInteraction) {
async execute(interaction) { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction;
// If subcommand is give
// If subcommand is give if (interaction.options.getSubcommand() === 'give') {
if (interaction.options.getSubcommand() === 'give') { // Execute give addon
// Execute give addon await give(interaction);
await give(interaction); }
}
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${interaction?.guild?.id} User: ${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction?.user?.id
interaction.commandName } executed /${
} ${interaction.options.getSubcommand()}` interaction.commandName
); } ${interaction.options.getSubcommand()}`
}, );
}; },
};

View file

@ -1,96 +1,95 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { guilds } = require('../../../../helpers/database/models'); import guilds from '../../../../helpers/database/models/guildSchema';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { guild, user } = interaction;
const { guild } = member;
// Check permission
// Check permission if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Settings - Guild [Credits]',
title: ':hammer: Settings - Guild [Credits]', color: config.colors.error as any,
color: config.colors.error, description: `You don't have permission to manage this!`,
description: `You don't have permission to manage this!`, timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return interaction.editReply({ embeds: [embed] });
return interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// Get options
// Get options const status = await interaction.options.getBoolean('status');
const status = await interaction.options.getBoolean('status'); const rate = await interaction.options.getNumber('rate');
const rate = await interaction.options.getNumber('rate'); const timeout = await interaction.options.getNumber('timeout');
const timeout = await interaction.options.getNumber('timeout'); const minimumLength = await interaction.options.getNumber('minimum-length');
const minimumLength = await interaction.options.getNumber('minimum-length'); const workRate = await interaction.options.getNumber('work-rate');
const workRate = await interaction.options.getNumber('work-rate'); const workTimeout = await interaction.options.getNumber('work-timeout');
const workTimeout = await interaction.options.getNumber('work-timeout');
// Get guild object
// Get guild object const guildDB = await guilds.findOne({
const guildDB = await guilds.findOne({ guildId: guild?.id,
guildId: guild.id, });
});
// Modify values
// Modify values guildDB.credits.status = status !== null ? status : guildDB.credits.status;
guildDB.credits.status = status !== null ? status : guildDB.credits.status; guildDB.credits.rate = rate !== null ? rate : guildDB.credits.rate;
guildDB.credits.rate = rate !== null ? rate : guildDB.credits.rate; guildDB.credits.timeout =
guildDB.credits.timeout = timeout !== null ? timeout : guildDB.credits.timeout;
timeout !== null ? timeout : guildDB.credits.timeout; guildDB.credits.workRate =
guildDB.credits.workRate = workRate !== null ? workRate : guildDB.credits.workRate;
workRate !== null ? workRate : guildDB.credits.workRate; guildDB.credits.workTimeout =
guildDB.credits.workTimeout = workTimeout !== null ? workTimeout : guildDB.credits.workTimeout;
workTimeout !== null ? workTimeout : guildDB.credits.workTimeout; guildDB.credits.minimumLength =
guildDB.credits.minimumLength = minimumLength !== null ? minimumLength : guildDB.credits.minimumLength;
minimumLength !== null ? minimumLength : guildDB.credits.minimumLength;
// Save guild
// Save guild await guildDB.save().then(async () => {
await guildDB.save().then(async () => { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Settings - Guild [Credits]',
title: ':hammer: Settings - Guild [Credits]', description: 'Following settings is set!',
description: 'Following settings is set!', color: config.colors.success as any,
color: config.colors.success, fields: [
fields: [ { name: '🤖 Status', value: `${guildDB.credits.status}`, inline: true },
{ name: '🤖 Status', value: `${guildDB.credits.status}`, inline: true }, { name: '📈 Rate', value: `${guildDB.credits.rate}`, inline: true },
{ name: '📈 Rate', value: `${guildDB.credits.rate}`, inline: true }, {
{ name: '📈 Work Rate',
name: '📈 Work Rate', value: `${guildDB.credits.workRate}`,
value: `${guildDB.credits.workRate}`, inline: true,
inline: true, },
}, {
{ name: '🔨 Minimum Length',
name: '🔨 Minimum Length', value: `${guildDB.credits.minimumLength}`,
value: `${guildDB.credits.minimumLength}`, inline: true,
inline: true, },
}, {
{ name: '⏰ Timeout',
name: '⏰ Timeout', value: `${guildDB.credits.timeout}`,
value: `${guildDB.credits.timeout}`, inline: true,
inline: true, },
}, {
{ name: '⏰ Work Timeout',
name: '⏰ Work Timeout', value: `${guildDB.credits.workTimeout}`,
value: `${guildDB.credits.workTimeout}`, inline: true,
inline: true, },
}, ],
], timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${guild?.id} User: ${user.id} has changed credit details.`
`Guild: ${member.guild.id} User: ${member.id} has changed credit details.` );
); });
}); };
};

View file

@ -1,5 +0,0 @@
const pterodactyl = require('./pterodactyl');
const credits = require('./credits');
const points = require('./points');
module.exports = { pterodactyl, credits, points };

View file

@ -0,0 +1,5 @@
import pterodactyl from './pterodactyl';
import credits from './credits';
import points from './points';
export default { pterodactyl, credits, points };

View file

@ -1,80 +1,79 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { guilds } = require('../../../../helpers/database/models'); import guilds from '../../../../helpers/database/models/guildSchema';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member;
// Check permission
// Check permission if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Settings - Guild [Points]',
title: ':hammer: Settings - Guild [Points]', color: config.colors.error as any,
color: config.colors.error, description: `You don't have permission to manage this!`,
description: `You don't have permission to manage this!`, timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return interaction.editReply({ embeds: [embed] });
return interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// Get options
// Get options const status = await interaction.options.getBoolean('status');
const status = await interaction.options.getBoolean('status'); const rate = await interaction.options.getNumber('rate');
const rate = await interaction.options.getNumber('rate'); const timeout = await interaction.options.getNumber('timeout');
const timeout = await interaction.options.getNumber('timeout'); const minimumLength = await interaction.options.getNumber('minimum-length');
const minimumLength = await interaction.options.getNumber('minimum-length');
// Get guild object
// Get guild object const guildDB = await guilds.findOne({
const guildDB = await guilds.findOne({ guildId: interaction?.guild?.id,
guildId: guild.id, });
});
// Modify values
// Modify values guildDB.credits.status = status !== null ? status : guildDB.credits.status;
guildDB.credits.status = status !== null ? status : guildDB.credits.status; guildDB.credits.rate = rate !== null ? rate : guildDB.credits.rate;
guildDB.credits.rate = rate !== null ? rate : guildDB.credits.rate; guildDB.credits.timeout =
guildDB.credits.timeout = timeout !== null ? timeout : guildDB.credits.timeout;
timeout !== null ? timeout : guildDB.credits.timeout; guildDB.credits.minimumLength =
guildDB.credits.minimumLength = minimumLength !== null ? minimumLength : guildDB.credits.minimumLength;
minimumLength !== null ? minimumLength : guildDB.credits.minimumLength;
// Save guild
// Save guild await guildDB.save().then(async () => {
await guildDB.save().then(async () => { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Settings - Guild [Points]',
title: ':hammer: Settings - Guild [Points]', description: 'Following settings is set!',
description: 'Following settings is set!', color: config.colors.success as any,
color: config.colors.success, fields: [
fields: [ { name: '🤖 Status', value: `${guildDB.credits.status}`, inline: true },
{ name: '🤖 Status', value: `${guildDB.credits.status}`, inline: true }, { name: '📈 Rate', value: `${guildDB.credits.rate}`, inline: true },
{ name: '📈 Rate', value: `${guildDB.credits.rate}`, inline: true }, {
{ name: '🔨 Minimum Length',
name: '🔨 Minimum Length', value: `${guildDB.credits.minimumLength}`,
value: `${guildDB.credits.minimumLength}`, inline: true,
inline: true, },
}, {
{ name: '⏰ Timeout',
name: '⏰ Timeout', value: `${guildDB.credits.timeout}`,
value: `${guildDB.credits.timeout}`, inline: true,
inline: true, },
}, ],
], timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} has changed credit details.`
`Guild: ${guild.id} User: ${member.id} has changed credit details.` );
); });
}); };
};

View file

@ -1,63 +1,62 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
// Database models // Database models
const { apis } = require('../../../../helpers/database/models'); import apis from '../../../../helpers/database/models/apiSchema';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member;
// Check permission
// Check permission if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Settings - Guild [Pterodactyl]',
title: ':hammer: Settings - Guild [Pterodactyl]', color: config.colors.error as any,
color: config.colors.error, description: 'You do not have permission to manage this!',
description: 'You do not have permission to manage this!', timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply return interaction.editReply({ embeds: [embed] });
return interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// Get options
// Get options
const url = await interaction.options.getString('url');
const url = await interaction.options.getString('url'); const token = await interaction.options.getString('token');
const token = await interaction.options.getString('token');
// Update API credentials
// Update API credentials
await apis
await apis .findOneAndUpdate(
.findOneAndUpdate( { guildId: interaction?.guild?.id },
{ guildId: guild.id }, { url, token },
{ url, token }, { new: true, upsert: true }
{ new: true, upsert: true } )
) .then(async () => {
.then(async () => { // Build embed
// Build embed
const embed = {
const embed = { title: ':hammer: Settings - Guild [Pterodactyl]',
title: ':hammer: Settings - Guild [Pterodactyl]', color: config.colors.success as any,
color: config.colors.success, description: 'Pterodactyl settings is saved!',
description: 'Pterodactyl settings is saved!', timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send reply
// Send reply
await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
// Send debug message
await logger.debug(
await logger.debug( `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} has changed api credentials.`
`Guild: ${guild.id} User: ${member.id} has changed api credentials.` );
); });
}); };
};

View file

@ -1,50 +1,53 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import pterodactyl from './addons/pterodactyl';
const { pterodactyl, credits, points } = require('./addons'); import credits from './addons/credits';
import points from './addons/points';
module.exports = async (interaction) => {
// Destructure member export default async (interaction: CommandInteraction) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!interaction?.memberPermissions?.has(Permissions.FLAGS.MANAGE_GUILD)) {
const embed = { // Create embed object
title: 'Settings - Guild', const embed = {
color: config.colors.error, title: 'Settings - Guild',
description: 'You do not have permission to manage this!', color: config.colors.error as any,
timestamp: new Date(), description: 'You do not have permission to manage this!',
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
} await interaction.editReply({ embeds: [embed] });
}
// If subcommand is pterodactyl
if (interaction.options.getSubcommand() === 'pterodactyl') { // If subcommand is pterodactyl
// Execute pterodactyl addon if (interaction.options.getSubcommand() === 'pterodactyl') {
await pterodactyl(interaction); // Execute pterodactyl addon
} await pterodactyl(interaction);
}
// If subcommand is credits
else if (interaction.options.getSubcommand() === 'credits') { // If subcommand is credits
// Execute credits addon else if (interaction.options.getSubcommand() === 'credits') {
await credits(interaction); // Execute credits addon
} await credits(interaction);
}
// If subcommand is points
else if (interaction.options.getSubcommand() === 'points') { // If subcommand is points
// Execute points addon else if (interaction.options.getSubcommand() === 'points') {
await points(interaction); // Execute points addon
} await points(interaction);
}
// Send debug message
await logger.debug( // Send debug message
`Guild: ${member.guild.id} User: ${member.id} executed /${ await logger.debug(
interaction.commandName `Guild: ${interaction?.guild?.id} User: ${
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` interaction?.user?.id
); } executed /${
}; interaction.commandName
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
);
};

View file

@ -1,128 +1,127 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
import guild from './guild';
const guild = require('./guild'); import user from './user';
const user = require('./user');
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('settings')
.setName('settings') .setDescription('Manage settings.')
.setDescription('Manage settings.') .addSubcommandGroup((group) =>
.addSubcommandGroup((group) => group
group .setName('guild')
.setName('guild') .setDescription('Manage guild settings.')
.setDescription('Manage guild settings.') .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('pterodactyl')
.setName('pterodactyl') .setDescription('Controlpanel.gg')
.setDescription('Controlpanel.gg') .addStringOption((option) =>
.addStringOption((option) => option
option .setName('url')
.setName('url') .setDescription('The api url')
.setDescription('The api url') .setRequired(true)
.setRequired(true) )
) .addStringOption((option) =>
.addStringOption((option) => option
option .setName('token')
.setName('token') .setDescription('The api token')
.setDescription('The api token') .setRequired(true)
.setRequired(true) )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('credits')
.setName('credits') .setDescription('Credits')
.setDescription('Credits') .addBooleanOption((option) =>
.addBooleanOption((option) => option
option .setName('status')
.setName('status') .setDescription('Should credits be enabled?')
.setDescription('Should credits be enabled?') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('rate')
.setName('rate') .setDescription('Amount of credits per message.')
.setDescription('Amount of credits per message.') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('minimum-length')
.setName('minimum-length') .setDescription('Minimum length of message to earn credits.')
.setDescription('Minimum length of message to earn credits.') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('work-rate')
.setName('work-rate') .setDescription('Maximum amount of credits on work.')
.setDescription('Maximum amount of credits on work.') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('work-timeout')
.setName('work-timeout') .setDescription(
.setDescription( 'Timeout between work schedules (milliseconds).'
'Timeout between work schedules (milliseconds).' )
) )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('timeout')
.setName('timeout') .setDescription(
.setDescription( 'Timeout between earning credits (milliseconds).'
'Timeout between earning credits (milliseconds).' )
) )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('points')
.setName('points') .setDescription('Points')
.setDescription('Points') .addBooleanOption((option) =>
.addBooleanOption((option) => option
option .setName('status')
.setName('status') .setDescription('Should credits be enabled?')
.setDescription('Should credits be enabled?') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('rate')
.setName('rate') .setDescription('Amount of credits per message.')
.setDescription('Amount of credits per message.') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('minimum-length')
.setName('minimum-length') .setDescription('Minimum length of message to earn credits.')
.setDescription('Minimum length of message to earn credits.') )
) .addNumberOption((option) =>
.addNumberOption((option) => option
option .setName('timeout')
.setName('timeout') .setDescription(
.setDescription( 'Timeout between earning credits (milliseconds).'
'Timeout between earning credits (milliseconds).' )
) )
) )
) )
) .addSubcommandGroup((group) =>
.addSubcommandGroup((group) => group
group .setName('user')
.setName('user') .setDescription('Manage user settings.')
.setDescription('Manage user settings.') .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('appearance')
.setName('appearance') .setDescription('Manage your appearance')
.setDescription('Manage your appearance') .addStringOption((option) =>
.addStringOption((option) => option
option .setName('language')
.setName('language') .setDescription('Configure your language')
.setDescription('Configure your language') .addChoice('English', 'en')
.addChoice('English', 'en') .addChoice('Swedish', 'sv')
.addChoice('Swedish', 'sv') )
) )
) ),
), async execute(interaction: CommandInteraction) {
async execute(interaction) { // If subcommand group is guild
// If subcommand group is guild if (interaction.options.getSubcommandGroup() === 'guild') {
if (interaction.options.getSubcommandGroup() === 'guild') { // Execute guild group
// Execute guild group await guild(interaction);
await guild(interaction); }
} // If subcommand group is user
// If subcommand group is user else if (interaction.options.getSubcommandGroup() === 'user') {
else if (interaction.options.getSubcommandGroup() === 'user') { // Execute user group
// Execute user group await user(interaction);
await user(interaction); }
} },
}, };
};

View file

@ -1,47 +1,49 @@
const config = require('../../../../../config.json'); import config from '../../../../../config.json';
const logger = require('../../../../handlers/logger'); import logger from '../../../../handlers/logger';
import { CommandInteraction } from 'discord.js';
// Database models // Database models
const { users } = require('../../../../helpers/database/models'); import users from '../../../../helpers/database/models/userSchema';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member;
// Get options
// Get options const language = await interaction.options.getString('language');
const language = await interaction.options.getString('language');
// Get user object
// Get user object const userDB = await users.findOne({
const userDB = await users.findOne({ userId: member.id, guildId: guild.id }); userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
// Modify values });
userDB.language = language !== null ? language : userDB.language;
// Modify values
// Save guild userDB.language = language !== null ? language : userDB.language;
await userDB.save().then(async () => {
// Create embed object // Save guild
const embed = { await userDB.save().then(async () => {
title: ':hammer: Settings - User [Appearance]', // Create embed object
description: 'Following settings is set!', const embed = {
color: config.colors.success, title: ':hammer: Settings - User [Appearance]',
fields: [ description: 'Following settings is set!',
{ color: config.colors.success as any,
name: '🏳️‍🌈 Language', fields: [
value: `${userDB.language}`, {
inline: true, name: '🏳️‍🌈 Language',
}, value: `${userDB.language}`,
], inline: true,
timestamp: new Date(), },
footer: { iconURL: config.footer.icon, text: config.footer.text }, ],
}; timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
// Send interaction reply };
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send interaction reply
// Send debug message await interaction.editReply({ embeds: [embed] });
await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} has changed appearance settings.` // Send debug message
); await logger.debug(
}); `Guild: ${interaction?.guild?.id} User: ${interaction?.user?.id} has changed appearance settings.`
}; );
});
};

View file

@ -1,3 +0,0 @@
const appearance = require('./appearance');
module.exports = { appearance };

View file

@ -0,0 +1,3 @@
import appearance from './appearance';
export default { appearance };

View file

@ -1,23 +1,24 @@
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import appearance from './addons/appearance';
const { appearance } = require('./addons');
export default async (interaction: CommandInteraction) => {
module.exports = async (interaction) => { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction;
// If subcommand is appearance
// If subcommand is appearance if (interaction.options.getSubcommand() === 'appearance') {
if (interaction.options.getSubcommand() === 'appearance') { // Execute appearance addon
// Execute appearance addon await appearance(interaction);
await appearance(interaction); }
}
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${interaction?.guild?.id} User: ${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction?.user?.id
interaction.commandName } executed /${
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` interaction.commandName
); } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
}; );
};

View file

@ -1,175 +1,177 @@
const { v4: uuidv4 } = require('uuid'); import { v4 as uuidv4 } from 'uuid';
const axios = require('axios'); import axios from 'axios';
const config = require('../../../../config.json'); import config from '../../../../config.json';
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import apis from '../../../helpers/database/models/apiSchema';
const { credits, apis } = require('../../../helpers/database/models'); import users from '../../../helpers/database/models/userSchema';
const creditNoun = require('../../../helpers/creditNoun'); import creditNoun from '../../../helpers/creditNoun';
import { CommandInteraction } from 'discord.js';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
const { member } = interaction; const { member } = interaction;
const { guild } = member;
// Get options
// Get options const amount = await interaction.options.getInteger('amount');
const amount = await interaction.options.getInteger('amount');
if (amount === null) return;
// Get user object
const userDB = await users.findOne({ // Get user object
userId: member.id, const userDB = await users.findOne({
guildId: guild.id, userId: interaction?.user?.id,
}); guildId: interaction?.guild?.id,
});
// Get DM user object
const dmUser = interaction.client.users.cache.get(member.id); // Get DM user object
const dmUser = interaction.client.users.cache.get(interaction?.user?.id);
// Stop if amount or user credits is below 100
if ((amount || userDB.credits) < 100) { // Stop if amount or user credits is below 100
const embed = { if ((amount || userDB.credits) < 100) {
title: ':shopping_cart: Shop - Pterodactyl', const embed = {
description: `You **can't** withdraw for __Pterodactyl__ below **100**.`, title: ':shopping_cart: Shop - Pterodactyl',
color: config.colors.error, description: `You **can't** withdraw for __Pterodactyl__ below **100**.`,
fields: [ color: config.colors.error as any,
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` }, fields: [
], { name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
timestamp: new Date(), ],
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
} return interaction.editReply({ embeds: [embed] });
}
// Stop if amount or user credits is above 1.000.000
if ((amount || userDB.credits) > 1000000) { // Stop if amount or user credits is above 1.000.000
const embed = { if ((amount || userDB.credits) > 1000000) {
title: ':shopping_cart: Shop - Pterodactyl', const embed = {
description: `You **can't** withdraw for __Pterodactyl__ above **1.000.000**.`, title: ':shopping_cart: Shop - Pterodactyl',
color: config.colors.error, description: `You **can't** withdraw for __Pterodactyl__ above **1.000.000**.`,
fields: [ color: config.colors.error as any,
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` }, fields: [
], { name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
timestamp: new Date(), ],
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
} return interaction.editReply({ embeds: [embed] });
}
// Stop if user credits is below amount
if (userDB.credits < amount) { // Stop if user credits is below amount
const embed = { if (userDB.credits < amount) {
title: ':shopping_cart: Shop - Pterodactyl', const embed = {
description: `You have **insufficient** credits.`, title: ':shopping_cart: Shop - Pterodactyl',
color: config.colors.error, description: `You have **insufficient** credits.`,
fields: [ color: config.colors.error as any,
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` }, fields: [
], { name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
timestamp: new Date(), ],
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
return interaction.editReply({ embeds: [embed], ephemeral: true }); };
} return interaction.editReply({ embeds: [embed] });
}
// Generate a unique voucher for the user
const code = uuidv4(); // Generate a unique voucher for the user
const code = uuidv4();
// Get api object
const apiCredentials = await apis.findOne({ // Get api object
guildId: guild.id, const apiCredentials = await apis.findOne({
}); guildId: interaction?.guild?.id,
});
// Create a api instance
const api = axios.create({ // Create a api instance
baseURL: apiCredentials.url, const api = axios.create({
headers: { Authorization: `Bearer ${apiCredentials.token}` }, baseURL: apiCredentials.url,
}); headers: { Authorization: `Bearer ${apiCredentials.token}` },
});
// Get shop URL
const shopUrl = apiCredentials.url.replace('/api', '/store'); // Get shop URL
const shopUrl = apiCredentials.url.replace('/api', '/store');
// Make API request
await api // Make API request
await api
// Make a post request to the API
.post('vouchers', { // Make a post request to the API
uses: 1, .post('vouchers', {
code, uses: 1,
credits: amount || userDB.credits, code,
memo: `${interaction.createdTimestamp} - ${member.id}`, credits: amount || userDB.credits,
}) memo: `${interaction.createdTimestamp} - ${interaction?.user?.id}`,
})
// If successful
.then(async () => { // If successful
// Create DM embed object .then(async () => {
const dmEmbed = { // Create DM embed object
title: ':shopping_cart: Shop - Pterodactyl', const dmEmbed = {
description: `Redeem this voucher [here](${shopUrl})!`, title: ':shopping_cart: Shop - Pterodactyl',
fields: [ description: `Redeem this voucher [here](${shopUrl})!`,
{ name: 'Code', value: `${code}`, inline: true }, fields: [
{ { name: 'Code', value: `${code}`, inline: true },
name: 'Credits', {
value: `${amount || userDB.credits}`, name: 'Credits',
inline: true, value: `${amount || userDB.credits}`,
}, inline: true,
], },
color: config.colors.success, ],
timestamp: new Date(), color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Create interaction embed object
const interactionEmbed = { // Create interaction embed object
title: ':shopping_cart: Shop - Pterodactyl', const interactionEmbed = {
description: 'I have sent you the code in DM!', title: ':shopping_cart: Shop - Pterodactyl',
color: config.colors.success, description: 'I have sent you the code in DM!',
timestamp: new Date(), color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
};
// Withdraw amount from user credits
userDB.credits -= amount || userDB.credits; // Withdraw amount from user credits
userDB.credits -= amount || userDB.credits;
// Save new credits
await userDB // Save new credits
.save() await userDB
// If successful .save()
.then(async () => { // If successful
// Send debug message .then(async () => {
await logger.debug( // Send debug message
`User: ${member.username} redeemed: ${creditNoun(amount)}` await logger.debug(
); `User: ${interaction?.user?.username} redeemed: ${creditNoun(
amount
// Send DM message )}`
await dmUser.send({ embeds: [dmEmbed] }); );
// Send interaction reply // Send DM message
await interaction.editReply({ await dmUser?.send({ embeds: [dmEmbed] });
embeds: [interactionEmbed],
ephemeral: true, // Send interaction reply
}); await interaction.editReply({
}) embeds: [interactionEmbed],
});
// If error occurs })
.catch(async (e) => {
await logger.error(e); // If error occurs
const embed = { .catch(async (e: any) => {
title: ':shopping_cart: Shop - Pterodactyl', await logger.error(e);
description: 'Something went wrong, please try again later.', const embed = {
color: config.colors.error, title: ':shopping_cart: Shop - Pterodactyl',
timestamp: new Date(), description: 'Something went wrong, please try again later.',
footer: { iconURL: config.footer.icon, text: config.footer.text }, color: config.colors.error as any,
}; timestamp: new Date(),
return interaction.editReply({ embeds: [embed], ephemeral: true }); footer: { iconURL: config.footer.icon, text: config.footer.text },
}); };
}) return interaction.editReply({ embeds: [embed] });
});
// If error occurs })
.catch(async (e) => {
await logger.error(e); // If error occurs
const embed = { .catch(async (e) => {
title: ':shopping_cart: Shop - Pterodactyl', await logger.error(e);
description: 'Something went wrong, please try again later.', const embed = {
color: config.colors.error, title: ':shopping_cart: Shop - Pterodactyl',
timestamp: new Date(), description: 'Something went wrong, please try again later.',
footer: { iconURL: config.footer.icon, text: config.footer.text }, color: config.colors.error as any,
}; timestamp: new Date(),
return interaction.editReply({ embeds: [embed], ephemeral: true }); footer: { iconURL: config.footer.icon, text: config.footer.text },
}); };
}; return interaction.editReply({ embeds: [embed] });
});
};

View file

@ -1,47 +0,0 @@
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');
const config = require('../../../../config.json');
const logger = require('../../../handlers/logger');
const { guilds, users } = require('../../../helpers/database/models');
const creditNoun = require('../../../helpers/creditNoun');
module.exports = async (interaction) => {
const name = interaction.options.getString('name');
const { member } = interaction;
const { guild } = member;
const guildDB = await guilds.findOne({ guildId: guild.id });
const userDB = await users.findOne({ userId: member.id, guildId: guild.id });
guild.roles
.create({
data: {
name,
color: 'BLUE',
},
reason: `${interaction.member.id} bought from shop`,
})
.then(async (role) => {
console.log(role);
userDB.credits -= guildDB.shop.roles.pricePerHour;
await userDB.save().then(async () => {
const embed = {
title: ':shopping_cart: Shop - Roles',
description: `You have bought ${role.name} for ${guildDB.shop.roles.pricePerHour} per hour.`,
color: config.colors.error,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
ephemeral: true,
});
});
})
.catch(console.error);
};

View file

@ -0,0 +1,48 @@
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios';
import config from '../../../../config.json';
import logger from '../../../handlers/logger';
import guilds from '../../../helpers/database/models/guildSchema';
import users from '../../../helpers/database/models/userSchema';
import creditNoun from '../../../helpers/creditNoun';
import { CommandInteraction, RoleManager } from 'discord.js';
export default async (interaction: CommandInteraction) => {
const name = interaction.options.getString('name');
const { member } = interaction;
const guildDB = await guilds.findOne({ guildId: interaction?.guild?.id });
const userDB = await users.findOne({
userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
});
if (name === null) return;
(interaction?.guild?.roles as RoleManager)
.create({
name,
color: 'BLUE',
reason: `${interaction?.user?.id} bought from shop`,
})
.then(async (role) => {
console.log(role);
userDB.credits -= guildDB.shop.roles.pricePerHour;
await userDB.save().then(async () => {
const embed = {
title: ':shopping_cart: Shop - Roles',
description: `You have bought ${role.name} for ${guildDB.shop.roles.pricePerHour} per hour.`,
color: config.colors.error as any,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
});
});
})
.catch(console.error);
};

View file

@ -1,61 +1,59 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
const { Permissions } = require('discord.js'); import { Permissions, CommandInteraction } from 'discord.js';
import guilds from '../../helpers/database/models/guildSchema';
const guilds = require('../../helpers/database/models/guildSchema'); import pterodactyl from './addons/pterodactyl';
import roles from './roles';
const pterodactyl = require('./addons/pterodactyl');
const roles = require('./roles'); export default {
data: new SlashCommandBuilder()
module.exports = { .setName('shop')
data: new SlashCommandBuilder() .setDescription('Open our shop.')
.setName('shop') .addSubcommand((subcommand) =>
.setDescription('Open our shop.') subcommand
.addSubcommand((subcommand) => .setName('pterodactyl')
subcommand .setDescription('Buy pterodactyl power.')
.setName('pterodactyl') .addIntegerOption((option) =>
.setDescription('Buy pterodactyl power.') option
.addIntegerOption((option) => .setName('amount')
option .setDescription('How much credits you want to withdraw.')
.setName('amount') )
.setDescription('How much credits you want to withdraw.') )
) .addSubcommandGroup((group) =>
) group
.addSubcommandGroup((group) => .setName('roles')
group .setDescription('Manage custom roles.')
.setName('roles') .addSubcommand((command) =>
.setDescription('Manage custom roles.') command
.addSubcommand((command) => .setName('buy')
command .setDescription('Buy a custom role')
.setName('buy') .addStringOption((option) =>
.setDescription('Buy a custom role') option
.addStringOption((option) => .setName('name')
option .setDescription('Name of the role you wish to purchase.')
.setName('name') )
.setDescription('Name of the role you wish to purchase.') )
) .addSubcommand((command) =>
) command
.addSubcommand((command) => .setName('cancel')
command .setDescription('Cancel a custom role')
.setName('cancel') .addRoleOption((option) =>
.setDescription('Cancel a custom role') option
.addRoleOption((option) => .setName('role')
option .setDescription('Name of the role you wish to cancel.')
.setName('role') )
.setDescription('Name of the role you wish to cancel.') )
) ),
) async execute(interaction: CommandInteraction) {
), // If subcommand is pterodactyl
async execute(interaction) { if (interaction.options.getSubcommand() === 'pterodactyl') {
// If subcommand is pterodactyl // Execute pterodactyl addon
if (interaction.options.getSubcommand() === 'pterodactyl') { await pterodactyl(interaction);
// Execute pterodactyl addon }
await pterodactyl(interaction);
} // If subcommand group is roles
else if (interaction.options.getSubcommandGroup() === 'roles') {
// If subcommand group is roles // Execute roles addon
else if (interaction.options.getSubcommandGroup() === 'roles') { await roles(interaction);
// Execute roles addon }
await roles(interaction); },
} };
},
};

View file

@ -1,68 +0,0 @@
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');
const config = require('../../../../../config.json');
const logger = require('../../../../handlers/logger');
const {
users,
shopRoles,
guilds,
} = require('../../../../helpers/database/models');
const creditNoun = require('../../../../helpers/creditNoun');
module.exports = async (interaction) => {
const { member } = interaction;
const { guild } = member;
const name = await interaction.options.getString('name');
await interaction.guild.roles
.create({
name,
color: 'RED',
reason: `${interaction.member.id} bought from shop`,
})
.then(async (role) => {
// Get guild object
const guildDB = await guilds.findOne({
guildId: interaction.member.guild.id,
});
const userDB = await users.findOne({
userId: member.id,
guildId: guild.id,
});
const { pricePerHour } = guildDB.shop.roles;
userDB.credits -= pricePerHour;
await userDB.save();
await shopRoles.create({
roleId: role.id,
userId: member.id,
guildId: guild.id,
pricePerHour,
lastPayed: new Date(),
});
member.roles.add(role.id);
await shopRoles.find().then((role) => console.log(role));
const embed = {
title: ':shopping_cart: Shop - Roles [Buy]',
description: `You have bought ${role.name} for ${guildDB.shop.roles.pricePerHour} per hour.`,
color: config.colors.success,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
ephemeral: true,
});
})
.catch(console.error);
};

View file

@ -0,0 +1,66 @@
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios';
import config from '../../../../../config.json';
import logger from '../../../../handlers/logger';
import users from '../../../../helpers/database/models/userSchema';
import shopRoles from '../../../../helpers/database/models/shopRolesSchema';
import guilds from '../../../../helpers/database/models/guildSchema';
import creditNoun from '../../../../helpers/creditNoun';
import { CommandInteraction, GuildMemberRoleManager } from 'discord.js';
export default async (interaction: CommandInteraction) => {
const { member } = interaction;
const name = await interaction.options.getString('name');
if (name === null) return;
await interaction?.guild?.roles
.create({
name,
color: 'RED',
reason: `${interaction?.user?.id} bought from shop`,
})
.then(async (role) => {
// Get guild object
const guildDB = await guilds.findOne({
guildId: interaction?.guild?.id,
});
const userDB = await users.findOne({
userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
});
const { pricePerHour } = guildDB.shop.roles;
userDB.credits -= pricePerHour;
await userDB.save();
await shopRoles.create({
roleId: role?.id,
userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
pricePerHour,
lastPayed: new Date(),
});
await (interaction?.member?.roles as GuildMemberRoleManager)?.add(
role?.id
);
await shopRoles.find().then((role: any) => console.log(role));
const embed = {
title: ':shopping_cart: Shop - Roles [Buy]',
description: `You have bought ${role.name} for ${guildDB.shop.roles.pricePerHour} per hour.`,
color: config.colors.success as any,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
});
})
.catch(console.error);
};

View file

@ -1,64 +0,0 @@
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');
const config = require('../../../../../config.json');
const logger = require('../../../../handlers/logger');
const {
users,
shopRoles,
guilds,
} = require('../../../../helpers/database/models');
const creditNoun = require('../../../../helpers/creditNoun');
module.exports = async (interaction) => {
const { member } = interaction;
const { guild } = member;
const role = await interaction.options.getRole('role');
const roleExist = await shopRoles.find({
guildId: guild.id,
userId: member.id,
roleId: role.id,
});
if (roleExist) {
await member.roles.remove(role.id);
await interaction.guild.roles
.delete(role.id, `${interaction.member.id} canceled from shop`)
.then(async () => {
// Get guild object
const guildDB = await guilds.findOne({
guildId: interaction.member.guild.id,
});
const userDB = await users.findOne({
userId: member.id,
guildId: guild.id,
});
await shopRoles.deleteOne({
roleId: role.id,
userId: member.id,
guildId: guild.id,
});
const embed = {
title: ':shopping_cart: Shop - Roles [Buy]',
description: `You have canceled ${role.name}.`,
color: config.colors.success,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
ephemeral: true,
});
})
.catch(console.error);
}
};

View file

@ -0,0 +1,63 @@
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios';
import config from '../../../../../config.json';
import logger from '../../../../handlers/logger';
import users from '../../../../helpers/database/models/userSchema';
import shopRoles from '../../../../helpers/database/models/shopRolesSchema';
import guilds from '../../../../helpers/database/models/guildSchema';
import creditNoun from '../../../../helpers/creditNoun';
import { CommandInteraction, GuildMemberRoleManager } from 'discord.js';
export default async (interaction: CommandInteraction) => {
const { member } = interaction;
const role = await interaction.options.getRole('role');
if (role === null) return;
const roleExist = await shopRoles.find({
guildId: interaction?.guild?.id,
userId: interaction?.user?.id,
roleId: role?.id,
});
if (roleExist) {
await (interaction?.member?.roles as GuildMemberRoleManager).remove(
role?.id
);
await interaction?.guild?.roles
.delete(role?.id, `${interaction?.user?.id} canceled from shop`)
.then(async () => {
// Get guild object
const guildDB = await guilds.findOne({
guildId: interaction?.guild?.id,
});
const userDB = await users.findOne({
userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
});
await shopRoles.deleteOne({
roleId: role?.id,
userId: interaction?.user?.id,
guildId: interaction?.guild?.id,
});
const embed = {
title: ':shopping_cart: Shop - Roles [Buy]',
description: `You have canceled ${role.name}.`,
color: config.colors.success as any,
fields: [
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
],
timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text },
};
return interaction.editReply({
embeds: [embed],
});
})
.catch(console.error);
}
};

View file

@ -1,4 +0,0 @@
const buy = require('./buy');
const cancel = require('./cancel');
module.exports = { buy, cancel };

View file

@ -0,0 +1,4 @@
import buy from './buy';
import cancel from './cancel';
export default { buy, cancel };

View file

@ -1,27 +1,29 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import buy from './addons/buy';
const { buy, cancel } = require('./addons'); import cancel from './addons/cancel';
import { CommandInteraction } from 'discord.js';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
// If subcommand is buy // If subcommand is buy
if (interaction.options.getSubcommand() === 'buy') { if (interaction.options.getSubcommand() === 'buy') {
// Execute buy addon // Execute buy addon
await buy(interaction); await buy(interaction);
} }
// If subcommand is cancel // If subcommand is cancel
if (interaction.options.getSubcommand() === 'cancel') { if (interaction.options.getSubcommand() === 'cancel') {
// Execute cancel addon // Execute cancel addon
await cancel(interaction); await cancel(interaction);
} }
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} executed /${ `Guild: ${interaction?.guild?.id} User: ${
interaction.commandName interaction?.user?.id
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` } executed /${
); interaction.commandName
}; } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
);
};

View file

@ -1,18 +1,18 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
import { CommandInteraction } from 'discord.js';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
const interactionEmbed = { const interactionEmbed = {
title: ':hammer: Utilities - About', title: ':hammer: Utilities - About',
description: `This bot is hosted by ${ description: `This bot is hosted by ${
config.hoster.url config.hoster.url
? `[${config.hoster.name}](${config.hoster.url})` ? `[${config.hoster.name}](${config.hoster.url})`
: `${config.hoster.name}` : `${config.hoster.name}`
}, the bot is developed by [Zyner](https://github.com/ZynerOrg)! }, the bot is developed by [Zyner](https://github.com/ZynerOrg)!
If you are interested in contributing, then just [fork it](https://github.com/ZynerOrg/xyter) yourself, we :heart: Open Source.`, If you are interested in contributing, then just [fork it](https://github.com/ZynerOrg/xyter) yourself, we :heart: Open Source.`,
color: config.colors.success, color: config.colors.success as any,
timestamp: new Date(), timestamp: new Date(),
footer: { iconURL: config.footer.icon, text: config.footer.text }, footer: { iconURL: config.footer.icon, text: config.footer.text },
}; };
interaction.editReply({ embeds: [interactionEmbed], ephemeral: true }); interaction.editReply({ embeds: [interactionEmbed] });
}; };

View file

@ -1,5 +0,0 @@
const lookup = require('./lookup');
const about = require('./about');
const stats = require('./stats');
module.exports = { lookup, about, stats };

View file

@ -0,0 +1,5 @@
import lookup from './lookup';
import about from './about';
import stats from './stats';
export default { lookup, about, stats };

View file

@ -1,88 +1,87 @@
const axios = require('axios'); import axios from 'axios';
import config from '../../../../config.json';
const config = require('../../../../config.json'); import logger from '../../../handlers/logger';
const logger = require('../../../handlers/logger'); import { CommandInteraction } from 'discord.js';
export default async (interaction: CommandInteraction) => {
module.exports = async (interaction) => { try {
try { // Get lookup query
// Get lookup query const query = await interaction.options.getString('query');
const query = await interaction.options.getString('query');
// Make API request
// Make API request await axios
await axios // Make a get request
// Make a get request .get(`http://ip-api.com/json/${query}`)
.get(`http://ip-api.com/json/${query}`)
// If successful
// If successful .then(async (res) => {
.then(async (res) => { // If query failed
// If query failed if (res.data.status === 'fail') {
if (res.data.status === 'fail') { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Utilities - Lookup',
title: ':hammer: Utilities - Lookup', description: `${res.data.message}: ${res.data.query}`,
description: `${res.data.message}: ${res.data.query}`, color: config.colors.error as any,
color: config.colors.error, timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [embed] }); }
}
// If query is successful
// If query is successful else if (res.data.status === 'success') {
else if (res.data.status === 'success') { // Create embed object
// Create embed object const embed = {
const embed = { title: ':hammer: Utilities - Lookup',
title: ':hammer: Utilities - Lookup', fields: [
fields: [ { name: 'AS', value: `${res.data.as || 'Not available'}` },
{ name: 'AS', value: `${res.data.as || 'Not available'}` }, {
{ name: 'Country',
name: 'Country', value: `${res.data.country || 'Not available'}`,
value: `${res.data.country || 'Not available'}`, },
}, {
{ name: 'Country Code',
name: 'Country Code', value: `${res.data.countryCode || 'Not available'}`,
value: `${res.data.countryCode || 'Not available'}`, },
}, {
{ name: 'Region',
name: 'Region', value: `${res.data.region || 'Not available'}`,
value: `${res.data.region || 'Not available'}`, },
}, {
{ name: 'Region Name',
name: 'Region Name', value: `${res.data.regionName || 'Not available'}`,
value: `${res.data.regionName || 'Not available'}`, },
}, { name: 'City', value: `${res.data.city || 'Not available'}` },
{ name: 'City', value: `${res.data.city || 'Not available'}` }, { name: 'ZIP Code', value: `${res.data.zip || 'Not available'}` },
{ name: 'ZIP Code', value: `${res.data.zip || 'Not available'}` }, { name: 'Latitude', value: `${res.data.lat || 'Not available'}` },
{ name: 'Latitude', value: `${res.data.lat || 'Not available'}` }, {
{ name: 'Longitude',
name: 'Longitude', value: `${res.data.lon || 'Not available'}`,
value: `${res.data.lon || 'Not available'}`, },
}, {
{ name: 'Timezone',
name: 'Timezone', value: `${res.data.timezone || 'Not available'}`,
value: `${res.data.timezone || 'Not available'}`, },
}, { name: 'ISP', value: `${res.data.isp || 'Not available'}` },
{ name: 'ISP', value: `${res.data.isp || 'Not available'}` }, {
{ name: 'Organization',
name: 'Organization', value: `${res.data.org || 'Not available'}`,
value: `${res.data.org || 'Not available'}`, },
}, ],
], color: config.colors.success as any,
color: config.colors.success, timestamp: new Date(),
timestamp: new Date(), footer: { iconURL: config.footer.icon, text: config.footer.text },
footer: { iconURL: config.footer.icon, text: config.footer.text }, };
};
// Send interaction reply
// Send interaction reply await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [embed] }); }
} })
}) .catch(async (e) => {
.catch(async (e) => { await logger.error(e);
await logger.error(e); });
}); } catch (e) {
} catch (e) { await logger.error(e);
await logger.error(e); }
} };
};

View file

@ -1,52 +1,53 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
import { CommandInteraction } from 'discord.js';
module.exports = async (interaction) => { export default async (interaction: CommandInteraction) => {
let totalSeconds = interaction.client.uptime / 1000; if (interaction?.client?.uptime === null) return;
const days = Math.floor(totalSeconds / 86400); let totalSeconds = interaction?.client?.uptime / 1000;
totalSeconds %= 86400; const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor(totalSeconds / 3600); totalSeconds %= 86400;
totalSeconds %= 3600; const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor(totalSeconds / 60); totalSeconds %= 3600;
const seconds = Math.floor(totalSeconds % 60); const minutes = Math.floor(totalSeconds / 60);
const seconds = Math.floor(totalSeconds % 60);
const uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`;
const uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`;
const interactionEmbed = {
title: ':hammer: Utilities - Stats', const interactionEmbed = {
description: 'Below you can see a list of statistics about the bot.', title: ':hammer: Utilities - Stats',
fields: [ description: 'Below you can see a list of statistics about the bot.',
{ fields: [
name: '⏰ Latency', {
value: `${Date.now() - interaction.createdTimestamp} ms`, name: '⏰ Latency',
inline: true, value: `${Date.now() - interaction.createdTimestamp} ms`,
}, inline: true,
{ },
name: '⏰ API Latency', {
value: `${Math.round(interaction.client.ws.ping)} ms`, name: '⏰ API Latency',
inline: true, value: `${Math.round(interaction.client.ws.ping)} ms`,
}, inline: true,
{ },
name: '⏰ Uptime', {
value: `${uptime}`, name: '⏰ Uptime',
inline: false, value: `${uptime}`,
}, inline: false,
{ },
name: '📈 Guilds', {
value: `${interaction.client.guilds.cache.size}`, name: '📈 Guilds',
inline: true, value: `${interaction.client.guilds.cache.size}`,
}, inline: true,
{ },
name: '📈 Users (non-unique)', {
value: `${interaction.client.guilds.cache.reduce( name: '📈 Users (non-unique)',
(acc, guild) => acc + guild.memberCount, value: `${interaction.client.guilds.cache.reduce(
0 (acc, guild) => acc + guild.memberCount,
)}`, 0
inline: true, )}`,
}, inline: true,
], },
color: config.colors.success, ],
timestamp: new Date(), color: config.colors.success as any,
footer: { iconURL: config.footer.icon, text: config.footer.text }, timestamp: new Date(),
}; footer: { iconURL: config.footer.icon, text: config.footer.text },
interaction.editReply({ embeds: [interactionEmbed], ephemeral: true }); };
}; interaction.editReply({ embeds: [interactionEmbed] });
};

View file

@ -1,45 +1,46 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import lookup from './addons/lookup';
const { lookup, about, stats } = require('./addons'); import about from './addons/about';
import stats from './addons/stats';
module.exports = { import { CommandInteraction } from 'discord.js';
data: new SlashCommandBuilder() export default {
.setName('utilities') data: new SlashCommandBuilder()
.setDescription('Common utilities.') .setName('utilities')
.addSubcommand((subcommand) => .setDescription('Common utilities.')
subcommand .addSubcommand((subcommand) =>
.setName('lookup') subcommand
.setDescription( .setName('lookup')
'Lookup a domain or ip. (Request sent over HTTP, proceed with caution!)' .setDescription(
) 'Lookup a domain or ip. (Request sent over HTTP, proceed with caution!)'
.addStringOption((option) => )
option .addStringOption((option) =>
.setName('query') option
.setDescription('The query you want to look up.') .setName('query')
.setRequired(true) .setDescription('The query you want to look up.')
) .setRequired(true)
) )
.addSubcommand((subcommand) => )
subcommand.setName('about').setDescription('About this bot!)') .addSubcommand((subcommand) =>
) subcommand.setName('about').setDescription('About this bot!)')
.addSubcommand((subcommand) => )
subcommand.setName('stats').setDescription('Check bot statistics!)') .addSubcommand((subcommand) =>
), subcommand.setName('stats').setDescription('Check bot statistics!)')
async execute(interaction) { ),
// If subcommand is lookup async execute(interaction: CommandInteraction) {
if (interaction.options.getSubcommand() === 'lookup') { // If subcommand is lookup
// Execute lookup addon if (interaction.options.getSubcommand() === 'lookup') {
await lookup(interaction); // Execute lookup addon
} await lookup(interaction);
// If subcommand is about }
else if (interaction.options.getSubcommand() === 'about') { // If subcommand is about
// Execute about addon else if (interaction.options.getSubcommand() === 'about') {
await about(interaction); // Execute about addon
} await about(interaction);
// If subcommand is stats }
else if (interaction.options.getSubcommand() === 'stats') { // If subcommand is stats
// Execute stats addon else if (interaction.options.getSubcommand() === 'stats') {
await stats(interaction); // Execute stats addon
} await stats(interaction);
}, }
}; },
};

0
src/configs/general.ts Normal file
View file

View file

@ -1,23 +1,26 @@
const { dbGuildFix, dbMemberFix } = require('../helpers'); import { Guild } from 'discord.js';
import dbGuildFix from '../helpers/dbGuildFix';
import dbMemberFix from '../helpers/dbMemberFix';
module.exports = { export default {
name: 'guildCreate', name: 'guildCreate',
async execute(guild) { async execute(guild: Guild) {
// Destructure client // Destructure client
const { client } = guild; const { client } = guild;
await guild.members.fetch().then(async (members) => { await guild.members.fetch().then(async (members) => {
await members.forEach(async (member) => { members.forEach(async (member) => {
const { user } = member; const { user } = member;
dbMemberFix(user, guild); dbMemberFix(user, guild);
}); });
}); });
await dbGuildFix(guild); await dbGuildFix(guild);
// Set client status // Set client status
await client.user.setPresence({ client?.user?.setPresence({
activities: [ activities: [
{ type: 'WATCHING', name: `${client.guilds.cache.size} guilds` }, { type: 'WATCHING', name: `${client?.guilds?.cache?.size} guilds` },
], ],
status: 'online', status: 'online',
}); });

View file

@ -1,87 +0,0 @@
const {
guilds,
users,
apis,
counters,
shopRoles,
timeouts,
} = require('../helpers/database/models');
const logger = require('../handlers/logger');
module.exports = {
name: 'guildDelete',
async execute(guild) {
// Destructure client
const { client } = guild;
guilds
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(`Successfully deleted guild: ${guild.id}`);
})
.catch(async (e) => {
await logger.error(`Failed to delete guild: ${guild.id} ${e}`);
});
users
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(`Successfully deleted guild: ${guild.id}'s users`);
})
.catch(async (e) => {
await logger.error(`Failed to delete guild: ${guild.id}'s users ${e}`);
});
apis
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(`Successfully deleted guild: ${guild.id}'s apis`);
})
.catch(async (e) => {
await logger.error(`Failed to delete guild: ${guild.id}'s apis ${e}`);
});
counters
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(
`Successfully deleted guild: ${guild.id}'s counters`
);
})
.catch(async (e) => {
await logger.error(
`Failed to delete guild: ${guild.id}'s counters ${e}`
);
});
shopRoles
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(
`Successfully deleted guild: ${guild.id}'s shop roles`
);
})
.catch(async (e) => {
await logger.error(
`Failed to delete guild: ${guild.id}'s shop roles ${e}`
);
});
timeouts
.deleteMany({ guildId: guild.id })
.then(async () => {
await logger.debug(
`Successfully deleted guild: ${guild.id}'s timeouts`
);
})
.catch(async (e) => {
await logger.error(
`Failed to delete guild: ${guild.id}'s timeouts ${e}`
);
});
// Set client status
await client.user.setPresence({
activities: [
{ type: 'WATCHING', name: `${client.guilds.cache.size} guilds` },
],
status: 'online',
});
},
};

75
src/events/guildDelete.ts Normal file
View file

@ -0,0 +1,75 @@
import guilds from '../helpers/database/models/guildSchema';
import users from '../helpers/database/models/userSchema';
import apis from '../helpers/database/models/apiSchema';
import counters from '../helpers/database/models/counterSchema';
import shopRoles from '../helpers/database/models/shopRolesSchema';
import timeouts from '../helpers/database/models/timeoutSchema';
import logger from '../handlers/logger';
import { Guild } from 'discord.js';
export default {
name: 'guildDelete',
async execute(guild: Guild) {
// Destructure client
const { client } = guild;
guilds
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id} ${e}`);
});
users
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}'s users`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id}'s users ${e}`);
});
apis
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}'s apis`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id}'s apis ${e}`);
});
counters
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}'s counters`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id}'s counters ${e}`);
});
shopRoles
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}'s shop roles`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id}'s shop roles ${e}`);
});
timeouts
.deleteMany({ guildId: guild.id })
.then(async () => {
logger.debug(`Successfully deleted guild: ${guild.id}'s timeouts`);
})
.catch(async (e) => {
logger.error(`Failed to delete guild: ${guild.id}'s timeouts ${e}`);
});
// Set client status
await client?.user?.setPresence({
activities: [
{ type: 'WATCHING', name: `${client.guilds.cache.size} guilds` },
],
status: 'online',
});
},
};

View file

@ -1,15 +0,0 @@
const { users } = require('../helpers/database/models');
const logger = require('../handlers/logger');
module.exports = {
name: 'guildMemberAdd',
async execute(member) {
await users
.create({ userId: member.id, guildId: member.guild.id })
.then(
logger.debug(
`Guild: ${member.guild.id} User: ${member.id} created successfully`
)
);
},
};

View file

@ -0,0 +1,17 @@
import users from '../helpers/database/models/userSchema';
import logger from '../handlers/logger';
import { GuildMember } from 'discord.js';
export default {
name: 'guildMemberAdd',
async execute(member: GuildMember) {
await users
.create({ userId: member?.id, guildId: member?.guild?.id })
.then(async () =>
logger.debug(
`Guild: ${member?.guild?.id} User: ${member?.id} created successfully`
)
);
},
};

View file

@ -1,15 +0,0 @@
const { users } = require('../helpers/database/models');
const logger = require('../handlers/logger');
module.exports = {
name: 'guildMemberRemove',
async execute(member) {
await users
.deleteOne({ userId: member.id, guildId: member.guild.id })
.then(
logger.debug(
`Guild: ${member.guild.id} User: ${member.id} deleted successfully`
)
);
},
};

View file

@ -0,0 +1,17 @@
import users from '../helpers/database/models/userSchema';
import logger from '../handlers/logger';
import { GuildMember } from 'discord.js';
export default {
name: 'guildMemberRemove',
async execute(member: GuildMember) {
await users
.deleteOne({ userId: member?.id, guildId: member?.guild?.id })
.then(async () =>
logger.debug(
`Guild: ${member?.guild?.id} User: ${member?.id} deleted successfully`
)
);
},
};

View file

@ -1,74 +0,0 @@
const config = require('../../config.json');
const logger = require('../handlers/logger');
const { guilds } = require('../helpers/database/models');
module.exports = {
name: 'interactionCreate',
async execute(interaction) {
// Destructure member, client
const { member, client } = interaction;
// If interaction is command
if (interaction.isCommand()) {
// Get command from collection
const command = client.commands.get(interaction.commandName);
// If command do not exist
if (!command) return;
// Create guild if it does not exist already
await guilds.findOne(
{ guildId: member.guild.id },
{ new: true, upsert: true }
);
try {
// Defer reply
await interaction.deferReply({
embeds: [
{
author: {
name: client.user.username,
icon_url: client.user.displayAvatarURL(),
url: 'https://bot.zyner.org/',
},
title: 'Check',
description: 'Please wait...',
color: config.colors.wait,
timestamp: new Date(),
},
],
ephemeral: true,
});
// Execute command
await command.execute(interaction);
// Send debug message
await logger.debug(`Executing command: ${interaction.commandName}`);
} catch (err) {
// Send debug message
await logger.error(err);
// Send interaction reply
await interaction.reply({
embeds: [
{
author: {
name: client.user.username,
icon_url: client.user.displayAvatarURL(),
url: 'https://bot.zyner.org/',
},
title: 'Error',
description: 'There was an error while executing this command!',
color: config.colors.error,
timestamp: new Date(),
},
],
ephemeral: true,
});
}
}
},
};

View file

@ -0,0 +1,57 @@
import config from '../../config.json';
import logger from '../handlers/logger';
import guilds from '../helpers/database/models/guildSchema';
import { Interaction, ColorResolvable } from 'discord.js';
export default {
name: 'interactionCreate',
async execute(interaction: Interaction) {
// Destructure member, client
const { client, guild } = interaction;
// If interaction is command
if (interaction.isCommand()) {
// Get command from collection
const command = client.commands.get(interaction.commandName);
// If command do not exist
if (!command) return;
// Create guild if it does not exist already
await guilds.findOne({ guildId: guild?.id }, { new: true, upsert: true });
try {
// Defer reply
await interaction.deferReply();
// Execute command
await command.execute(interaction);
// Send debug message
logger.debug(`Executing command: ${interaction.commandName}`);
} catch (e) {
// Send debug message
logger.error(e);
// Send interaction reply
await interaction.reply({
embeds: [
{
author: {
name: client?.user?.username,
icon_url: client?.user?.displayAvatarURL(),
url: 'https://bot.zyner.org/',
},
title: 'Error',
description: 'There was an error while executing this command!',
color: config.colors.error as ColorResolvable,
timestamp: new Date(),
},
],
ephemeral: true,
});
}
}
},
};

View file

@ -1,32 +0,0 @@
const { guilds, users } = require('../../helpers/database/models');
const { points, credits, counter } = require('./modules');
module.exports = {
name: 'messageCreate',
async execute(message) {
const { guild, author } = message;
// If message author is bot
if (author.bot) return;
// Get guild object
const guildDB = await guilds.findOne({ guildId: guild.id });
// Get guild object
const userDB = await users.findOne({
guildId: guild.id,
userId: author.id,
});
// Manage credits
await credits(guildDB, userDB, message);
// Manage points
await points(guildDB, userDB, message);
// Manage counter
await counter(guildDB, userDB, message);
},
};

View file

@ -0,0 +1,35 @@
import guilds from '../../helpers/database/models/guildSchema';
import users from '../../helpers/database/models/userSchema';
import points from './modules/points';
import credits from './modules/credits';
import counter from './modules/counter';
import { Message } from 'discord.js';
export default {
name: 'messageCreate',
async execute(message: Message) {
const { guild, author } = message;
// If message author is bot
if (author.bot) return;
// Get guild object
const guildDB = await guilds.findOne({ guildId: guild?.id });
// Get guild object
const userDB = await users.findOne({
guildId: guild?.id,
userId: author?.id,
});
// Manage credits
await credits(guildDB, userDB, message);
// Manage points
await points(guildDB, userDB, message);
// Manage counter
await counter(guildDB, userDB, message);
},
};

View file

@ -1,38 +1,32 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import counters from '../../../helpers/database/models/counterSchema';
const {
users, import { Message } from 'discord.js';
guilds,
experiences, export default async (guildDB: any, userDB: any, message: Message) => {
credits, const { guild, channel, content } = message;
counters,
timeouts, // Get counter object
} = require('../../../helpers/database/models'); const counter = await counters.findOne({
guildId: guild?.id,
module.exports = async (guildDB, userDB, message) => { channelId: channel.id,
const { guild, channel, content } = message; });
// Get counter object // If counter for the message channel
const counter = await counters.findOne({ if (counter) {
guildId: guild.id, // If message content is not strictly the same as counter word
channelId: channel.id, if (content !== counter.word) {
}); // Delete the message
await message.delete();
// If counter for the message channel } else {
if (counter) { // Add 1 to the counter object
// If message content is not strictly the same as counter word await counters.findOneAndUpdate(
if (content !== counter.word) { {
// Delete the message guildId: guild?.id,
await message.delete(); channelId: channel.id,
} else { },
// Add 1 to the counter object { $inc: { counter: 1 } }
await counters.findOneAndUpdate( );
{ }
guildId: guild.id, }
channelId: channel.id, };
},
{ $inc: { counter: 1 } }
);
}
}
};

View file

@ -1,78 +1,70 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import timeouts from '../../../helpers/database/models/timeoutSchema';
const { import { Message } from 'discord.js';
users, export default async (guildDB: any, userDB: any, message: Message) => {
guilds, const { guild, author, channel, content } = message;
experiences,
credits, // If message length is below guild minimum length
counters, if (content.length < guildDB.credits.minimumLength) return;
timeouts,
} = require('../../../helpers/database/models'); // Check if user has a timeout
const isTimeout = await timeouts.findOne({
module.exports = async (guildDB, userDB, message) => { guildId: guild?.id,
const { guild, author, channel, content } = message; userId: author.id,
timeoutId: '2022-03-15-17-42',
// If message length is below guild minimum length });
if (content.length < guildDB.credits.minimumLength) return;
// If user is not on timeout
// Check if user has a timeout if (!isTimeout) {
const isTimeout = await timeouts.findOne({ // Add credits to user
guildId: guild.id,
userId: author.id, userDB.credits += guildDB.credits.rate;
timeoutId: '2022-03-15-17-42',
}); await userDB
.save()
// If user is not on timeout .then(async () => {
if (!isTimeout) { // Send debug message
// Add credits to user await logger.debug(
`Guild: ${guild?.id} User: ${author.id} Channel: ${channel.id} credits add ${guildDB.credits.rate} balance: ${userDB.credits}`
userDB.credits += guildDB.credits.rate; );
})
await userDB .catch(async (e: any) => {
.save() // Send error message
.then(async () => { await logger.error(e);
// Send debug message });
await logger.debug(
`Guild: ${guild.id} User: ${author.id} Channel: ${channel.id} credits add ${guildDB.credits.rate} balance: ${userDB.credits}` // Create a timeout for the user
); await timeouts.create({
}) guildId: guild?.id,
.catch(async (e) => { userId: author.id,
// Send error message timeoutId: '2022-03-15-17-42',
await logger.error(e); });
});
setTimeout(async () => {
// Create a timeout for the user // Send debug message
await timeouts.create({ await logger.debug(
guildId: guild.id, `Guild: ${guild?.id} User: ${author.id} Channel: ${
userId: author.id, channel.id
timeoutId: '2022-03-15-17-42', } has not talked within last ${
}); guildDB.credits.timeout / 1000
} seconds, credits can be given`
setTimeout(async () => { );
// Send debug message
await logger.debug( // When timeout is out, remove it from the database
`Guild: ${guild.id} User: ${author.id} Channel: ${ await timeouts.deleteOne({
channel.id guildId: guild?.id,
} has not talked within last ${ userId: author.id,
guildDB.credits.timeout / 1000 timeoutId: '2022-03-15-17-42',
} seconds, credits can be given` });
); }, guildDB.credits.timeout);
} else {
// When timeout is out, remove it from the database // Send debug message
await timeouts.deleteOne({ await logger.debug(
guildId: guild.id, `Guild: ${guild?.id} User: ${author.id} Channel: ${
userId: author.id, channel.id
timeoutId: '2022-03-15-17-42', } has talked within last ${
}); guildDB.credits.timeout / 1000
}, guildDB.credits.timeout); } seconds, no credits given`
} else { );
// Send debug message }
await logger.debug( };
`Guild: ${guild.id} User: ${author.id} Channel: ${
channel.id
} has talked within last ${
guildDB.credits.timeout / 1000
} seconds, no credits given`
);
}
};

View file

@ -1,5 +0,0 @@
const points = require('./points');
const credits = require('./credits');
const counter = require('./counter');
module.exports = { points, credits, counter };

View file

@ -0,0 +1,5 @@
import points from './points';
import credits from './credits';
import counter from './counter';
export default { points, credits, counter };

View file

@ -1,70 +1,70 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import timeouts from '../../../helpers/database/models/timeoutSchema';
const { timeouts } = require('../../../helpers/database/models');
import { Message } from 'discord.js';
module.exports = async (guildDB, userDB, message) => { export default async (guildDB: any, userDB: any, message: Message) => {
const { author, guild, channel, content } = message; const { author, guild, channel, content } = message;
// If message length is below guild minimum length // If message length is below guild minimum length
if (content.length < guildDB.points.minimumLength) return; if (content.length < guildDB.points.minimumLength) return;
// Check if user has a timeout // Check if user has a timeout
const isTimeout = await timeouts.findOne({ const isTimeout = await timeouts.findOne({
guildId: guild.id, guildId: guild?.id,
userId: author.id, userId: author.id,
timeoutId: '2022-03-15-17-41', timeoutId: '2022-03-15-17-41',
}); });
// If user is not on timeout // If user is not on timeout
if (!isTimeout) { if (!isTimeout) {
// Add points to user // Add points to user
userDB.points += guildDB.points.rate; userDB.points += guildDB.points.rate;
await userDB await userDB
.save() .save()
.then(async () => { .then(async () => {
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${author.id} Channel: ${channel.id} points add: ${guildDB.points.rate} balance: ${userDB.points}` `Guild: ${guild?.id} User: ${author.id} Channel: ${channel.id} points add: ${guildDB.points.rate} balance: ${userDB.points}`
); );
}) })
.catch(async (e) => { .catch(async (e: any) => {
// Send error message // Send error message
await logger.error(e); await logger.error(e);
}); });
// Create a timeout for the user // Create a timeout for the user
await timeouts.create({ await timeouts.create({
guildId: guild.id, guildId: guild?.id,
userId: author.id, userId: author.id,
timeoutId: '2022-03-15-17-41', timeoutId: '2022-03-15-17-41',
}); });
setTimeout(async () => { setTimeout(async () => {
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${author.id} Channel: ${ `Guild: ${guild?.id} User: ${author.id} Channel: ${
channel.id channel.id
} has not talked within last ${ } has not talked within last ${
guildDB.points.timeout / 1000 guildDB.points.timeout / 1000
} seconds, points can be given` } seconds, points can be given`
); );
// When timeout is out, remove it from the database // When timeout is out, remove it from the database
await timeouts.deleteOne({ await timeouts.deleteOne({
guildId: guild.id, guildId: guild?.id,
userId: author.id, userId: author.id,
timeoutId: '2022-03-15-17-41', timeoutId: '2022-03-15-17-41',
}); });
}, guildDB.points.timeout); }, guildDB.points.timeout);
} else { } else {
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${author.id} Channel: ${ `Guild: ${guild?.id} User: ${author.id} Channel: ${
channel.id channel.id
} has talked within last ${ } has talked within last ${
guildDB.points.timeout / 1000 guildDB.points.timeout / 1000
} seconds, no points given` } seconds, no points given`
); );
} }
}; };

View file

@ -1,27 +1,27 @@
const { counters } = require('../helpers/database/models'); import counters from '../helpers/database/models/counterSchema';
import { Message } from 'discord.js';
module.exports = { export default {
name: 'messageUpdate', name: 'messageUpdate',
async execute(oldMessage, newMessage) { async execute(oldMessage: Message, newMessage: Message) {
// If message author is bot // If message author is bot
if (newMessage.author.bot) return; if (newMessage.author.bot) return;
// Get counter object // Get counter object
const counter = await counters.findOne({ const counter = await counters.findOne({
guildId: newMessage.guild.id, guildId: newMessage.guild?.id,
channelId: newMessage.channel.id, channelId: newMessage.channel.id,
}); });
// If counter for the message channel // If counter for the message channel
if (counter) { if (counter) {
// If message content is not strictly the same as counter word // If message content is not strictly the same as counter word
if (newMessage.content !== counter.word) { if (newMessage.content !== counter.word) {
// Delete the message // Delete the message
await newMessage.delete(); await newMessage.delete();
await newMessage.channel.send( await newMessage.channel.send(
`${newMessage.author} said **${counter.word}**.` `${newMessage.author} said **${counter.word}**.`
); );
} }
} }
}, },
}; };

View file

@ -1,36 +1,39 @@
const logger = require('../handlers/logger'); import logger from '../handlers/logger';
const config = require('../../config.json'); import config from '../../config.json';
import deployCommands from '../helpers/deployCommands';
const { deployCommands, dbGuildFix, dbMemberFix } = require('../helpers'); import dbGuildFix from '../helpers/dbGuildFix';
import dbMemberFix from '../helpers/dbMemberFix';
module.exports = {
name: 'ready', import { Client } from 'discord.js';
once: true, export default {
async execute(client) { name: 'ready',
// Send info message once: true,
await logger.info(`Ready! Logged in as ${client.user.tag}`); async execute(client: Client) {
console.log('Test');
// Set client status // Send info message
await client.user.setPresence({ await logger.info(`Ready! Logged in as ${client?.user?.tag}`);
activities: [
{ type: 'WATCHING', name: `${client.guilds.cache.size} guilds` }, // Set client status
], await client?.user?.setPresence({
status: 'online', activities: [
}); { type: 'WATCHING', name: `${client.guilds.cache.size} guilds` },
],
if (config.importToDB) { status: 'online',
const guilds = client.guilds.cache; });
await guilds.map(async (guild) => {
await guild.members.fetch().then(async (members) => { if (config.importToDB) {
await members.forEach(async (member) => { const guilds = client.guilds.cache;
const { user } = member; await guilds.map(async (guild) => {
dbMemberFix(user, guild); await guild?.members.fetch().then(async (members) => {
}); await members.forEach(async (member) => {
}); const { user } = member;
await dbGuildFix(guild); dbMemberFix(user, guild);
}); });
} });
await dbGuildFix(guild);
await deployCommands(); });
}, }
};
await deployCommands();
},
};

View file

@ -1,13 +0,0 @@
const fs = require('fs'); // fs
const { Collection } = require('discord.js'); // discord.js
module.exports = async (client) => {
client.commands = new Collection();
const commandFiles = fs.readdirSync('./src/commands');
for (const file of commandFiles) {
// eslint-disable-next-line import/no-dynamic-require, global-require
const command = require(`../commands/${file}`);
client.commands.set(command.data.name, command);
}
};

12
src/handlers/commands.ts Normal file
View file

@ -0,0 +1,12 @@
import fs from 'fs'; // fs
import { Collection } from 'discord.js'; // discord.js
import { Client } from '../types/common/discord';
export default async (client: Client) => {
client.commands = new Collection();
const commandFiles = fs.readdirSync('./src/commands');
for (const file of commandFiles) {
const command = require(`../commands/${file}`);
client.commands.set(command.default.data.name, command.default);
}
};

View file

@ -1,14 +0,0 @@
const fs = require('fs'); // fs
module.exports = async (client) => {
const eventFiles = fs.readdirSync('./src/events');
for (const file of eventFiles) {
const event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
};

19
src/handlers/events.ts Normal file
View file

@ -0,0 +1,19 @@
import fs from 'fs'; // fs
import { Client } from 'discord.js'; // discord.js
export default async (client: Client) => {
const eventFiles = fs.readdirSync('./src/events');
for (const file of eventFiles) {
const event = require(`../events/${file}`);
if (event.once) {
client.once(event.default.name, (...args) =>
event.default.execute(...args)
);
} else {
client.on(event.default.name, (...args) =>
event.default.execute(...args)
);
}
}
};

View file

@ -1,6 +0,0 @@
const events = require('./events');
const commands = require('./commands');
const locale = require('./locale');
const schedules = require('./schedules');
module.exports = { events, commands, locale, schedules };

6
src/handlers/index.ts Normal file
View file

@ -0,0 +1,6 @@
import events from './events';
import commands from './commands';
import locale from './locale';
import schedules from './schedules';
export default { events, commands, locale, schedules };

View file

@ -1,135 +1,135 @@
const i18next = require('i18next'); import i18next from 'i18next';
module.exports = async () => { export default async () => {
await i18next.init({ await i18next.init({
lng: 'en', // if you're using a language detector, do not define the lng option lng: 'en', // if you're using a language detector, do not define the lng option
// debug: true, // debug: true,
fallbackLng: 'en', fallbackLng: 'en',
resources: { resources: {
en: { en: {
general: { not_available: 'Not Available' }, general: { not_available: 'Not Available' },
commands: { commands: {
credits: { credits: {
general: { general: {
credits_one: '{{count}} credit', credits_one: '{{count}} credit',
credits_other: '{{count}} credits', credits_other: '{{count}} credits',
}, },
addons: { addons: {
balance: { embed: { title: 'Credits' } }, balance: { embed: { title: 'Credits' } },
gift: { embed: { title: 'Gift' } }, gift: { embed: { title: 'Gift' } },
}, },
}, },
reputation: { reputation: {
addons: { addons: {
give: { give: {
version01: { version01: {
embed: { embed: {
title: ':medal: Reputation', title: ':medal: Reputation',
description: description:
'You have given reputation within the last day, you can not repute now!', 'You have given reputation within the last day, you can not repute now!',
}, },
}, },
version02: { version02: {
embed: { embed: {
title: ':medal: Reputation', title: ':medal: Reputation',
description: description:
'You have given {{user}} a {{type}} reputation!', 'You have given {{user}} a {{type}} reputation!',
}, },
}, },
version03: { version03: {
embed: { embed: {
title: ':medal: Reputation', title: ':medal: Reputation',
description: 'You can not repute yourself.', description: 'You can not repute yourself.',
}, },
}, },
}, },
}, },
}, },
profile: { profile: {
addons: { addons: {
view: { view: {
embed: { embed: {
title: 'Profile', title: 'Profile',
reputation: 'Reputation (Global)', reputation: 'Reputation (Global)',
level: 'Level (Guild)', level: 'Level (Guild)',
points: 'Points (Guild)', points: 'Points (Guild)',
credits: 'Credits (Guild)', credits: 'Credits (Guild)',
language_code: 'Language Code (Global)', language_code: 'Language Code (Global)',
}, },
}, },
settings: { settings: {
embed: { embed: {
title: 'Profile', title: 'Profile',
description: 'Following settings is set', description: 'Following settings is set',
fields: { language: 'Language' }, fields: { language: 'Language' },
}, },
}, },
}, },
}, },
}, },
}, },
sv: { sv: {
general: { not_available: 'Otillgänglig' }, general: { not_available: 'Otillgänglig' },
commands: { commands: {
credits: { credits: {
general: { general: {
credits_one: '{{count}} krona', credits_one: '{{count}} krona',
credits_other: '{{count}} kronor', credits_other: '{{count}} kronor',
}, },
addons: { addons: {
balance: { embed: { title: 'Krediter' } }, balance: { embed: { title: 'Krediter' } },
gift: { embed: { title: 'Gåva' } }, gift: { embed: { title: 'Gåva' } },
}, },
}, },
reputation: { reputation: {
addons: { addons: {
give: { give: {
version01: { version01: {
embed: { embed: {
title: ':medal: Omdöme', title: ':medal: Omdöme',
description: description:
'Du har redan gett omdöme inom den senaste dagen, du kan inte ge ett omdöme just nu!', 'Du har redan gett omdöme inom den senaste dagen, du kan inte ge ett omdöme just nu!',
}, },
}, },
version02: { version02: {
embed: { embed: {
title: ':medal: Omdöme', title: ':medal: Omdöme',
description: 'Du har gett {{user}} ett {{type}} omdöme!', description: 'Du har gett {{user}} ett {{type}} omdöme!',
}, },
}, },
version03: { version03: {
embed: { embed: {
title: ':medal: Omdöme', title: ':medal: Omdöme',
description: 'Du kan inte ge dig själv ett omdöme.', description: 'Du kan inte ge dig själv ett omdöme.',
}, },
}, },
}, },
}, },
}, },
profile: { profile: {
addons: { addons: {
view: { view: {
embed: { embed: {
title: 'Profil', title: 'Profil',
reputation: 'Omdöme (Globalt)', reputation: 'Omdöme (Globalt)',
level: 'Nivå (Server)', level: 'Nivå (Server)',
points: 'Poäng (Server)', points: 'Poäng (Server)',
credits: 'Krediter (Server)', credits: 'Krediter (Server)',
language_code: 'Språkkod (Globalt)', language_code: 'Språkkod (Globalt)',
}, },
}, },
settings: { settings: {
embed: { embed: {
title: 'Profil', title: 'Profil',
description: 'Följande inställningar är satta', description: 'Följande inställningar är satta',
fields: { language: 'Språk' }, fields: { language: 'Språk' },
}, },
}, },
}, },
}, },
}, },
}, },
}, },
}); });
}; };

View file

@ -1,6 +0,0 @@
const pino = require('pino');
const config = require('../../config.json');
const logger = pino({ level: config.debug ? 'debug' : 'info' });
module.exports = logger;

4
src/handlers/logger.ts Normal file
View file

@ -0,0 +1,4 @@
import pino from 'pino';
import * as config from '../../config.json';
export default pino({ level: config.debug ? 'debug' : 'info' });

View file

@ -1,48 +1,50 @@
const schedule = require('node-schedule'); import schedule from 'node-schedule';
const { shopRoles, users, guilds } = require('../helpers/database/models'); import users from '../helpers/database/models/userSchema';
const logger = require('./logger'); import shopRoles from '../helpers/database/models/shopRolesSchema';
import guilds from '../helpers/database/models/guildSchema';
module.exports = async (client) => { import logger from './logger';
schedule.scheduleJob('*/30 * * * *', async () => { import { Client } from 'discord.js';
shopRoles.find().then(async (shopRoles) => { export default async (client: Client) => {
shopRoles.map(async (shopRole) => { schedule.scheduleJob('*/30 * * * *', async () => {
const payed = new Date(shopRole.lastPayed); shopRoles.find().then(async (shopRoles: any) => {
shopRoles.map(async (shopRole: any) => {
oneHourAfterPayed = payed.setHours(payed.getHours() + 1); const payed = new Date(shopRole.lastPayed);
if (new Date() > oneHourAfterPayed) { const oneHourAfterPayed = payed.setHours(payed.getHours() + 1);
// Get guild object
const guild = await guilds.findOne({ if (new Date() > new Date(oneHourAfterPayed)) {
guildId: shopRole.guildId, // Get guild object
}); const guild = await guilds.findOne({
guildId: shopRole.guildId,
const userDB = await users.findOne({ });
userId: shopRole.userId,
guildId: shopRole.guildId, const userDB = await users.findOne({
}); userId: shopRole.userId,
const { pricePerHour } = guild.shop.roles; guildId: shopRole.guildId,
});
if (userDB.credits < pricePerHour) { const { pricePerHour } = guild.shop.roles;
const rGuild = await client.guilds.cache.get(`${shopRole.guildId}`);
const rMember = await rGuild.members.fetch(`${shopRole.userId}`); if (userDB.credits < pricePerHour) {
const rGuild = await client.guilds.cache.get(`${shopRole.guildId}`);
await rMember.roles const rMember = await rGuild?.members.fetch(`${shopRole.userId}`);
.remove(`${shopRole.roleId}`)
.then(console.log) await rMember?.roles
.catch(console.error); // Removes all roles .remove(`${shopRole.roleId}`)
} .then(console.log)
.catch(console.error); // Removes all roles
shopRole.lastPayed = new Date(); }
shopRole.save();
userDB.credits -= pricePerHour; shopRole.lastPayed = new Date();
userDB.save(); shopRole.save();
await logger.debug( userDB.credits -= pricePerHour;
`${shopRole.roleId} was payed one hour later. BEFORE: ${payed} AFTER: ${oneHourAfterPayed} UPDATED: ${shopRole.updatedAt} CREATED: ${shopRole.createdAt}` userDB.save();
); await logger.debug(
} `${shopRole.roleId} was payed one hour later. BEFORE: ${payed} AFTER: ${oneHourAfterPayed} UPDATED: ${shopRole.updatedAt} CREATED: ${shopRole.createdAt}`
}); );
}); }
});
await logger.debug('Checking schedules! (Every 30 minutes)'); });
});
}; await logger.debug('Checking schedules! (Every 30 minutes)');
});
};

View file

@ -1,2 +1,2 @@
module.exports = (amount) => export default (amount: number) =>
`${amount <= 1 ? `${amount} credit` : `${amount} credits`}`; `${amount <= 1 ? `${amount} credit` : `${amount} credits`}`;

View file

@ -1,13 +0,0 @@
const mongoose = require('mongoose');
const config = require('../../../config.json');
const logger = require('../../handlers/logger');
module.exports = async () => {
try {
await mongoose.connect(config.mongodb.url);
await logger.info('Connected to the database');
} catch (err) {
await logger.error(err);
}
};

View file

@ -0,0 +1,10 @@
import mongoose from 'mongoose';
import * as config from '../../../config.json';
import logger from '../../handlers/logger';
export default async () =>
{
await mongoose.connect(config.mongodb.url);
logger.info('Connected to the database');
};

View file

@ -1,29 +1,29 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const apiSchema = new mongoose.Schema( const apiSchema = new mongoose.Schema(
{ {
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
url: { url: {
type: mongoose.SchemaTypes.String, type: mongoose.SchemaTypes.String,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
default: 'https://localhost/api/', default: 'https://localhost/api/',
}, },
token: { token: {
type: mongoose.SchemaTypes.String, type: mongoose.SchemaTypes.String,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
default: 'token', default: 'token',
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('api', apiSchema); export default mongoose.model('api', apiSchema);

View file

@ -1,34 +1,34 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const counterSchema = new mongoose.Schema( const counterSchema = new mongoose.Schema(
{ {
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
channelId: { channelId: {
type: mongoose.SchemaTypes.String, type: mongoose.SchemaTypes.String,
required: true, required: true,
unique: true, unique: true,
index: true, index: true,
}, },
word: { word: {
type: mongoose.SchemaTypes.String, type: mongoose.SchemaTypes.String,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
counter: { counter: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
default: 0, default: 0,
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('counter', counterSchema); export default mongoose.model('counter', counterSchema);

View file

@ -1,71 +1,71 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const guildSchema = new mongoose.Schema( const guildSchema = new mongoose.Schema(
{ {
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: true, unique: true,
index: true, index: true,
}, },
credits: { credits: {
status: { status: {
type: mongoose.SchemaTypes.Boolean, type: mongoose.SchemaTypes.Boolean,
default: true, default: true,
}, },
rate: { rate: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 1, default: 1,
}, },
minimumLength: { minimumLength: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 5, default: 5,
}, },
timeout: { timeout: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 5000, default: 5000,
}, },
workRate: { workRate: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 15, default: 15,
}, },
workTimeout: { workTimeout: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 900000, default: 900000,
}, },
}, },
shop: { shop: {
roles: { roles: {
status: { status: {
type: mongoose.SchemaTypes.Boolean, type: mongoose.SchemaTypes.Boolean,
default: true, default: true,
}, },
pricePerHour: { pricePerHour: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 5, default: 5,
}, },
}, },
}, },
points: { points: {
status: { status: {
type: mongoose.SchemaTypes.Boolean, type: mongoose.SchemaTypes.Boolean,
default: false, default: false,
}, },
rate: { rate: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 1, default: 1,
}, },
minimumLength: { minimumLength: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 5, default: 5,
}, },
timeout: { timeout: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
default: 5000, default: 5000,
}, },
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('guild', guildSchema); export default mongoose.model('guild', guildSchema);

View file

@ -1,15 +0,0 @@
const users = require('./userSchema');
const guilds = require('./guildSchema');
const apis = require('./apiSchema');
const timeouts = require('./timeoutSchema');
const counters = require('./counterSchema');
const shopRoles = require('./shopRolesSchema');
module.exports = {
users,
guilds,
apis,
timeouts,
counters,
shopRoles,
};

View file

@ -0,0 +1,15 @@
import users from './userSchema';
import guilds from './guildSchema';
import apis from './apiSchema';
import timeouts from './timeoutSchema';
import counters from './counterSchema';
import shopRoles from './shopRolesSchema';
export default {
users,
guilds,
apis,
timeouts,
counters,
shopRoles,
};

View file

@ -1,39 +1,39 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const shopRoleSchema = new mongoose.Schema( const shopRoleSchema = new mongoose.Schema(
{ {
roleId: { roleId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
userId: { userId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
pricePerHour: { pricePerHour: {
type: mongoose.SchemaTypes.Number, type: mongoose.SchemaTypes.Number,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
default: 5, default: 5,
}, },
lastPayed: { lastPayed: {
type: mongoose.SchemaTypes.Date, type: mongoose.SchemaTypes.Date,
unique: false, unique: false,
index: true, index: true,
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('shopRole', shopRoleSchema); export default mongoose.model('shopRole', shopRoleSchema);

View file

@ -1,22 +1,22 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const timeoutSchema = new mongoose.Schema( const timeoutSchema = new mongoose.Schema(
{ {
userId: { userId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
timeoutId: { type: mongoose.SchemaTypes.String }, timeoutId: { type: mongoose.SchemaTypes.String },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('timeout', timeoutSchema); export default mongoose.model('timeout', timeoutSchema);

View file

@ -1,29 +1,29 @@
const mongoose = require('mongoose'); import mongoose from 'mongoose';
const userSchema = new mongoose.Schema( const userSchema = new mongoose.Schema(
{ {
guildId: { guildId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
userId: { userId: {
type: mongoose.SchemaTypes.Decimal128, type: mongoose.SchemaTypes.Decimal128,
required: true, required: true,
unique: false, unique: false,
index: true, index: true,
}, },
language: { language: {
type: mongoose.SchemaTypes.String, type: mongoose.SchemaTypes.String,
default: 'en', default: 'en',
}, },
reputation: { type: mongoose.SchemaTypes.Number, default: 0 }, reputation: { type: mongoose.SchemaTypes.Number, default: 0 },
credits: { type: mongoose.SchemaTypes.Number, default: 0 }, credits: { type: mongoose.SchemaTypes.Number, default: 0 },
levels: { type: mongoose.SchemaTypes.Number, default: 0 }, levels: { type: mongoose.SchemaTypes.Number, default: 0 },
points: { type: mongoose.SchemaTypes.Number, default: 0 }, points: { type: mongoose.SchemaTypes.Number, default: 0 },
}, },
{ timestamps: true } { timestamps: true }
); );
module.exports = mongoose.model('user', userSchema); export default mongoose.model('user', userSchema);

Some files were not shown because too many files have changed in this diff Show more