Lots of changes

This commit is contained in:
baz 2023-11-19 23:59:41 +00:00
parent 52d9a0879e
commit 9ce1b72394
13 changed files with 245 additions and 190 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,19 +1,27 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('beatgame')
.setName('beatgame') .setDescription('Log a game that you have beat towards the 100 game challenge!')
.setDescription('Log a game that you have beat towards the 100 game challenge!') .addStringOption(option => option.setName('gamename').setDescription('The name of the game.'))
.addStringOption(option => option.setName('gamename').setDescription('The name of the game.')) .addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.').setMinValue(0))
.addNumberOption(option => option.setName('gameid').setDescription('The IGDB game id.')) .addStringOption(option => option.setName('datestarted').setDescription('The date you started playing 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('datebeaten').setDescription('The date you beat the game (today if empty).'));
.addStringOption(option => option.setName('datebeaten').setDescription('The date you beat the game (today if empty).')),
async execute(interaction) {
const gamename = interaction.options.getString('gamename');
const gameid = interaction.options.getNumber('gameid');
if (!gamename && !gameid) return interaction.reply('No gamename or gameid supplied, please supply an option to register a game!'); export async function execute(interaction) {
if (gameid) return interaction.reply(`Game ID "${gameid}" has been beaten, Game logged!`); const gamename = interaction.options.getString('gamename');
return interaction.reply(`Game "${gamename}" has been beaten, Game logged!`); const gameid = interaction.options.getNumber('gameid');
},
}; if (!gamename && !gameid) return interaction.reply('No gamename or gameid supplied, please supply an option to register a game!');
const embed = new EmbedBuilder()
.setColor(0xFFD700)
.setAuthor({ name: `${interaction.user.displayName} beat a new game!`, iconURL: interaction.user.avatarURL() })
.setTitle('osu! beaten')
.setThumbnail('https://upload.wikimedia.org/wikipedia/en/8/8d/Dark_Souls_Cover_Art.jpg')
.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] });
}

View File

@ -1,13 +1,12 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('avatar')
.setName('avatar') .setDescription('Get the avatar URL of the selected user, or your own 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'));
.addUserOption(option => option.setName('user').setDescription('The user\'s avatar to show')),
async execute(interaction) { export async function 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,10 +1,9 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('ping')
.setName('ping') .setDescription('Replies with pong!');
.setDescription('Replies with pong!'),
async execute(interaction) { export async function execute(interaction) {
await interaction.reply('Pong!'); await interaction.reply('Pong!');
}, }
};

View File

@ -1,31 +1,30 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder()
.setName('reload') .setName('reload')
.setDescription('Reload a command.') .setDescription('Reload a command.')
.addStringOption(option => .addStringOption(option =>
option.setName('command') option.setName('command')
.setDescription('The command to reload.') .setDescription('The command to reload.')
.setRequired(true)), .setRequired(true));
async execute(interaction) {
const commandName = interaction.options.getString('command', true).toLowerCase();
const command = interaction.client.commands.get(commandName);
if (!command) { export async function execute(interaction) {
return interaction.reply(`There is no command with name \`${commandName}\`!`); const commandName = interaction.options.getString('command', true).toLowerCase();
} const command = interaction.client.commands.get(commandName);
delete require.cache[require.resolve(`./${command.data.name}.js`)]; if (!command) {
return interaction.reply(`There is no command with name \`${commandName}\`!`);
}
try { delete require.cache[require.resolve(`./${command.data.name}.js`)];
interaction.client.commands.delete(command.data.name);
const newCommand = require(`./${command.data.name}.js`); try {
interaction.client.commands.set(newCommand.data.name, newCommand); interaction.client.commands.delete(command.data.name);
await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`); const newCommand = require(`./${command.data.name}.js`);
} catch (error) { interaction.client.commands.set(newCommand.data.name, newCommand);
console.error(error); await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``); } 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,10 +1,9 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('server')
.setName('server') .setDescription('Provides information about the server.');
.setDescription('Provides information about the server.'),
async execute(interaction) { export async function 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,12 @@
const { SlashCommandBuilder } = require('discord.js'); import { SlashCommandBuilder } from 'discord.js';
module.exports = { export const data = new SlashCommandBuilder()
data: new SlashCommandBuilder() .setName('user')
.setName('user') .setDescription('Provides information about the user.');
.setDescription('Provides information about the user.'),
async execute(interaction) { export async function 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,10 +1,17 @@
const { REST, Routes } = require('discord.js'); import { REST, Routes } from 'discord.js';
const { clientId, guildId, token } = require('./config.json'); //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';
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);
@ -15,7 +22,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 = require(filePath); const command = await import(pathToFileURL(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 {
@ -25,7 +32,7 @@ for (const folder of commandFolders) {
} }
// Construct and prepare an instance of the REST module // Construct and prepare an instance of the REST module
const rest = new REST().setToken(token); const rest = new REST().setToken(process.env.token);
// and deploy your commands! // and deploy your commands!
(async () => { (async () => {
@ -34,7 +41,7 @@ const rest = new REST().setToken(token);
// The put method is used to fully refresh all commands in the guild with the current set // The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put( const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId), Routes.applicationGuildCommands(process.env.clientId, process.env.guildId),
{ body: commands }, { body: commands },
); );

View File

@ -1,51 +1,57 @@
const { Events, Collection } = require('discord.js'); import { Events, Collection } from 'discord.js';
module.exports = { export const name = Events.InteractionCreate;
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
console.log(interaction); export async function execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName); console.log(interaction);
if (!command) { const command = interaction.client.commands.get(interaction.commandName);
console.error(`No command matching ${interaction.commandName} was found.`);
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 });
} }
}
const { cooldowns } = interaction.client; timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
if (!cooldowns.has(command.data.name)) { try {
cooldowns.set(command.data.name, new Collection()); 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 });
} }
}
}
const now = Date.now(); // module.exports = {
const timestamps = cooldowns.get(command.data.name); // name: Events.InteractionCreate,
const defaultCooldownDuration = 3; // async execute(interaction) {
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 @@
const { Events } = require('discord.js'); import { Events } from 'discord.js';
module.exports = { export const name = Events.ClientReady;
name: Events.ClientReady,
once: true, export const 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,8 +1,12 @@
// Require the necessary discord.js classes // Require the necessary discord.js classes
const fs = require('node:fs'); import fs from 'node:fs';
const path = require('node:path'); import path from 'node:path';
const { Client, Collection, GatewayIntentBits } = require('discord.js'); import { pathToFileURL } from 'node:url';
const { token } = require('./config.json'); import { fileURLToPath } from 'url';
import { Client, Collection, GatewayIntentBits } from 'discord.js';
import { config } from 'dotenv';
config();
// Create a new client instance // Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] }); const client = new Client({ intents: [GatewayIntentBits.Guilds] });
@ -10,6 +14,8 @@ 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);
@ -19,7 +25,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 = require(filePath); const command = await import(pathToFileURL(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) {
@ -35,7 +41,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 = require(filePath); const event = await import(pathToFileURL(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 {
@ -43,5 +49,23 @@ for (const file of eventFiles) {
} }
} }
// Log in to Discord with your client's token fetch(
client.login(token); `https://id.twitch.tv/oauth2/token?client_id=${process.env.igdbClientId}&client_secret=${process.env.igdbClientSecret}&grant_type=client_credentials`,
{
method: 'POST',
},
)
.then(r => r.json().then(data => ({ status: r.status, headers: r.headers, body: data })))
.then(resp => {
if (resp.status != 200) {
console.log('Failed with ', resp.status, resp.body);
return;
}
console.log(resp.body.access_token);
})
.catch(err => {
console.error(err);
})
.finally();
client.login(process.env.token);

14
package-lock.json generated
View File

@ -9,7 +9,8 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"discord.js": "^14.14.1" "discord.js": "^14.14.1",
"dotenv": "^16.3.1"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^8.53.0" "eslint": "^8.53.0"
@ -526,6 +527,17 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/dotenv": {
"version": "16.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
"integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/motdotla/dotenv?sponsor=1"
}
},
"node_modules/escape-string-regexp": { "node_modules/escape-string-regexp": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",

View File

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