Added database

This commit is contained in:
Xeovalyte 2023-08-03 12:06:31 +02:00
parent b68cb0b219
commit cf968f198a
14 changed files with 1317 additions and 107 deletions

View File

@ -17,7 +17,7 @@
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
"indent": ["error", "tab"],
"indent": ["error", 2],
"keyword-spacing": "error",
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],

View File

@ -0,0 +1,23 @@
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { simpleEmbed } = require('../functions/embeds.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('clear')
.setDescription('Clear 1-100 messages')
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.addNumberOption(option => option
.setName('amount')
.setDescription('The amount of messages to clear')
.setRequired(true)),
async execute(interaction) {
const amount = interaction.options.getNumber('amount');
if (amount < 1 || amount > 100) return await interaction.reply({ embeds: [simpleEmbed('The amount must be between 1-100')] });
interaction.channel.bulkDelete(amount, true);
await interaction.reply({ embeds: [simpleEmbed(`Cleared **${amount}** messages`)], ephemeral: true });
},
};

View File

@ -3,12 +3,12 @@ const { simpleEmbed } = require('../functions/embeds.js');
const { client } = require('../index.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
const reply = await interaction.reply({ embeds: [simpleEmbed(`Websocket heartbeat: **${client.ws.ping}ms**\n Roundtrip latency: **Pinging...**`)], fetchReply: true, emphemeral: true });
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
const reply = await interaction.reply({ embeds: [simpleEmbed(`Websocket heartbeat: **${client.ws.ping}ms**\n Roundtrip latency: **Pinging...**`)], fetchReply: true, emphemeral: true });
interaction.editReply({ embeds: [simpleEmbed(`Websocket heartbeat: **${client.ws.ping}ms**\n Roundtrip latency: **${reply.createdTimestamp - interaction.createdTimestamp}ms**`)] });
},
interaction.editReply({ embeds: [simpleEmbed(`Websocket heartbeat: **${client.ws.ping}ms**\n Roundtrip latency: **${reply.createdTimestamp - interaction.createdTimestamp}ms**`)] });
},
};

BIN
discordbot/database.sqlite Normal file

Binary file not shown.

View File

@ -0,0 +1,25 @@
const { Events, EmbedBuilder } = require('discord.js');
const { client } = require('../index.js');
const { Users } = require('../functions/models');
module.exports = {
name: Events.GuildMemberAdd,
async execute(member) {
const addMemberEmbed = new EmbedBuilder()
.setTitle(`${member.user.globalName} has joined!`)
.setDescription(`Welcome ${member} to the **Polarcraft** Discord server!`)
.setColor(process.env.EMBED_COLOR)
.setThumbnail(member.user.avatarURL());
const channel = client.channels.cache.get(process.env.LOG_CHANNEL_ID);
channel.send({ embeds: [addMemberEmbed] });
try {
await Users.create({
id: member.user.id,
});
} catch (error) {
console.error(error);
}
},
};

View File

@ -0,0 +1,14 @@
const { Events, EmbedBuilder } = require('discord.js');
const { client } = require('../index.js');
module.exports = {
name: Events.GuildMemberRemove,
async execute(member) {
const removeMemberEmbed = new EmbedBuilder()
.setTitle(`${member.user.globalName} has left!`)
.setColor(process.env.EMBED_COLOR);
const channel = client.channels.cache.get(process.env.LOG_CHANNEL_ID);
channel.send({ embeds: [removeMemberEmbed] });
},
};

View File

@ -1,22 +1,22 @@
const { Events } = require('discord.js');
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
};

View File

@ -1,12 +1,17 @@
const { Events } = require('discord.js');
const deployCommands = require('../functions/deployCommands');
const { Users, Teams, Minecraft } = require('../functions/models');
module.exports = {
name: Events.ClientReady,
once: true,
execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
name: Events.ClientReady,
once: true,
execute(client) {
Users.sync();
Teams.sync();
Minecraft.sync();
deployCommands();
},
console.log(`Ready! Logged in as ${client.user.tag}`);
deployCommands();
},
};

View File

@ -3,43 +3,43 @@ const fs = require('node:fs');
const path = require('node:path');
module.exports = function deployCommands() {
const commands = [];
const commands = [];
const commandsPath = path.join(__dirname, '../commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
const commandsPath = path.join(__dirname, '../commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
let data;
if (process.env.GUILD_ID === 'production') {
data = await rest.put(
Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID),
{ body: commands },
);
} else {
data = await rest.put(
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.GUILD_ID),
{ body: commands },
);
}
let data;
if (process.env.GUILD_ID === 'production') {
data = await rest.put(
Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID),
{ body: commands },
);
} else {
data = await rest.put(
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.GUILD_ID),
{ body: commands },
);
}
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
};

View File

@ -1,9 +1,9 @@
const { EmbedBuilder } = require('discord.js');
const simpleEmbed = (value) => {
return new EmbedBuilder()
.setColor(process.env.EMBED_COLOR)
.setDescription(value);
return new EmbedBuilder()
.setColor(process.env.EMBED_COLOR)
.setDescription(value);
};
module.exports = { simpleEmbed };

View File

@ -0,0 +1,56 @@
const { sequelize } = require('../index');
const Sequelize = require('sequelize');
const Users = sequelize.define('users', {
id: {
type: Sequelize.STRING,
primaryKey: true,
unique: true,
},
teamId: {
type: Sequelize.STRING,
},
moderator: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
admin: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
});
const Teams = sequelize.define('teams', {
name: {
type: Sequelize.STRING,
unique: true,
validate: {
len: [3, 16],
isAlphanumeric: true,
},
},
color: {
type: Sequelize.STRING,
validate: {
is: /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,
},
},
});
const Minecraft = sequelize.define('minecraft', {
uuid: {
type: Sequelize.UUID,
unique: true,
primaryKey: true,
},
whitelisted: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
code: {
type: Sequelize.STRING,
unique: true,
},
});
module.exports = { Users, Teams, Minecraft };

View File

@ -1,12 +1,22 @@
const { Client, GatewayIntentBits, Collection } = require('discord.js');
const Sequelize = require('sequelize');
const dotenv = require('dotenv');
const fs = require('node:fs');
const path = require('node:path');
dotenv.config();
const sequelize = new Sequelize('polarcraft', 'user', process.env.DATABSE_PASSWORD, {
host: 'localhost',
dialect: 'sqlite',
logging: false,
// SQLite only
storage: 'database.sqlite',
});
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
exports.sequelize = sequelize;
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
exports.client = client;
client.commands = new Collection();
@ -15,27 +25,28 @@ const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(process.env.DISCORD_TOKEN);

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,9 @@
"license": "ISC",
"dependencies": {
"discord.js": "^14.12.1",
"dotenv": "^16.3.1"
"dotenv": "^16.3.1",
"sequelize": "^6.32.1",
"sqlite3": "^5.1.6"
},
"devDependencies": {
"eslint": "^8.46.0"