Move from module to commonjs

This commit is contained in:
baz 2023-11-26 23:02:34 +00:00
parent 56cab90b16
commit e489a1c710
15 changed files with 1359 additions and 260 deletions

View File

@ -1,47 +1,47 @@
// { {
// "extends": "eslint:recommended", "extends": "eslint:recommended",
// "env": { "env": {
// "node": true, "node": true,
// "es6": true "es6": true
// }, },
// "parserOptions": { "parserOptions": {
// "ecmaVersion": 2021 "ecmaVersion": 2021
// }, },
// "rules": { "rules": {
// // "arrow-spacing": ["warn", { "before": true, "after": true }], "arrow-spacing": ["warn", { "before": true, "after": true }],
// // "comma-dangle": ["error", "always-multiline"], "comma-dangle": ["error", "always-multiline"],
// // "comma-spacing": "error", "comma-spacing": "error",
// // "comma-style": "error", "comma-style": "error",
// // "curly": ["error", "multi-line", "consistent"], "curly": ["error", "multi-line", "consistent"],
// // "dot-location": ["error", "property"], "dot-location": ["error", "property"],
// // "handle-callback-err": "off", "handle-callback-err": "off",
// // "keyword-spacing": "error", "keyword-spacing": "error",
// // "max-nested-callbacks": ["error", { "max": 4 }], "max-nested-callbacks": ["error", { "max": 4 }],
// // "max-statements-per-line": ["error", { "max": 2 }], "max-statements-per-line": ["error", { "max": 2 }],
// // "no-console": "off", "no-console": "off",
// // "no-empty-function": "error", "no-empty-function": "error",
// // "no-floating-decimal": "error", "no-floating-decimal": "error",
// // "no-inline-comments": "error", "no-inline-comments": "error",
// // "no-lonely-if": "error", "no-lonely-if": "error",
// // "no-multi-spaces": "error", "no-multi-spaces": "error",
// // "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }], "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
// // "no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }], "no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
// // "no-trailing-spaces": ["error"], "no-trailing-spaces": ["error"],
// // "no-var": "error", "no-var": "error",
// // "object-curly-spacing": ["error", "always"], "object-curly-spacing": ["error", "always"],
// // "prefer-const": "error", "prefer-const": "error",
// // "quotes": ["error", "single"], "quotes": ["error", "single"],
// // "semi": ["error", "always"], "semi": ["error", "always"],
// // "space-before-blocks": "error", "space-before-blocks": "error",
// // "space-before-function-paren": ["error", { "space-before-function-paren": ["error", {
// // "anonymous": "never", "anonymous": "never",
// // "named": "never", "named": "never",
// // "asyncArrow": "always" "asyncArrow": "always"
// // }], }],
// // "space-in-parens": "error", "space-in-parens": "error",
// // "space-infix-ops": "error", "space-infix-ops": "error",
// // "space-unary-ops": "error", "space-unary-ops": "error",
// // "spaced-comment": "error", "spaced-comment": "error",
// // "yoda": "error" "yoda": "error"
// } }
// } }

View File

@ -1,45 +1,49 @@
import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
.setName('beatgame') data: new SlashCommandBuilder()
.setDescription('Log a game that you have beat towards the 100 game challenge!') .setName('beatgame')
.addStringOption(option => option.setName('gamename').setDescription('The name of the game.')) .setDescription('Log a game that you have beat towards the 100 game challenge!')
.addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.').setMinValue(0)) .addStringOption(option => option.setName('gamename').setDescription('The name of the game.'))
.addStringOption(option => option.setName('datestarted').setDescription('The date you started playing the game (today if empty).')) .addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.').setMinValue(0))
.addStringOption(option => option.setName('datebeaten').setDescription('The date you beat the game (today if empty).')) .addStringOption(option => option.setName('datestarted').setDescription('The date you started playing the game (today if empty).'))
.addStringOption(option => option.setName('platform').setDescription('The platform the game was released on.')); .addStringOption(option => option.setName('datebeaten').setDescription('The date you beat the game (today if empty).'))
export async function execute(interaction) { .addStringOption(option => option.setName('platform').setDescription('The platform the game was released on.')),
const gamename = interaction.options.getString('gamename'); async execute(interaction) {
const gameid = interaction.options.getNumber('gameid'); const gamename = interaction.options.getString('gamename');
const platform = interaction.options.getString('platform'); const gameid = interaction.options.getNumber('gameid');
const platform = interaction.options.getString('platform');
if (!gamename && !gameid) return interaction.reply('No gamename or gameid supplied, please supply an option to register a game!'); if (!gamename && !gameid) return interaction.reply('No gamename or gameid supplied, please supply an option to register a game!');
let body = ""; let body = "";
if (gameid) { if (gameid) {
body = body.concat('where id = ', gameid,'; '); body = body.concat('where id = ', gameid,'; ');
} else if (gamename) { } else if (gamename) {
body = body.concat('search "', gamename,'"; '); body = body.concat('search "', gamename,'"; ');
} }
body = body.concat('fields *;'); body = body.concat('fields *;');
let res = await getGameJson(body); let res = await getGameJson(body);
const coverUrl = await getCoverURL(res[0].cover); if (!res[0]) return interaction.reply("No game found for the options supplied.");
const embed = new EmbedBuilder() const coverUrl = await getCoverURL(res[0].cover);
.setColor(0xFFD700)
.setAuthor({ name: `${interaction.user.displayName} beat a new game!`, iconURL: interaction.user.avatarURL() })
.setTitle(`${res[0].name} beaten!`)
.setThumbnail(`${coverUrl}`)
.setDescription(`${interaction.user.displayName} has beaten 69 games, they have 31 games remaining.`)
.setFooter({ text: 'The Ochulus • 100 Games Challenge', iconURL: interaction.client.user.avatarURL() })
.setTimestamp();
return interaction.reply({ embeds: [embed] }); const embed = new EmbedBuilder()
} .setColor(0xFFD700)
.setAuthor({ name: `${interaction.user.displayName} beat a new game!`, iconURL: interaction.user.avatarURL() })
.setTitle(`${res[0].name} beaten!`)
.setThumbnail(`${coverUrl}`)
.setDescription(`${interaction.user.displayName} has beaten 69 games, they have 31 games remaining.`)
.setFooter({ text: 'The Ochulus • 100 Games Challenge', iconURL: interaction.client.user.avatarURL() })
.setTimestamp();
return interaction.reply({ embeds: [embed] });
},
};
async function getGameJson(body) { async function getGameJson(body) {
let res; let res;
@ -105,6 +109,9 @@ async function getCoverURL(id) {
url = 'https:'.concat(response[0].url); url = 'https:'.concat(response[0].url);
} }
}) })
.then(response => {
url = url.replace('t_thumb', 't_1080p_2x');
})
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });

View File

@ -1,12 +1,14 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
.setName('avatar') data: new SlashCommandBuilder()
.setDescription('Get the avatar URL of the selected user, or your own avatar.') .setName('avatar')
.addUserOption(option => option.setName('user').setDescription('The user\'s avatar to show')); .setDescription('Get the avatar URL of the selected user, or your own avatar.')
.addUserOption(option => option.setName('user').setDescription('The user\'s avatar to show')),
export async function execute(interaction) { async execute(interaction) {
const user = interaction.options.getUser('user'); const user = interaction.options.getUser('user');
if (user) return interaction.reply(`${user.username}'s avatar: ${user.displayAvatarURL()}`); if (user) return interaction.reply(`${user.username}'s avatar: ${user.displayAvatarURL()}`);
return interaction.reply(`Your avatar: ${interaction.user.displayAvatarURL()}`); return interaction.reply(`Your avatar: ${interaction.user.displayAvatarURL()}`);
} },
};

View File

@ -1,9 +1,10 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
data: new SlashCommandBuilder()
.setName('och') .setName('och')
.setDescription('och'); .setDescription('och'),
async execute(interaction) {
export async function execute(interaction) { await interaction.reply('och');
await interaction.reply('och'); },
} };

View File

@ -1,9 +1,11 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
.setName('ping') data: new SlashCommandBuilder()
.setDescription('Replies with pong!'); .setName('ping')
.setDescription('Replies with pong!'),
export async function execute(interaction) { async execute(interaction) {
await interaction.reply('Pong!'); await interaction.reply('Pong!');
} },
};

View File

@ -1,30 +1,32 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
.setName('reload') data: new SlashCommandBuilder()
.setDescription('Reload a command.') .setName('reload')
.addStringOption(option => .setDescription('Reload a command.')
option.setName('command') .addStringOption(option =>
.setDescription('The command to reload.') option.setName('command')
.setRequired(true)); .setDescription('The command to reload.')
.setRequired(true)),
export async function execute(interaction) { async execute(interaction) {
const commandName = interaction.options.getString('command', true).toLowerCase(); const commandName = interaction.options.getString('command', true).toLowerCase();
const command = interaction.client.commands.get(commandName); const command = interaction.client.commands.get(commandName);
if (!command) { if (!command) {
return interaction.reply(`There is no command with name \`${commandName}\`!`); return interaction.reply(`There is no command with name \`${commandName}\`!`);
} }
delete require.cache[require.resolve(`./${command.data.name}.js`)]; delete require.cache[require.resolve(`./${command.data.name}.js`)];
try { try {
interaction.client.commands.delete(command.data.name); interaction.client.commands.delete(command.data.name);
const newCommand = require(`./${command.data.name}.js`); const newCommand = require(`./${command.data.name}.js`);
interaction.client.commands.set(newCommand.data.name, newCommand); interaction.client.commands.set(newCommand.data.name, newCommand);
await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`); await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``); await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``);
} }
} },
};

View File

@ -1,9 +1,10 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
.setName('server') data: new SlashCommandBuilder()
.setDescription('Provides information about the server.'); .setName('server')
.setDescription('Provides information about the server.'),
export async function execute(interaction) { async execute(interaction) {
await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`); await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
} },
};

View File

@ -1,12 +1,14 @@
import { SlashCommandBuilder } from 'discord.js'; const { SlashCommandBuilder } = require('discord.js');
export const data = new SlashCommandBuilder() module.exports = {
data: new SlashCommandBuilder()
.setName('user') .setName('user')
.setDescription('Provides information about the user.'); .setDescription('Provides information about the user.'),
export async function execute(interaction) { async execute(interaction) {
// interaction.user is the object representing the user who ran the command // interaction.user is the object representing the user who ran the command
// interaction.member is the GuildMember object, which represents the user in the specific guild // interaction.member is the GuildMember object, which represents the user in the specific guild
await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`); await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`);
} },
};

View File

@ -1,17 +1,12 @@
import { REST, Routes } from 'discord.js'; const { REST, Routes } = require('discord.js');
//import { clientId, guildId, token } from './config.json'; const fs = require('node:fs');
import fs from 'node:fs'; const path = require('node:path');
import path from 'node:path';
import { fileURLToPath } from 'url';
import { pathToFileURL } from 'node:url';
import { config } from 'dotenv'; const { config } = require('dotenv');
config(); config();
const commands = []; const commands = [];
// Grab all the command files from the commands directory you created earlier // Grab all the command files from the commands directory you created earlier
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const foldersPath = path.join(__dirname, 'commands'); const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath); const commandFolders = fs.readdirSync(foldersPath);
@ -22,7 +17,7 @@ for (const folder of commandFolders) {
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) { for (const file of commandFiles) {
const filePath = path.join(commandsPath, file); const filePath = path.join(commandsPath, file);
const command = await import(pathToFileURL(filePath)); const command = require(filePath);
if ('data' in command && 'execute' in command) { if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON()); commands.push(command.data.toJSON());
} else { } else {

View File

@ -1,57 +1,49 @@
import { Events, Collection } from 'discord.js'; const { Events, Collection } = require('discord.js');
export const name = Events.InteractionCreate; module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
export async function execute(interaction) { const command = interaction.client.commands.get(interaction.commandName);
if (!interaction.isChatInputCommand()) return;
// console.log(interaction); if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
const command = interaction.client.commands.get(interaction.commandName); return;
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
const { cooldowns } = interaction.client;
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1000;
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true });
} }
}
timestamps.set(interaction.user.id, now); const { cooldowns } = interaction.client;
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
try { if (!cooldowns.has(command.data.name)) {
await command.execute(interaction); cooldowns.set(command.data.name, new Collection());
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing the command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
} }
}
}
// module.exports = { const now = Date.now();
// name: Events.InteractionCreate, const timestamps = cooldowns.get(command.data.name);
// async execute(interaction) { const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1000;
// }, if (timestamps.has(interaction.user.id)) {
// }; const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true });
}
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing the command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
},
};

View File

@ -1,9 +1,9 @@
import { Events } from 'discord.js'; const { Events } = require('discord.js');
export const name = Events.ClientReady; module.exports = {
name: Events.ClientReady,
export const once = true; once: true,
execute(client) {
export async function execute(client) { console.log(`Ready! Logged in as ${client.user.tag}`);
console.log(`Ready! Logged in as ${client.user.tag}`); },
} };

View File

@ -1,4 +1,4 @@
export class igdb { class igdb {
constructor() { constructor() {
// make a new token every day // make a new token every day
setInterval(() => { setInterval(() => {
@ -30,3 +30,7 @@ export class igdb {
.finally(); .finally();
} }
} }
module.exports = {
igdb
};

View File

@ -1,15 +1,15 @@
// Require the necessary discord.js classes // Require the necessary discord.js classes
import fs from 'node:fs'; const fs = require('node:fs');
import path from 'node:path'; const path = require('node:path');
import { pathToFileURL } from 'node:url'; const { pathToFileURL } = require('node:url');
import { fileURLToPath } from 'url'; const { fileURLToPath } = require('url');
import { Client, Collection, GatewayIntentBits } from 'discord.js'; const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
import { config } from 'dotenv'; const { config } = require('dotenv');
config(); config();
import { igdb } from './igdb.js'; const { igdb } = require('./igdb.js');
export const igdbHelper = new igdb(); const igdbHelper = new igdb();
// Create a new client instance // Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] }); const client = new Client({ intents: [GatewayIntentBits.Guilds] });
@ -17,8 +17,6 @@ const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection(); client.commands = new Collection();
client.cooldowns = new Collection(); client.cooldowns = new Collection();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const foldersPath = path.join(__dirname, 'commands'); const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath); const commandFolders = fs.readdirSync(foldersPath);
@ -28,7 +26,7 @@ for (const folder of commandFolders) {
for (const file of commandFiles) { for (const file of commandFiles) {
const filePath = path.join(commandsPath, file); const filePath = path.join(commandsPath, file);
const command = await import(pathToFileURL(filePath)); const command = require(filePath);
// Set a new item in the collection with the key as the command name and the value as the exported module // Set a new item in the collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) { if ('data' in command && 'execute' in command) {
@ -44,7 +42,7 @@ const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'
for (const file of eventFiles) { for (const file of eventFiles) {
const filePath = path.join(eventsPath, file); const filePath = path.join(eventsPath, file);
const event = await import(pathToFileURL(filePath)); const event = require(filePath);
if (event.once) { if (event.once) {
client.once(event.name, (...args) => event.execute(...args)); client.once(event.name, (...args) => event.execute(...args));
} else { } else {
@ -53,3 +51,31 @@ for (const file of eventFiles) {
} }
client.login(process.env.token); client.login(process.env.token);
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sqlite',
});
const Tags = sequelize.define('tags', {
name: {
type: Sequelize.STRING,
unique: true,
},
description: Sequelize.TEXT,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});
client.once(Events.ClientReady, () => {
Tags.sync({ force: true });
console.log(`Logged in as ${client.user.tag}!`);
})

1115
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,12 +6,14 @@
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"type": "module", "type": "commonjs",
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"discord.js": "^14.14.1", "discord.js": "^14.14.1",
"dotenv": "^16.3.1" "dotenv": "^16.3.1",
"sequelize": "^6.35.1",
"sqlite3": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^8.53.0" "eslint": "^8.53.0"