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",
// "env": {
// "node": true,
// "es6": true
// },
// "parserOptions": {
// "ecmaVersion": 2021
// },
// "rules": {
// // "arrow-spacing": ["warn", { "before": true, "after": true }],
// // "comma-dangle": ["error", "always-multiline"],
// // "comma-spacing": "error",
// // "comma-style": "error",
// // "curly": ["error", "multi-line", "consistent"],
// // "dot-location": ["error", "property"],
// // "handle-callback-err": "off",
// // "keyword-spacing": "error",
// // "max-nested-callbacks": ["error", { "max": 4 }],
// // "max-statements-per-line": ["error", { "max": 2 }],
// // "no-console": "off",
// // "no-empty-function": "error",
// // "no-floating-decimal": "error",
// // "no-inline-comments": "error",
// // "no-lonely-if": "error",
// // "no-multi-spaces": "error",
// // "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
// // "no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
// // "no-trailing-spaces": ["error"],
// // "no-var": "error",
// // "object-curly-spacing": ["error", "always"],
// // "prefer-const": "error",
// // "quotes": ["error", "single"],
// // "semi": ["error", "always"],
// // "space-before-blocks": "error",
// // "space-before-function-paren": ["error", {
// // "anonymous": "never",
// // "named": "never",
// // "asyncArrow": "always"
// // }],
// // "space-in-parens": "error",
// // "space-infix-ops": "error",
// // "space-unary-ops": "error",
// // "spaced-comment": "error",
// // "yoda": "error"
// }
// }
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2021
},
"rules": {
"arrow-spacing": ["warn", { "before": true, "after": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
"keyword-spacing": "error",
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
"no-trailing-spaces": ["error"],
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "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()
.setName('beatgame')
.setDescription('Log a game that you have beat towards the 100 game challenge!')
.addStringOption(option => option.setName('gamename').setDescription('The name of the game.'))
.addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.').setMinValue(0))
.addStringOption(option => option.setName('datestarted').setDescription('The date you started playing the game (today if empty).'))
.addStringOption(option => option.setName('datebeaten').setDescription('The date you beat the game (today if empty).'))
.addStringOption(option => option.setName('platform').setDescription('The platform the game was released on.'));
export async function execute(interaction) {
const gamename = interaction.options.getString('gamename');
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!');
let body = "";
if (gameid) {
body = body.concat('where id = ', gameid,'; ');
} else if (gamename) {
body = body.concat('search "', gamename,'"; ');
}
body = body.concat('fields *;');
let res = await getGameJson(body);
const coverUrl = await getCoverURL(res[0].cover);
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] });
}
module.exports = {
data: new SlashCommandBuilder()
.setName('beatgame')
.setDescription('Log a game that you have beat towards the 100 game challenge!')
.addStringOption(option => option.setName('gamename').setDescription('The name of the game.'))
.addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.').setMinValue(0))
.addStringOption(option => option.setName('datestarted').setDescription('The date you started playing the game (today if empty).'))
.addStringOption(option => option.setName('datebeaten').setDescription('The date you beat the game (today if empty).'))
.addStringOption(option => option.setName('platform').setDescription('The platform the game was released on.')),
async execute(interaction) {
const gamename = interaction.options.getString('gamename');
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!');
let body = "";
if (gameid) {
body = body.concat('where id = ', gameid,'; ');
} else if (gamename) {
body = body.concat('search "', gamename,'"; ');
}
body = body.concat('fields *;');
let res = await getGameJson(body);
if (!res[0]) return interaction.reply("No game found for the options supplied.");
const coverUrl = await getCoverURL(res[0].cover);
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) {
let res;
@ -105,6 +109,9 @@ async function getCoverURL(id) {
url = 'https:'.concat(response[0].url);
}
})
.then(response => {
url = url.replace('t_thumb', 't_1080p_2x');
})
.catch(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()
.setName('avatar')
.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'));
module.exports = {
data: new SlashCommandBuilder()
.setName('avatar')
.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) {
const user = interaction.options.getUser('user');
if (user) return interaction.reply(`${user.username}'s avatar: ${user.displayAvatarURL()}`);
return interaction.reply(`Your avatar: ${interaction.user.displayAvatarURL()}`);
}
async execute(interaction) {
const user = interaction.options.getUser('user');
if (user) return interaction.reply(`${user.username}'s avatar: ${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')
.setDescription('och');
export async function execute(interaction) {
await interaction.reply('och');
}
.setDescription('och'),
async execute(interaction) {
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()
.setName('ping')
.setDescription('Replies with pong!');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with pong!'),
export async function execute(interaction) {
await interaction.reply('Pong!');
}
async execute(interaction) {
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()
.setName('reload')
.setDescription('Reload a command.')
.addStringOption(option =>
option.setName('command')
.setDescription('The command to reload.')
.setRequired(true));
module.exports = {
data: new SlashCommandBuilder()
.setName('reload')
.setDescription('Reload a command.')
.addStringOption(option =>
option.setName('command')
.setDescription('The command to reload.')
.setRequired(true)),
export async function execute(interaction) {
const commandName = interaction.options.getString('command', true).toLowerCase();
const command = interaction.client.commands.get(commandName);
async execute(interaction) {
const commandName = interaction.options.getString('command', true).toLowerCase();
const command = interaction.client.commands.get(commandName);
if (!command) {
return interaction.reply(`There is no command with name \`${commandName}\`!`);
}
if (!command) {
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 {
interaction.client.commands.delete(command.data.name);
const newCommand = require(`./${command.data.name}.js`);
interaction.client.commands.set(newCommand.data.name, newCommand);
await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
} catch (error) {
console.error(error);
await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``);
}
}
try {
interaction.client.commands.delete(command.data.name);
const newCommand = require(`./${command.data.name}.js`);
interaction.client.commands.set(newCommand.data.name, newCommand);
await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
} catch (error) {
console.error(error);
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()
.setName('server')
.setDescription('Provides information about the server.');
export async function execute(interaction) {
await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
}
module.exports = {
data: new SlashCommandBuilder()
.setName('server')
.setDescription('Provides information about the server.'),
async execute(interaction) {
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')
.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.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}.`);
}
},
};

View File

@ -1,17 +1,12 @@
import { REST, Routes } from 'discord.js';
//import { clientId, guildId, token } from './config.json';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'url';
import { pathToFileURL } from 'node:url';
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
import { config } from 'dotenv';
const { config } = require('dotenv');
config();
const commands = [];
// 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 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
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = await import(pathToFileURL(filePath));
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} 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) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
// console.log(interaction);
const command = interaction.client.commands.get(interaction.commandName);
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 });
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
const { cooldowns } = interaction.client;
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 });
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
}
}
// module.exports = {
// name: Events.InteractionCreate,
// async execute(interaction) {
// },
// };
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);
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;
export const once = true;
export async function execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
}
module.exports = {
name: Events.ClientReady,
once: true,
execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
},
};

View File

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

View File

@ -1,15 +1,15 @@
// Require the necessary discord.js classes
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { fileURLToPath } from 'url';
import { Client, Collection, GatewayIntentBits } from 'discord.js';
const fs = require('node:fs');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const { fileURLToPath } = require('url');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
import { config } from 'dotenv';
const { config } = require('dotenv');
config();
import { igdb } from './igdb.js';
export const igdbHelper = new igdb();
const { igdb } = require('./igdb.js');
const igdbHelper = new igdb();
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
@ -17,8 +17,6 @@ const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
client.cooldowns = new Collection();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
@ -28,7 +26,7 @@ for (const folder of commandFolders) {
for (const file of commandFiles) {
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
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) {
const filePath = path.join(eventsPath, file);
const event = await import(pathToFileURL(filePath));
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
@ -52,4 +50,32 @@ 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": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"type": "commonjs",
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^14.14.1",
"dotenv": "^16.3.1"
"dotenv": "^16.3.1",
"sequelize": "^6.35.1",
"sqlite3": "^5.1.6"
},
"devDependencies": {
"eslint": "^8.53.0"