Update 'index.js'

This commit is contained in:
nodemixaholic 2024-03-25 19:28:07 +00:00
parent a5fcc273ca
commit b5f3cf4625

362
index.js
View file

@ -1,180 +1,182 @@
require('dotenv').config(); // Load environment variables from .env file require('dotenv').config(); // Load environment variables from .env file
const { Client, Intents } = require('discord.js'); const { Client, Intents } = require('discord.js');
const client = new Client({ const client = new Client({
intents: [ intents: [
Intents.FLAGS.GUILDS, Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES // Add intents as needed Intents.FLAGS.GUILD_MESSAGES // Add intents as needed
] ]
}); });
const { SlashCommandBuilder } = require('@discordjs/builders'); const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest'); const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9'); const { Routes } = require('discord-api-types/v9');
const { QuickDB } = require("quick.db"); const { QuickDB } = require("quick.db");
const Perspective = require('perspective-api-client'); const Perspective = require('perspective-api-client');
const express = require('express'); const express = require('express');
// Initialize Express.js app const minimumToxicToDelete = 0.83
const app = express();
const PORT = process.env.PORT || 3000; // Initialize Express.js app
const app = express();
// Initialize the DB const PORT = process.env.PORT || 3000;
const db = new QuickDB();
// Initialize the DB
// Retrieve Application ID from environment variable const db = new QuickDB();
const applicationId = process.env.DISCORD_APPLICATION_ID;
// Retrieve Application ID from environment variable
if (!applicationId) { const applicationId = process.env.DISCORD_APPLICATION_ID;
console.error('Application ID not found in environment variables.');
process.exit(1); // Exit the process if application ID is missing if (!applicationId) {
} console.error('Application ID not found in environment variables.');
const perspective = new Perspective({apiKey: process.env.PERSPECTIVE_API_KEY}); process.exit(1); // Exit the process if application ID is missing
}
// Set up Discord slash commands const perspective = new Perspective({apiKey: process.env.PERSPECTIVE_API_KEY});
const commands = [
new SlashCommandBuilder() // Set up Discord slash commands
.setName('xp') const commands = [
.setDescription('View your XP or someone else\'s XP') new SlashCommandBuilder()
.addUserOption(option => option.setName('user').setDescription('The user to view XP for')), .setName('xp')
new SlashCommandBuilder() .setDescription('View your XP or someone else\'s XP')
.setName('addxp') .addUserOption(option => option.setName('user').setDescription('The user to view XP for')),
.setDescription('Add XP to yourself or someone else (admin only)') new SlashCommandBuilder()
.addIntegerOption(option => option.setName('amount').setDescription('The amount of XP to add')) .setName('addxp')
.addUserOption(option => option.setName('user').setDescription('The user to add XP to')), .setDescription('Add XP to yourself or someone else (admin only)')
new SlashCommandBuilder() .addIntegerOption(option => option.setName('amount').setDescription('The amount of XP to add'))
.setName('removexp') .addUserOption(option => option.setName('user').setDescription('The user to add XP to')),
.setDescription('Remove XP from yourself or someone else (admin only)') new SlashCommandBuilder()
.addIntegerOption(option => option.setName('amount').setDescription('The amount of XP to remove')) .setName('removexp')
.addUserOption(option => option.setName('user').setDescription('The user to remove XP from')), .setDescription('Remove XP from yourself or someone else (admin only)')
].map(command => command.toJSON()); .addIntegerOption(option => option.setName('amount').setDescription('The amount of XP to remove'))
.addUserOption(option => option.setName('user').setDescription('The user to remove XP from')),
const rest = new REST({ version: '9' }).setToken(process.env.DISCORD_BOT_TOKEN); ].map(command => command.toJSON());
(async () => { const rest = new REST({ version: '9' }).setToken(process.env.DISCORD_BOT_TOKEN);
try {
console.log('Started refreshing application (/) commands.'); (async () => {
try {
if (applicationId) { console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(applicationId), if (applicationId) {
{ body: commands }, await rest.put(
); Routes.applicationCommands(applicationId),
console.log('Successfully reloaded application (/) commands.'); { body: commands },
} else { );
console.error('Application ID not found.'); console.log('Successfully reloaded application (/) commands.');
} } else {
} catch (error) { console.error('Application ID not found.');
console.error(error); }
} } catch (error) {
})(); console.error(error);
}
// Discord.js event listener for when the bot is ready })();
client.once('ready', () => {
console.log('Bot is ready!'); // Discord.js event listener for when the bot is ready
}); client.once('ready', () => {
console.log('Bot is ready!');
// Discord.js event listener for when a message is received });
client.on('messageCreate', async message => {
if (message.author.bot) return; // Discord.js event listener for when a message is received
client.on('messageCreate', async message => {
// Increment XP every 10 messages if (message.author.bot) return;
if (message.guild) {
const guildId = message.guild.id; // Increment XP every 10 messages
const xp = await db.get(`xp.${guildId}.${message.author.id}`) || 0; if (message.guild) {
await db.set(`xp.${guildId}.${message.author.id}`, xp + 1); const guildId = message.guild.id;
const xp = await db.get(`xp.${guildId}.${message.author.id}`) || 0;
// Check if user leveled up await db.set(`xp.${guildId}.${message.author.id}`, xp + 1);
const level = Math.floor(xp / 5) + 1;
const newLevel = Math.floor((xp + 1) / 5) + 1; // Check if user leveled up
if (newLevel > level) { const level = Math.floor(xp / 5) + 1;
message.channel.send(`${message.author.username} leveled up to level ${newLevel}!`); const newLevel = Math.floor((xp + 1) / 5) + 1;
} if (newLevel > level) {
} message.channel.send(`${message.author.username} leveled up to level ${newLevel}!`);
}); }
}
client.on('messageCreate', async message => { });
if (message.author.bot) { return; }
try { client.on('messageCreate', async message => {
const result = await perspective.analyze(message.content); if (message.author.bot) { return; }
console.log(`TOXICITY [0-1]: ${result.attributeScores.TOXICITY.summaryScore.value}`) try {
if (message.member.permissions.has("ADMINISTRATOR")) { return; } const result = await perspective.analyze(message.content);
if (result.attributeScores.TOXICITY.summaryScore.value > 0.93) { console.log(`TOXICITY [0-1]: ${result.attributeScores.TOXICITY.summaryScore.value}`)
// Take moderation action if (message.member.permissions.has("ADMINISTRATOR")) { return; }
message.delete(); if (result.attributeScores.TOXICITY.summaryScore.value > minimumToxicToDelete) {
message.channel.send(`${message.author}, your message has been removed for toxicity.`); // Take moderation action
} message.delete();
} catch {} message.channel.send(`${message.author}, your message has been removed for toxicity.`);
}) }
} catch {}
client.on('messageUpdate', async (oldMessage, newMessage) => { })
if (newMessage.author.bot) { return; }
console.log(`${oldMessage} ==> ${newMessage}`) client.on('messageUpdate', async (oldMessage, newMessage) => {
try { if (newMessage.author.bot) { return; }
const result = await perspective.analyze(newMessage.content); console.log(`${oldMessage} ==> ${newMessage}`)
console.log(`UPDATED TOXICITY [0-1]: ${result.attributeScores.TOXICITY.summaryScore.value}`) try {
if (newMessage.member.permissions.has("ADMINISTRATOR")) { return; } const result = await perspective.analyze(newMessage.content);
if (result.attributeScores.TOXICITY.summaryScore.value > 0.93) { console.log(`UPDATED TOXICITY [0-1]: ${result.attributeScores.TOXICITY.summaryScore.value}`)
// Take moderation action if (newMessage.member.permissions.has("ADMINISTRATOR")) { return; }
newMessage.delete(); if (result.attributeScores.TOXICITY.summaryScore.value > minimumToxicToDelete) {
newMessage.channel.send(`${newMessage.author}, your message has been removed for toxicity.`); // Take moderation action
} newMessage.delete();
} catch {} newMessage.channel.send(`${newMessage.author}, your message has been removed for toxicity.`);
}); }
} catch {}
// Discord.js event listener for when a slash command is used });
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return; // Discord.js event listener for when a slash command is used
client.on('interactionCreate', async interaction => {
const { commandName, options, guildId } = interaction; if (!interaction.isCommand()) return;
// Retrieve guild ID from interaction if available const { commandName, options, guildId } = interaction;
const interactionGuildId = guildId || interaction.guildId;
// Retrieve guild ID from interaction if available
if (!interactionGuildId) { const interactionGuildId = guildId || interaction.guildId;
console.error('Unable to retrieve guild ID.');
return; if (!interactionGuildId) {
} console.error('Unable to retrieve guild ID.');
return;
if (commandName === 'xp') { }
const guildId = interactionGuildId;
const user = options.getUser('user') || interaction.user; if (commandName === 'xp') {
const xp = await db.get(`xp.${guildId}.${user.id}`) || 0; const guildId = interactionGuildId;
console.log(xp) const user = options.getUser('user') || interaction.user;
await interaction.reply(`${user.username} has ${xp} XP.`); const xp = await db.get(`xp.${guildId}.${user.id}`) || 0;
} else if (commandName === 'addxp') { console.log(xp)
if (!interaction.member.permissions.has('ADMINISTRATOR')) { await interaction.reply(`${user.username} has ${xp} XP.`);
return interaction.reply('You do not have permission to use this command.'); } else if (commandName === 'addxp') {
} if (!interaction.member.permissions.has('ADMINISTRATOR')) {
return interaction.reply('You do not have permission to use this command.');
const guildId = interactionGuildId; }
const amount = options.getInteger('amount');
const user = options.getUser('user') || interaction.user; const guildId = interactionGuildId;
const currentXp = await db.get(`xp.${guildId}.${user.id}`) || 0; const amount = options.getInteger('amount');
await db.set(`xp.${guildId}.${user.id}`, currentXp + amount) const user = options.getUser('user') || interaction.user;
await interaction.reply(`${amount} XP added to ${user.username}.`); const currentXp = await db.get(`xp.${guildId}.${user.id}`) || 0;
} else if (commandName === 'removexp') { await db.set(`xp.${guildId}.${user.id}`, currentXp + amount)
if (!interaction.member.permissions.has('ADMINISTRATOR')) { await interaction.reply(`${amount} XP added to ${user.username}.`);
return interaction.reply('You do not have permission to use this command.'); } else if (commandName === 'removexp') {
} if (!interaction.member.permissions.has('ADMINISTRATOR')) {
return interaction.reply('You do not have permission to use this command.');
const guildId = interactionGuildId; }
const amount = options.getInteger('amount');
const user = options.getUser('user') || interaction.user; const guildId = interactionGuildId;
const currentXp = await db.get(`xp.${guildId}.${user.id}`) || 0; const amount = options.getInteger('amount');
await db.set(`xp.${guildId}.${user.id}`, Math.max(0, currentXp - amount)); const user = options.getUser('user') || interaction.user;
await interaction.reply(`${amount} XP removed from ${user.username}.`); const currentXp = await db.get(`xp.${guildId}.${user.id}`) || 0;
} await db.set(`xp.${guildId}.${user.id}`, Math.max(0, currentXp - amount));
}); await interaction.reply(`${amount} XP removed from ${user.username}.`);
}
// Start the Express.js server for the XP API });
app.get('/xp/:guildId/:userId', (req, res) => {
const { guildId, userId } = req.params; // Start the Express.js server for the XP API
const xp = db.get(`xp.${guildId}.${userId}`) || 0; app.get('/xp/:guildId/:userId', (req, res) => {
res.json({ guildId, userId, xp }); const { guildId, userId } = req.params;
}); const xp = db.get(`xp.${guildId}.${userId}`) || 0;
res.json({ guildId, userId, xp });
app.listen(PORT, () => { });
console.log(`XP API server is running on http://localhost:${PORT}`);
}); app.listen(PORT, () => {
console.log(`XP API server is running on http://localhost:${PORT}`);
// Login to Discord });
client.login(process.env.DISCORD_BOT_TOKEN);
// Login to Discord
client.login(process.env.DISCORD_BOT_TOKEN);