🚧 TypeScript rewrite

This commit is contained in:
Axel Olausson Holtenäs 2022-03-20 11:03:11 +01:00
parent e05468b417
commit 0503b8d1ec
No known key found for this signature in database
GPG key ID: E3AE7E194AE017ED
104 changed files with 3743 additions and 3755 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
}

30
.vscode/settings.json vendored
View file

@ -1,16 +1,14 @@
{ {
"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",
@ -28,7 +26,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.28.0", "discord-api-types": "^0.28.0",
"discord-dashboard": "^2.3.14", "discord-dashboard": "^2.3.14",
@ -42,9 +43,13 @@
"uuid": "^8.3.2" "uuid": "^8.3.2"
}, },
"devDependencies": { "devDependencies": {
"eslint": "8.11.0", "@typescript-eslint/eslint-plugin": "^5.15.0",
"eslint-config-airbnb-base": "15.0.0", "@typescript-eslint/parser": "^5.15.0",
"eslint-config-prettier": "8.5.0", "eslint": "^8.11.0",
"eslint-plugin-import": "2.25.4" "eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-prettier": "^4.0.0",
"prettier": "^2.6.0"
} }
} }

View file

@ -1,89 +1,89 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
// Check permission // Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { if (!member.permissions.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,
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], ephemeral: true });
} }
// 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,
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: member.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: member.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,
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: ${member.guild.id} User: ${member.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,
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 +1,40 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
// Check permission // Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { if (!member.permissions.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,
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], ephemeral: true });
} }
// Get options // Get options
const channel = await interaction.options.getChannel('channel'); const channel = await interaction.options.getChannel('channel');
await counters await counters
.deleteOne({ guildId: member.guild.id, channelId: channel.id }) .deleteOne({ guildId: member.guild.id, channelId: channel.id })
.then(async () => { .then(async () => {
interaction.editReply({ content: 'Removed' }); interaction.editReply({ content: 'Removed' });
}); });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} executed remove counter.` `Guild: ${member.guild.id} User: ${member.id} executed remove counter.`
); );
}; };

View file

@ -1,44 +1,43 @@
const { Permissions } = require('discord.js'); import { Permissions } 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, remove } from './addons';
const { add, remove } = require('./addons');
export default async (interaction) => {
module.exports = async (interaction) => { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction;
// Check permission
// Check permission if (!member.permissions.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 - Counter',
title: ':toolbox: Admin - Counter', color: config.colors.error,
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 await interaction.editReply({ embeds: [embed], ephemeral: true });
await interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// 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: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` );
); };
};

View file

@ -1,106 +1,106 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
const creditNoun = require('../../../../helpers/creditNoun'); import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member; const { guild } = member;
// Check permission // Check permission
if (!member.permissions.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, 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], ephemeral: true }); return interaction.editReply({ embeds: [embed], ephemeral: true });
} }
// 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');
// 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: ':toolbox: Admin - Credits [Give]', title: ':toolbox: Admin - Credits [Give]',
description: "You can't give zero or below.", description: "You can't give zero or below.",
color: 0xbb2124, color: 0xbb2124,
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], ephemeral: true });
} }
// Get toUserDB object // Get toUserDB object
const toUserDB = await users.findOne({ const toUserDB = await users.findOne({
userId: user.id, userId: user.id,
guildId: interaction.member.guild.id, guildId: interaction.member.guild.id,
}); });
// 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: ':toolbox: Admin - Credits [Give]', title: ':toolbox: Admin - Credits [Give]',
description: description:
'That user has no credits, I can not give credits to the user', 'That user has no credits, I can not give credits to the user',
color: config.colors.error, 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
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed], ephemeral: true });
} }
// Deposit amount to toUserDB // Deposit amount to toUserDB
toUserDB.credits += amount; toUserDB.credits += amount;
// Save toUserDB // Save toUserDB
await toUserDB await toUserDB
.save() .save()
// If successful // If successful
.then(async () => { .then(async () => {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':toolbox: Admin - Credits [Give]', title: ':toolbox: Admin - Credits [Give]',
description: `Gave ${creditNoun(amount)} to ${user}.`, description: `Gave ${creditNoun(amount)} to ${user}.`,
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 },
}; };
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Administrator: ${interaction.user.username} gave ${ `Administrator: ${interaction.user.username} gave ${
amount <= 1 ? `${amount} credit` : `${amount} credits` amount <= 1 ? `${amount} credit` : `${amount} credits`
} to ${user.username}` } to ${user.username}`
); );
// Send interaction reply // Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${member.id} gave ${user.id} ${creditNoun( `Guild: ${guild.id} User: ${member.id} gave ${user.id} ${creditNoun(
amount 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,106 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
const creditNoun = require('../../../../helpers/creditNoun');
import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => {
// Destructure member export default async (interaction) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!member.permissions.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,
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], ephemeral: true });
}
// 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 is zero or below
// Create embed object if (amount <= 0) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Set]', const embed = {
description: "You can't give zero or below.", title: ':toolbox: Admin - Credits [Set]',
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], ephemeral: true });
}
// 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: user.id,
}); guildId: interaction.member.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 [Set]', const embed = {
description: title: ':toolbox: Admin - Credits [Set]',
'That user has no credits, I can not set credits to the user', description:
color: config.colors.error, 'That user has no credits, I can not set credits to the user',
timestamp: new Date(), color: config.colors.error,
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], ephemeral: true });
}
// Set toUserDB with amount
toUserDB.credits = amount; // Set toUserDB with amount
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 [Set]', const embed = {
description: `You set ${creditNoun(amount)} on ${user}.`, title: ':toolbox: Admin - Credits [Set]',
color: 0x22bb33, description: `You set ${creditNoun(amount)} on ${user}.`,
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} set ${ await logger.debug(
amount <= 1 ? `${amount} credit` : `${amount} credits` `Administrator: ${interaction.user.username} set ${
} on ${user.username}` amount <= 1 ? `${amount} credit` : `${amount} credits`
); } on ${user.username}`
);
// Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
await logger.debug( // Send debug message
`Guild: ${member.guild.id} User: ${member.id} set ${ await logger.debug(
user.id `Guild: ${member.guild.id} User: ${member.id} set ${
} to ${creditNoun(amount)}.` user.id
); } to ${creditNoun(amount)}.`
}); );
}; });
};

View file

@ -1,105 +1,106 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
const creditNoun = require('../../../../helpers/creditNoun');
import creditNoun from '../../../../helpers/creditNoun';
module.exports = async (interaction) => {
// Destructure member export default async (interaction) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!member.permissions.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,
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], ephemeral: true });
}
// 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 is zero or below
// Give embed object if (amount <= 0) {
const embed = { // Give embed object
title: ':toolbox: Admin - Credits [Take]', const embed = {
description: "You can't take zero or below.", title: ':toolbox: Admin - Credits [Take]',
color: 0xbb2124, description: "You can't take 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], ephemeral: true });
}
// Get toUser object
const toUser = await users.findOne({ // Get toUser object
userId: user.id, const toUser = await users.findOne({
guildId: interaction.member.guild.id, userId: user.id,
}); guildId: interaction.member.guild.id,
});
// 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 [Take]', const embed = {
description: title: ':toolbox: Admin - Credits [Take]',
'That user has no credits, I can not take credits from the user', description:
color: config.colors.error, 'That user has no credits, I can not take credits from the user',
timestamp: new Date(), color: config.colors.error,
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], ephemeral: true });
}
// Withdraw amount from toUser
toUser.credits -= amount; // Withdraw amount from toUser
toUser.credits -= amount;
// Save toUser
await toUser // Save toUser
.save() await toUser
.save()
// If successful
.then(async () => { // If successful
// Create embed object .then(async () => {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Take]', const embed = {
description: `You took ${creditNoun(amount)} to ${user}.`, title: ':toolbox: Admin - Credits [Take]',
color: 0x22bb33, description: `You took ${creditNoun(amount)} to ${user}.`,
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} took ${ await logger.debug(
amount <= 1 ? `${amount} credit` : `${amount} credits` `Administrator: ${interaction.user.username} took ${
} from ${user.username}` amount <= 1 ? `${amount} credit` : `${amount} credits`
); } from ${user.username}`
);
// Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true }); // Send interaction reply
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
await logger.debug( // Send debug message
`Guild: ${member.guild.id} User: ${member.id} took ${creditNoun( await logger.debug(
amount `Guild: ${member.guild.id} User: ${member.id} took ${creditNoun(
)} from ${user.id}.` amount
); )} from ${user.id}.`
}); );
}; });
};

View file

@ -1,135 +1,136 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
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) => {
const { member } = interaction; // Destructure member
const { member } = interaction;
// Check permission
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Check permission
// Create embed object if (!member.permissions.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,
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], ephemeral: true });
}
// 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.member.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.member.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,
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], ephemeral: true });
}
// 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,
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], ephemeral: true });
}
// If amount is zero or below
if (amount <= 0) { // If amount is zero or below
// Create embed object if (amount <= 0) {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Transfer]', const embed = {
description: "You can't transfer zero or below.", title: ':toolbox: Admin - Credits [Transfer]',
color: config.colors.error, description: "You can't transfer zero or below.",
timestamp: new Date(), color: config.colors.error,
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], ephemeral: true });
}
// Withdraw amount from fromUser
fromUser.credits -= amount; // Withdraw amount from fromUser
fromUser.credits -= amount;
// Deposit amount to toUser
toUser.credits += amount; // Deposit amount to toUser
toUser.credits += amount;
// Save users
await saveUser(fromUser, toUser) // Save users
// If successful await saveUser(fromUser, toUser)
.then(async () => { // If successful
// Create embed object .then(async () => {
const embed = { // Create embed object
title: ':toolbox: Admin - Credits [Transfer]', const embed = {
description: `You sent ${creditNoun(amount)} from ${from} to ${to}.`, title: ':toolbox: Admin - Credits [Transfer]',
color: config.colors.success, description: `You sent ${creditNoun(amount)} from ${from} to ${to}.`,
fields: [ color: config.colors.success,
{ fields: [
name: `${from.username} Balance`, {
value: `${fromUser.credits}`, name: `${from.username} Balance`,
inline: true, value: `${fromUser.credits}`,
}, inline: true,
{ },
name: `${to.username} Balance`, {
value: `${toUser.credits}`, name: `${to.username} Balance`,
inline: true, value: `${toUser.credits}`,
}, 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
await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message
await logger.debug( // Send debug message
`Guild: ${member.guild.id} User: ${member.id} transferred ${creditNoun( await logger.debug(
amount `Guild: ${member.guild.id} User: ${member.id} transferred ${creditNoun(
)} from ${from.id} to ${to.id}.` amount
); )} from ${from.id} to ${to.id}.`
}); );
}; });
};

View file

@ -1,56 +1,55 @@
const { Permissions } = require('discord.js'); import { Permissions } 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, take, set, transfer } from './addons';
const { give, take, set, transfer } = require('./addons');
export default async (interaction) => {
module.exports = async (interaction) => { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction;
// Check permission
// Check permission if (!member.permissions.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',
title: ':toolbox: Admin - Credits', color: config.colors.error,
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 await interaction.editReply({ embeds: [embed], ephemeral: true });
await interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// 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); }
}
// If subcommand is take
// If subcommand is take else if (interaction.options.getSubcommand() === 'take') {
else if (interaction.options.getSubcommand() === 'take') { // Execute take addon
// Execute take addon await take(interaction);
await take(interaction); }
}
// If subcommand is set
// If subcommand is set else if (interaction.options.getSubcommand() === 'set') {
else if (interaction.options.getSubcommand() === 'set') { // Execute set addon
// Execute set addon await set(interaction);
await set(interaction); }
}
// If subcommand is transfer
// If subcommand is transfer else if (interaction.options.getSubcommand() === 'transfer') {
else if (interaction.options.getSubcommand() === 'transfer') { // Execute transfer addon
// Execute transfer addon await transfer(interaction);
await transfer(interaction); }
}
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${member.guild.id} User: ${member.id} executed /${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` );
); };
};

View file

@ -1,138 +1,137 @@
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');
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('admin')
.setName('admin') .setDescription('Admin actions.')
.setDescription('Admin actions.') .addSubcommandGroup((group) =>
.addSubcommandGroup((group) => group
group .setName('credits')
.setName('credits') .setDescription('Manage credits.')
.setDescription('Manage credits.') .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('give')
.setName('give') .setDescription('Give credits to a user')
.setDescription('Give credits to a user') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('user')
.setName('user') .setDescription('The user you want to pay.')
.setDescription('The user you want to pay.') .setRequired(true)
.setRequired(true) )
) .addIntegerOption((option) =>
.addIntegerOption((option) => option
option .setName('amount')
.setName('amount') .setDescription('The amount you will pay.')
.setDescription('The amount you will pay.') .setRequired(true)
.setRequired(true) )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('set')
.setName('set') .setDescription('Set credits to a user')
.setDescription('Set credits to a user') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('user')
.setName('user') .setDescription('The user you want to set credits on.')
.setDescription('The user you want to set credits on.') .setRequired(true)
.setRequired(true) )
) .addIntegerOption((option) =>
.addIntegerOption((option) => option
option .setName('amount')
.setName('amount') .setDescription('The amount you will set.')
.setDescription('The amount you will set.') .setRequired(true)
.setRequired(true) )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('take')
.setName('take') .setDescription('Take credits from a user')
.setDescription('Take credits from a user') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('user')
.setName('user') .setDescription('The user you want to take credits from.')
.setDescription('The user you want to take credits from.') .setRequired(true)
.setRequired(true) )
) .addIntegerOption((option) =>
.addIntegerOption((option) => option
option .setName('amount')
.setName('amount') .setDescription('The amount you will take.')
.setDescription('The amount you will take.') .setRequired(true)
.setRequired(true) )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('transfer')
.setName('transfer') .setDescription('Transfer credits from a user to another user.')
.setDescription('Transfer credits from a user to another user.') .addUserOption((option) =>
.addUserOption((option) => option
option .setName('from')
.setName('from') .setDescription('The user you want to take credits from.')
.setDescription('The user you want to take credits from.') .setRequired(true)
.setRequired(true) )
) .addUserOption((option) =>
.addUserOption((option) => option
option .setName('to')
.setName('to') .setDescription('The user you want to give credits to.')
.setDescription('The user you want to give credits to.') .setRequired(true)
.setRequired(true) )
) .addIntegerOption((option) =>
.addIntegerOption((option) => option
option .setName('amount')
.setName('amount') .setDescription('The amount you will transfer.')
.setDescription('The amount you will transfer.') .setRequired(true)
.setRequired(true) )
) )
) )
) .addSubcommandGroup((group) =>
.addSubcommandGroup((group) => group
group .setName('counter')
.setName('counter') .setDescription('Manage counters.')
.setDescription('Manage counters.') .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('add')
.setName('add') .setDescription('Add a counter')
.setDescription('Add a counter') .addChannelOption((option) =>
.addChannelOption((option) => option
option .setName('channel')
.setName('channel') .setDescription('The counter channel.')
.setDescription('The counter channel.') .setRequired(true)
.setRequired(true) )
) .addStringOption((option) =>
.addStringOption((option) => option
option .setName('word')
.setName('word') .setDescription('The counter word.')
.setDescription('The counter word.') .setRequired(true)
.setRequired(true) )
) .addNumberOption((option) =>
.addNumberOption((option) => option.setName('start').setDescription('Start at number X.')
option.setName('start').setDescription('Start at number X.') )
) )
) .addSubcommand((command) =>
.addSubcommand((command) => command
command .setName('remove')
.setName('remove') .setDescription('Remove a counter')
.setDescription('Remove a counter') .addChannelOption((option) =>
.addChannelOption((option) => option
option .setName('channel')
.setName('channel') .setDescription('The counter channel.')
.setDescription('The counter channel.') .setRequired(true)
.setRequired(true) )
) )
) ),
), async execute(interaction) {
async execute(interaction) { // If subcommand group is credits
// If subcommand group is credits if (interaction.options.getSubcommandGroup() === 'credits') {
if (interaction.options.getSubcommandGroup() === 'credits') { // Execute credits group
// Execute credits group await credits(interaction);
await credits(interaction); }
}
// If subcommand group is credits
// If subcommand group is credits else if (interaction.options.getSubcommandGroup() === 'counter') {
else if (interaction.options.getSubcommandGroup() === 'counter') { // Execute credits group
// Execute credits group await counter(interaction);
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';
const { counters } = require('../../../helpers/database/models');
export default async (interaction) => {
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: member.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,
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,
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], ephemeral: true });
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,26 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import view from './addons/view';
const view = require('./addons/view');
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('counter')
.setName('counter') .setDescription('Manage counters.')
.setDescription('Manage counters.') .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand
subcommand .setName('view')
.setName('view') .setDescription('View a counter.')
.setDescription('View a counter.') .addChannelOption((option) =>
.addChannelOption((option) => option
option .setName('channel')
.setName('channel') .setDescription('The counter channel you want to view')
.setDescription('The counter channel you want to view') .setRequired(true)
.setRequired(true) )
) ),
), async execute(interaction) {
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,68 +1,67 @@
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';
const { users } = require('../../../helpers/database/models'); import creditNoun from '../../../helpers/creditNoun';
const creditNoun = require('../../../helpers/creditNoun');
export default async (interaction) => {
module.exports = async (interaction) => { // 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.member.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, 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], ephemeral: true }); }
}
// 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, 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], ephemeral: true }); }
}
// 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, 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], ephemeral: true }); }
} };
};

View file

@ -1,139 +1,138 @@
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';
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');
export default async (interaction) => {
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;
const { guild } = member;
// Get fromUserDB object
// Get fromUserDB object const fromUserDB = await users.findOne({
const fromUserDB = await users.findOne({ userId: interaction.user.id,
userId: interaction.user.id, guildId: interaction.member.guild.id,
guildId: interaction.member.guild.id, });
});
// Get toUserDB object
// Get toUserDB object const toUserDB = await users.findOne({
const toUserDB = await users.findOne({ userId: user.id,
userId: user.id, guildId: interaction.member.guild.id,
guildId: interaction.member.guild.id, });
});
// If receiver is same as sender
// If receiver is same as sender if (user.id === interaction.user.id) {
if (user.id === interaction.user.id) { // Create embed object
// Create embed object const embed = {
const embed = { title: ':dollar: Credits - Gift',
title: ':dollar: Credits - Gift', description: "You can't pay yourself.",
description: "You can't pay yourself.", color: 0xbb2124,
color: 0xbb2124, 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], ephemeral: true }); }
}
// 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: 0xbb2124, 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], ephemeral: true }); }
}
// 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: 0xbb2124, 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], ephemeral: true }); }
}
// 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, 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], ephemeral: true }); }
}
// 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(user.id);
// Send DM to user
// Send DM to user await dmUser.send({ embeds: [dmEmbed] });
await dmUser.send({ embeds: [dmEmbed] });
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${guild.id} User: ${member.id} gift sent from: ${interaction.user.id} to: ${user.id}`
`Guild: ${guild.id} User: ${member.id} gift sent from: ${interaction.user.id} to: ${user.id}` );
);
// Send interaction reply
// Send interaction reply return interaction.editReply({
return interaction.editReply({ embeds: [interactionEmbed],
embeds: [interactionEmbed], ephemeral: true,
ephemeral: true, });
}); });
}); };
};

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';
const creditNoun = require('../../../helpers/creditNoun'); import creditNoun from '../../../helpers/creditNoun';
module.exports = async (interaction) => { export default async (interaction) => {
// 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.member.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, index) =>
`**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: 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 },
}; };
// Send interaction reply // Send interaction reply
return interaction.editReply({ embeds: [embed], ephemeral: true }); return interaction.editReply({ embeds: [embed], ephemeral: true });
}; };

View file

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

View file

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

View file

@ -1,75 +1,70 @@
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, credits, experiences } from '../../../helpers/database/models';
const {
users, export default async (interaction) => {
credits, try {
experiences, // Destructure member
} = require('../../../helpers/database/models'); const { member } = await interaction;
const { guild } = member;
module.exports = async (interaction) => {
try { // Get options
// Destructure member const target = await interaction.options.getUser('target');
const { member } = await interaction;
const { guild } = member; // Get discord user object
const discordUser = await interaction.client.users.fetch(
// Get options `${target ? target.id : member.id}`
const target = await interaction.options.getUser('target'); );
// Get discord user object // Get user object
const discordUser = await interaction.client.users.fetch( const userDB = await users.findOne({
`${target ? target.id : member.id}` userId: await discordUser.id,
); guildId: guild.id,
});
// Get user object
const userDB = await users.findOne({ // Create embed object
userId: await discordUser.id, const embed = {
guildId: guild.id, author: {
}); name: `${await discordUser.username}#${await discordUser.discriminator}`,
icon_url: await discordUser.displayAvatarURL(),
// Create embed object },
const embed = { color: config.colors.success,
author: { fields: [
name: `${await discordUser.username}#${await discordUser.discriminator}`, {
icon_url: await discordUser.displayAvatarURL(), name: `:dollar: Credits`,
}, value: `${userDB.credits || 'Not found'}`,
color: config.colors.success, inline: true,
fields: [ },
{ {
name: `:dollar: Credits`, name: `:squeeze_bottle: Level`,
value: `${userDB.credits || 'Not found'}`, value: `${userDB.level || 'Not found'}`,
inline: true, inline: true,
}, },
{ {
name: `:squeeze_bottle: Level`, name: `:squeeze_bottle: Points`,
value: `${userDB.level || 'Not found'}`, value: `${userDB.points || 'Not found'}`,
inline: true, inline: true,
}, },
{ {
name: `:squeeze_bottle: Points`, name: `:loudspeaker: Reputation`,
value: `${userDB.points || 'Not found'}`, value: `${userDB.reputation || 'Not found'}`,
inline: true, inline: true,
}, },
{ {
name: `:loudspeaker: Reputation`, name: `:rainbow_flag: Language`,
value: `${userDB.reputation || 'Not found'}`, value: `${userDB.language || 'Not found'}`,
inline: true, inline: true,
}, },
{ ],
name: `:rainbow_flag: Language`, timestamp: new Date(),
value: `${userDB.language || 'Not found'}`, footer: { iconURL: config.footer.icon, text: config.footer.text },
inline: true, };
},
], // Send interaction reply
timestamp: new Date(), return await interaction.editReply({ embeds: [embed], ephemeral: true });
footer: { iconURL: config.footer.icon, text: config.footer.text }, } catch (e) {
}; // 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');
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) {
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,121 @@
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, timeouts } from '../../../helpers/database/models';
const { users, timeouts } = require('../../../helpers/database/models');
export default async (interaction) => {
module.exports = async (interaction) => { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction; const { guild } = member;
const { guild } = member;
// 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: member.id, guildId: guild.id,
guildId: 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: guild.id, userId: member.id,
userId: member.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.member.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, 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, 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: ${member.guild.id} User: ${member.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: member.guild.id, userId: member.id,
userId: member.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: ${member.guild.id} User: ${ member.id
member.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: member.guild.id, userId: member.id,
userId: member.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, 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: ${member.guild.id} User: ${member.id} has repute within last ${ config.reputation.timeout / 1000
config.reputation.timeout / 1000 } seconds, no reputation can be given`
} seconds, no reputation can be given` );
); }
} };
};

View file

@ -1,47 +1,46 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
const { Permissions } = require('discord.js'); import { Permissions } 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) {
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: ${member.guild.id} User: ${member.id} executed /${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommand()}`
} ${interaction.options.getSubcommand()}` );
); },
}, };
};

View file

@ -1,96 +1,96 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member; const { guild } = member;
// Check permission // Check permission
if (!member.permissions.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, 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], ephemeral: true }); 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, 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], ephemeral: true }); await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.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,80 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member; const { guild } = member;
// Check permission // Check permission
if (!member.permissions.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, 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], ephemeral: true }); 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: 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, 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], ephemeral: true }); await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${member.id} has changed credit details.` `Guild: ${guild.id} User: ${member.id} has changed credit details.`
); );
}); });
}; };

View file

@ -1,63 +1,63 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member; const { guild } = member;
// Check permission // Check permission
if (!member.permissions.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, 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], ephemeral: true }); 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: 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, 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], ephemeral: true }); await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${guild.id} User: ${member.id} has changed api credentials.` `Guild: ${guild.id} User: ${member.id} has changed api credentials.`
); );
}); });
}; };

View file

@ -1,50 +1,49 @@
const { Permissions } = require('discord.js'); import { Permissions } 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, credits, points } from './addons';
const { pterodactyl, credits, points } = require('./addons');
export default async (interaction) => {
module.exports = async (interaction) => { // Destructure member
// Destructure member const { member } = interaction;
const { member } = interaction;
// Check permission
// Check permission if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) {
if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { // Create embed object
// Create embed object const embed = {
const embed = { title: 'Settings - Guild',
title: 'Settings - Guild', color: config.colors.error,
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 await interaction.editReply({ embeds: [embed], ephemeral: true });
await interaction.editReply({ embeds: [embed], ephemeral: true }); }
}
// If subcommand is pterodactyl
// If subcommand is pterodactyl if (interaction.options.getSubcommand() === 'pterodactyl') {
if (interaction.options.getSubcommand() === 'pterodactyl') { // Execute pterodactyl addon
// Execute pterodactyl addon await pterodactyl(interaction);
await pterodactyl(interaction); }
}
// If subcommand is credits
// If subcommand is credits else if (interaction.options.getSubcommand() === 'credits') {
else if (interaction.options.getSubcommand() === 'credits') { // Execute credits addon
// Execute credits addon await credits(interaction);
await credits(interaction); }
}
// If subcommand is points
// If subcommand is points else if (interaction.options.getSubcommand() === 'points') {
else if (interaction.options.getSubcommand() === 'points') { // Execute points addon
// Execute points addon await points(interaction);
await points(interaction); }
}
// Send debug message
// Send debug message await logger.debug(
await logger.debug( `Guild: ${member.guild.id} User: ${member.id} executed /${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
} ${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 } 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) {
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,47 @@
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';
module.exports = async (interaction) => { export default async (interaction) => {
// Destructure member // Destructure member
const { member } = interaction; const { member } = interaction;
const { guild } = member; 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({ userId: member.id, guildId: guild.id }); const userDB = await users.findOne({ userId: member.id, guildId: guild.id });
// Modify values // Modify values
userDB.language = language !== null ? language : userDB.language; userDB.language = language !== null ? language : userDB.language;
// Save guild // Save guild
await userDB.save().then(async () => { await userDB.save().then(async () => {
// Create embed object // Create embed object
const embed = { const embed = {
title: ':hammer: Settings - User [Appearance]', title: ':hammer: Settings - User [Appearance]',
description: 'Following settings is set!', description: 'Following settings is set!',
color: config.colors.success, color: config.colors.success,
fields: [ fields: [
{ {
name: '🏳️‍🌈 Language', name: '🏳️‍🌈 Language',
value: `${userDB.language}`, value: `${userDB.language}`,
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], ephemeral: true }); await interaction.editReply({ embeds: [embed], ephemeral: true });
// Send debug message // Send debug message
await logger.debug( await logger.debug(
`Guild: ${member.guild.id} User: ${member.id} has changed appearance settings.` `Guild: ${member.guild.id} User: ${member.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,22 @@
const { Permissions } = require('discord.js'); import { Permissions } 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';
const { appearance } = require('./addons');
export default async (interaction) => {
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: ${member.guild.id} User: ${member.id} executed /${
`Guild: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` );
); };
};

View file

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

View file

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

View file

@ -1,64 +1,59 @@
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 { users, shopRoles, guilds } from '../../../../helpers/database/models';
const { import creditNoun from '../../../../helpers/creditNoun';
users,
shopRoles, export default async (interaction) => {
guilds, const { member } = interaction;
} = require('../../../../helpers/database/models'); const { guild } = member;
const creditNoun = require('../../../../helpers/creditNoun');
const role = await interaction.options.getRole('role');
module.exports = async (interaction) => {
const { member } = interaction; const roleExist = await shopRoles.find({
const { guild } = member; guildId: guild.id,
userId: member.id,
const role = await interaction.options.getRole('role'); roleId: role.id,
});
const roleExist = await shopRoles.find({
guildId: guild.id, if (roleExist) {
userId: member.id, await member.roles.remove(role.id);
roleId: role.id,
}); await interaction.guild.roles
.delete(role.id, `${interaction.member.id} canceled from shop`)
if (roleExist) { .then(async () => {
await member.roles.remove(role.id); // Get guild object
const guildDB = await guilds.findOne({
await interaction.guild.roles guildId: interaction.member.guild.id,
.delete(role.id, `${interaction.member.id} canceled from shop`) });
.then(async () => {
// Get guild object const userDB = await users.findOne({
const guildDB = await guilds.findOne({ userId: member.id,
guildId: interaction.member.guild.id, guildId: guild.id,
}); });
const userDB = await users.findOne({ await shopRoles.deleteOne({
userId: member.id, roleId: role.id,
guildId: guild.id, userId: member.id,
}); guildId: guild.id,
});
await shopRoles.deleteOne({
roleId: role.id, const embed = {
userId: member.id, title: ':shopping_cart: Shop - Roles [Buy]',
guildId: guild.id, description: `You have canceled ${role.name}.`,
}); color: config.colors.success,
fields: [
const embed = { { name: 'Your balance', value: `${creditNoun(userDB.credits)}` },
title: ':shopping_cart: Shop - Roles [Buy]', ],
description: `You have canceled ${role.name}.`, timestamp: new Date(),
color: config.colors.success, footer: { iconURL: config.footer.icon, text: config.footer.text },
fields: [ };
{ name: 'Your balance', value: `${creditNoun(userDB.credits)}` }, return interaction.editReply({
], embeds: [embed],
timestamp: new Date(), ephemeral: true,
footer: { iconURL: config.footer.icon, text: config.footer.text }, });
}; })
return interaction.editReply({ .catch(console.error);
embeds: [embed], }
ephemeral: true, };
});
})
.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,26 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import { buy, cancel } from './addons';
const { buy, cancel } = require('./addons');
export default async (interaction) => {
module.exports = async (interaction) => { // 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: ${member.guild.id} User: ${member.id} executed /${ interaction.commandName
interaction.commandName } ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}`
} ${interaction.options.getSubcommandGroup()} ${interaction.options.getSubcommand()}` );
); };
};

View file

@ -1,18 +1,18 @@
const config = require('../../../../config.json'); import config from '../../../../config.json';
module.exports = async (interaction) => { export default async (interaction) => {
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,
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], ephemeral: true });
}; };

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

View file

@ -1,45 +1,44 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); import { SlashCommandBuilder } from '@discordjs/builders';
import { lookup, about, stats } from './addons';
const { lookup, about, stats } = require('./addons');
export default {
module.exports = { data: new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('utilities')
.setName('utilities') .setDescription('Common utilities.')
.setDescription('Common utilities.') .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand
subcommand .setName('lookup')
.setName('lookup') .setDescription(
.setDescription( 'Lookup a domain or ip. (Request sent over HTTP, proceed with caution!)'
'Lookup a domain or ip. (Request sent over HTTP, proceed with caution!)' )
) .addStringOption((option) =>
.addStringOption((option) => option
option .setName('query')
.setName('query') .setDescription('The query you want to look up.')
.setDescription('The query you want to look up.') .setRequired(true)
.setRequired(true) )
) )
) .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand.setName('about').setDescription('About this bot!)')
subcommand.setName('about').setDescription('About this bot!)') )
) .addSubcommand((subcommand) =>
.addSubcommand((subcommand) => subcommand.setName('stats').setDescription('Check bot statistics!)')
subcommand.setName('stats').setDescription('Check bot statistics!)') ),
), async execute(interaction) {
async execute(interaction) { // If subcommand is lookup
// If subcommand is lookup if (interaction.options.getSubcommand() === 'lookup') {
if (interaction.options.getSubcommand() === 'lookup') { // Execute lookup addon
// Execute lookup addon await lookup(interaction);
await lookup(interaction); }
} // If subcommand is about
// If subcommand is about else if (interaction.options.getSubcommand() === 'about') {
else if (interaction.options.getSubcommand() === 'about') { // Execute about addon
// Execute about addon await about(interaction);
await about(interaction); }
} // If subcommand is stats
// If subcommand is stats else if (interaction.options.getSubcommand() === 'stats') {
else if (interaction.options.getSubcommand() === 'stats') { // Execute stats addon
// Execute stats addon await stats(interaction);
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 +1,31 @@
const { guilds, users } = require('../../helpers/database/models'); import { guilds, users } from '../../helpers/database/models';
import { points, credits, counter } from './modules';
const { points, credits, counter } = require('./modules');
export default {
module.exports = { name: 'messageCreate',
name: 'messageCreate', async execute(message) {
async execute(message) { const { guild, author } = message;
const { guild, author } = message;
// If message author is bot
// If message author is bot if (author.bot) return;
if (author.bot) return;
// Get guild object
// Get guild object const guildDB = await guilds.findOne({ guildId: guild.id });
const guildDB = await guilds.findOne({ guildId: guild.id });
// Get guild object
// Get guild object const userDB = await users.findOne({
const userDB = await users.findOne({ guildId: guild.id,
guildId: guild.id, userId: author.id,
userId: author.id, });
});
// Manage credits
// Manage credits
await credits(guildDB, userDB, message);
await credits(guildDB, userDB, message);
// Manage points
// Manage points await points(guildDB, userDB, message);
await points(guildDB, userDB, message);
// Manage counter
// Manage counter await counter(guildDB, userDB, message);
await counter(guildDB, userDB, message); },
}, };
};

View file

@ -1,38 +1,30 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import { users, guilds, experiences, credits, counters, timeouts } from '../../../helpers/database/models';
const {
users, export default async (guildDB, userDB, message) => {
guilds, const { guild, channel, content } = message;
experiences,
credits, // Get counter object
counters, const counter = await counters.findOne({
timeouts, guildId: guild.id,
} = require('../../../helpers/database/models'); channelId: channel.id,
});
module.exports = async (guildDB, userDB, message) => {
const { guild, channel, content } = message; // If counter for the message channel
if (counter) {
// Get counter object // If message content is not strictly the same as counter word
const counter = await counters.findOne({ if (content !== counter.word) {
guildId: guild.id, // Delete the message
channelId: channel.id, await message.delete();
}); } else {
// Add 1 to the counter object
// If counter for the message channel await counters.findOneAndUpdate(
if (counter) { {
// If message content is not strictly the same as counter word guildId: guild.id,
if (content !== counter.word) { channelId: channel.id,
// Delete the message },
await message.delete(); { $inc: { counter: 1 } }
} else { );
// Add 1 to the counter object }
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 { users, guilds, experiences, credits, counters, timeouts } from '../../../helpers/database/models';
const {
users, export default async (guildDB, userDB, 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) => {
.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,69 @@
const logger = require('../../../handlers/logger'); import logger from '../../../handlers/logger';
import { timeouts } from '../../../helpers/database/models';
const { timeouts } = require('../../../helpers/database/models');
export default async (guildDB, userDB, message) => {
module.exports = async (guildDB, userDB, 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) => { // 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';
module.exports = { export default {
name: 'messageUpdate', name: 'messageUpdate',
async execute(oldMessage, newMessage) { async execute(oldMessage, newMessage) {
// 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,35 @@
const logger = require('../handlers/logger'); import logger from '../handlers/logger';
const config = require('../../config.json'); import config from '../../config.json';
import { deployCommands, dbGuildFix, dbMemberFix } from '../helpers';
const { deployCommands, dbGuildFix, dbMemberFix } = require('../helpers');
export default {
module.exports = { name: 'ready',
name: 'ready', once: true,
once: true, async execute(client) {
async execute(client) { // Send info message
// Send info message await logger.info(`Ready! Logged in as ${client.user.tag}`);
await logger.info(`Ready! Logged in as ${client.user.tag}`);
// Set client status
// Set client status await client.user.setPresence({
await 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', });
});
if (config.importToDB) {
if (config.importToDB) { const guilds = client.guilds.cache;
const guilds = client.guilds.cache; await guilds.map(async (guild) => {
await guilds.map(async (guild) => { await guild.members.fetch().then(async (members) => {
await guild.members.fetch().then(async (members) => { await members.forEach(async (member) => {
await members.forEach(async (member) => { const { user } = member;
const { user } = member; dbMemberFix(user, guild);
dbMemberFix(user, guild); });
}); });
}); await dbGuildFix(guild);
await dbGuildFix(guild); });
}); }
}
await deployCommands();
await deployCommands(); },
}, };
};

View file

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

View file

@ -1,6 +1,7 @@
const fs = require('fs'); // fs import fs from 'fs'; // fs
import { Client } from 'discord.js'; // discord.js
module.exports = async (client) => { export default async (client: Client) => {
const eventFiles = fs.readdirSync('./src/events'); const eventFiles = fs.readdirSync('./src/events');
for (const file of eventFiles) { for (const file of eventFiles) {

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

View file

@ -1,21 +1,31 @@
// TODO This file will make sure that all guilds always has at least one entry in all collections with "guildId" // TODO This file will make sure that all guilds always has at least one entry in all collections with "guildId"
const { apis, guilds } = require('./database/models'); import apis from "./database/models/apiSchema"
const logger = require('../handlers/logger'); import guilds from "./database/models/guildSchema"
module.exports = async (guild) => { import logger from '../handlers/logger';
import { Guild } from 'discord.js';
export default async (guild: Guild) =>
{
const api = await apis.findOne({ guildId: guild.id }); const api = await apis.findOne({ guildId: guild.id });
const guildData = await guilds.findOne({ guildId: guild.id }); const guildData = await guilds.findOne({ guildId: guild.id });
if (!api) { if (!api)
{
apis.create({ guildId: guild.id }); apis.create({ guildId: guild.id });
logger.debug(`Guild: ${guild.id} added api collection`); logger.debug(`Guild: ${guild.id} added api collection`);
} else { }
else
{
logger.debug(`Guild: ${guild.id} already in api collection`); logger.debug(`Guild: ${guild.id} already in api collection`);
} }
if (!guildData) { if (!guildData)
{
guilds.create({ guildId: guild.id }); guilds.create({ guildId: guild.id });
logger.debug(`Guild: ${guild.id} added guild collection`); logger.debug(`Guild: ${guild.id} added guild collection`);
} else { }
else
{
logger.debug(`Guild: ${guild.id} already in guild collection`); logger.debug(`Guild: ${guild.id} already in guild collection`);
} }
}; };

View file

@ -1,20 +1,27 @@
const { users } = require('./database/models'); import users from './database/models/userSchema';
const logger = require('../handlers/logger'); import logger from '../handlers/logger';
import { Guild, User } from 'discord.js';
module.exports = async (user, guild) => { export default async (user: User, guild: Guild) =>
{
const userData = await users.findOne({ userId: user.id, guildId: guild.id }); const userData = await users.findOne({ userId: user.id, guildId: guild.id });
if (!userData) { if (!userData)
{
users users
.create({ userId: user.id, guildId: guild.id }) .create({ userId: user.id, guildId: guild.id })
.then(async () => { .then(async () =>
{
await logger.debug(`User: ${user.id} added user collection`); await logger.debug(`User: ${user.id} added user collection`);
}) })
.catch(async (e) => { .catch(async (e) =>
{
await logger.error( await logger.error(
`User: ${user.id} failed to added user collection ${e}` `User: ${user.id} failed to added user collection ${e}`
); );
}); });
} else { }
else
{
logger.debug(`User: ${user.id} already in user collection`); logger.debug(`User: ${user.id} already in user collection`);
} }

View file

@ -1,6 +0,0 @@
const database = require('./database');
const deployCommands = require('./deployCommands');
const dbGuildFix = require('./dbGuildFix');
const dbMemberFix = require('./dbMemberFix');
module.exports = { database, deployCommands, dbGuildFix, dbMemberFix };

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

@ -0,0 +1,6 @@
import database from "./database.ts';
import deployCommands from './deployCommands';
import dbGuildFix from './dbGuildFix';
import dbMemberFix from './dbMemberFix';
export default { database, deployCommands, dbGuildFix, dbMemberFix };

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