Skip to content

Commit

Permalink
Merge branch 'master' into christmas-holiday-cheer
Browse files Browse the repository at this point in the history
  • Loading branch information
XeIris committed Nov 6, 2024
2 parents b8da589 + ab18391 commit 55ca933
Show file tree
Hide file tree
Showing 50 changed files with 632 additions and 328 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.env
node_modules/*
*/temp/*
database.db
*.db
*.zip
*.csv
*.csv
*.txt
15 changes: 8 additions & 7 deletions classes/birthdayScheduler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const cron = require('node-cron');
const { EmbedBuilder } = require('discord.js');
const { log, logError } = require('../utils/log');
require('dotenv').config(); // Load the environment variables

class BirthdayScheduler {
Expand All @@ -15,18 +16,18 @@ class BirthdayScheduler {
const utcDay = now.getUTCDate().toString().padStart(2, '0');
const utcHour = now.getUTCHours().toString().padStart(2, '0');
const todayHour = `${utcMonth}-${utcDay}T${utcHour}`; // MM-DDTHH format
console.log(`Checking for birthdays on ${todayHour} (UTC)`);
log(`Checking for birthdays on ${todayHour} (UTC)`);

try {
const birthdays = await this.client.db.getUsersWithBirthday(todayHour);
console.log('Users with birthdays this hour:', birthdays);
log('Users with birthdays this hour:', birthdays);

if (birthdays.length > 0) {
const channelIds = process.env.BIRTHDAY_CHANNELS.split(','); // Get all channel IDs from .env
for (const channelId of channelIds) {
const channel = this.client.channels.cache.get(channelId.trim()); // Trim spaces and get the channel
if (!channel) {
console.error(`Channel ID ${channelId} not found or invalid.`);
logError(`Channel ID ${channelId} not found or invalid.`);
continue;
}

Expand All @@ -36,16 +37,16 @@ class BirthdayScheduler {
.setDescription(`Today is <@${user.id}>'s birthday! Let's all wish them a great day! 🥳`)
.setColor(0x00FF00);

console.log(`Sending birthday message for ${user.id} to channel ${channelId}`);
log(`Sending birthday message for ${user.id} to channel ${channelId}`);
await channel.send({ embeds: [birthdayEmbed] });
}
}
} else {
console.log('No birthdays this hour.');
log('No birthdays this hour.');
}
console.log('Birthday check complete.');
log('Birthday check complete.');
} catch (error) {
console.error('Error during birthday check:', error);
logError('Error during birthday check:', error);
}
});
}
Expand Down
3 changes: 2 additions & 1 deletion classes/bitcoin.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const axios = require('axios');
const { logError } = require('../utils/log');

class Bitcoin{
constructor(){
Expand All @@ -10,7 +11,7 @@ class Bitcoin{
const response = await axios.get(this.bitcoinPriceUrl);
return response.data;
}catch(err){
console.error('Error fetching Bitcoin price:', err);
logError('Error fetching Bitcoin price:', err);
return null;
}
}
Expand Down
278 changes: 135 additions & 143 deletions classes/database.js

Large diffs are not rendered by default.

77 changes: 47 additions & 30 deletions classes/silverwolf.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const fs = require("fs");
const path = require("path");
const BirthdayScheduler = require('./birthdayScheduler');
const Canvas = require('canvas');
const { log } = require('../utils/log');
// const CharacterAI = require('node_characterai')
require('dotenv').config();

Expand All @@ -26,47 +27,62 @@ class Silverwolf extends Client {
// try{
// this.loadSilverwolfAI();
// }catch(error){
// console.log("Error loading Silverwolf AI: ", error)
// log("Error loading Silverwolf AI: ", error)
// }
}

async init(){
log("--------------------\nInitializing Silverwolf...\n--------------------");
await this.loadCommands();
await this.loadKeywords();
await this.loadListeners();

this.birthdayScheduler.start();

console.log("Silverwolf initialized.");
log(`Silverwolf initialized.
----------------------------------------------
____ _ _ _ __
/ ___|(_) |_ _____ _ ____ _____ | |/ _|
\\___ \\| | \\ \\ / / _ \\ '__\\ \\ /\\ / / _ \\| | |_
___) | | |\\ V / __/ | \\ V V / (_) | | _|
|____/|_|_| \\_/ \\___|_| \\_/\\_/ \\___/|_|_|
----------------------------------------------
Product of Silverwolf™ Corp.
All wrongs reserved.
----------------------------------------------`);
}

async loadCommands(){
log("--------------------\nLoading commands...\n--------------------");
const commandDir = path.join(__dirname, "../commands");
const commandFiles = fs.readdirSync(commandDir).filter(file => file.endsWith(".js"));

for (const file of commandFiles) {
const CommandClass = require(path.join(commandDir, file));
console.log(CommandClass);
// log(CommandClass);
const command = new CommandClass(this);
this.commands.set(command.name, command);
console.log(`Command ${command.name} loaded.`);
log(`Command ${command.name} loaded.`);
}
console.log("Commands loaded.");
log("Commands loaded.");
}

async loadKeywords(){
log("--------------------\nLoading keywords...\n--------------------");
const keywordsFile = path.join(__dirname, "../data/keywords.json");
const keywords = fs.readFileSync(keywordsFile, "utf8");
this.keywords = JSON.parse(keywords);
for (const [keyword, reply] of Object.entries(this.keywords)){
console.log(`Keyword: ${keyword} -> ${reply}`);
// log(`Keyword: ${keyword} -> ${reply}`);
log(`Keyword ${keyword} loaded.`);
}
console.log("Keywords loaded.");
log("Keywords loaded.");
}

async loadListeners(){
log("--------------------\nLoading listeners...\n--------------------");
this.on("ready", () => {
console.log("uwu ready");
log("Client ready.");
});
this.on("messageCreate", (message) => {
this.processMessage(message);
Expand All @@ -80,7 +96,7 @@ class Silverwolf extends Client {
this.on("messageUpdate", (oldMessage, newMessage) => {
this.processEdit(oldMessage, newMessage);
});
console.log("Listeners loaded.");
log("Listeners loaded.");
}

processInteraction(interaction){
Expand All @@ -91,22 +107,22 @@ class Silverwolf extends Client {
}
const command = this.commands.get(interaction.commandName);
if(!command) return;
console.log(`Command ${command.name} executed by ${interaction.user.tag}`);
log(`Command ${command.name} executed by ${interaction.user.username} (${interaction.user.id}) in ${interaction.channel.name} (${interaction.channel.id}) in ${interaction.guild.name} (${interaction.guild.id})`);
try{
command.execute(interaction);
}catch(error){
console.error(error);
logError(error);
}
}
}

processMessage(message) {
if (message.author.bot) return;
if (!message.guild) return;
console.log(`Message received from ${message.author.username}: ${message.content}`);
log(`Message received from ${message.author.username} (${message.author.id}) in ${message.channel.name} (${message.channel.id}) in ${message.guild.name} (${message.guild.id}): ${message.content}`);

if (Math.random() < 0.01 && !(message.channel.name == "super-serious-secret-vent-rant-chat")) {
console.log("Summoning a pokemon...");
log("Summoning a pokemon...");
this.summonPokemon(message);
}

Expand Down Expand Up @@ -160,7 +176,7 @@ class Silverwolf extends Client {
// After generating the quote or image...
await sentMessage.edit({ content: null, files: [content.files[0]] });
} else {
console.error('No file or content to send in the reply.');
logError('No file or content to send in the reply.');
}
}
};
Expand All @@ -181,12 +197,12 @@ class Silverwolf extends Client {


processDelete(message){
console.log(`Message deleted by ${message.author.username}: ${message.content}`);
log(`Message deleted by ${message.author.username} (${message.author.id}) in ${message.channel.name} (${message.channel.id}) in ${message.guild.name} (${message.guild.id}): ${message.content}`);
this.deletedMessages.unshift(message);
}

processEdit(oldMessage, newMessage){
console.log(`Message edited by ${oldMessage.author.username}: ${oldMessage.content} -> ${newMessage.content}`);
log(`Message edited by ${oldMessage.author.username} (${oldMessage.author.id}) in ${oldMessage.channel.name} (${oldMessage.channel.id}) in ${oldMessage.guild.name} (${oldMessage.guild.id}): ${oldMessage.content} -> ${newMessage.content}`);
this.editedMessages.unshift({old: oldMessage, new: newMessage});
}

Expand All @@ -199,7 +215,7 @@ class Silverwolf extends Client {
try {
// Retrieve blacklisted commands for the guild
const blacklistedCommandsData = await this.db.getBlacklistedCommands(guildId);
console.log(`Blacklisted commands for guild ${guildId}:`, blacklistedCommandsData);
log(`Blacklisted commands for guild ${guildId}:`, blacklistedCommandsData);

// Extract just the command names from the data
const blacklistedCommands = blacklistedCommandsData.map(item => item.command_name);
Expand All @@ -213,18 +229,18 @@ class Silverwolf extends Client {

// If there are no blacklisted commands, register all commands
if (blacklistedCommands.length === 0) {
console.log(`No blacklisted commands for guild ${guildId}. Registering all commands.`);
log(`No blacklisted commands for guild ${guildId}. Registering all commands.`);
const response = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commandsArray },
);

console.log(`Successfully registered commands for guild ${guildId}:`, response);
log(`Successfully registered commands for guild ${guildId}:`, response);
} else {
// Remove blacklisted commands from the array
const filteredCommandsArray = commandsArray.filter(command => {
if (blacklistedCommands.includes(command.name)) {
console.log(`Excluding blacklisted command "${command.name}" for guild: ${guildId}`);
log(`Excluding blacklisted command "${command.name}" for guild: ${guildId}`);
return false; // Exclude the command if blacklisted
} else if (!this.commands.has(command.name)) {
console.warn(`Warning: Command "${command.name}" not found in the registered commands for guild: ${guildId}. It may have been misspelled.`);
Expand All @@ -233,21 +249,22 @@ class Silverwolf extends Client {
});

// Register the filtered commands for this guild
console.log(`Registering commands for guild: ${guildId}`);
log(`Registering commands for guild: ${guildId}`);
const response = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: filteredCommandsArray },
);

console.log(`Successfully registered commands for guild ${guildId}:`, response);
log(`Successfully registered commands for guild ${guildId}:`, response);
}
} catch (error) {
console.error(`Error registering commands for guild ${guildId}:`, error);
logError(`Error registering commands for guild ${guildId}:`, error);
}
}

console.log("All commands registered successfully.");
console.log("Successfully finished startup.");
log("All commands registered successfully.");
log("Successfully finished startup.");
log("=======================================================")
}


Expand All @@ -272,7 +289,7 @@ class Silverwolf extends Client {
}else{
randomInterval = (Math.floor(Math.random() * 3) + 1) * 60 * 60 * 1000; // Random interval between 1 and 3 hours
}
console.log(`Setting status to "${randomGame}". Next change in ${randomInterval / 1000 / 60} minutes.`);
log(`Setting status to "${randomGame}". Next change in ${randomInterval / 1000 / 60} minutes.`);

setTimeout(() => this.setRandomGame(), randomInterval); // Schedule the next game change
}
Expand All @@ -283,9 +300,9 @@ class Silverwolf extends Client {
const data = fs.readFileSync(filePath, "utf8");
const json = JSON.parse(data);
this.games = json.games || [];
console.log("Games loaded from status.json:", this.games);
log("Games loaded from status.json:", this.games);
} catch (error) {
console.error("Error loading games from status.json:", error);
logError("Error loading games from status.json:", error);
}
}

Expand All @@ -298,12 +315,12 @@ class Silverwolf extends Client {

// this.chat = await silverwolf.createOrContinueChat(characterId)

// console.log("Silverwolf AI loaded.")
// log("Silverwolf AI loaded.")
// }

async login(){
await super.login(this.token);
console.log(`Logged in as ${this.user.tag}`);
log(`Logged in as ${this.user.tag}`);
this.setRandomGame(); // Start cycling through games after logging in
}

Expand Down
5 changes: 4 additions & 1 deletion commands/BitcoinPriceCommand.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Discord = require('discord.js');
const { Command } = require('./classes/command.js'); // Adjust the path if necessary
const { Bitcoin } = require('../classes/bitcoin.js');
const { log, logError } = require('../utils/log');

class BitcoinPriceCommand extends Command {
constructor(client) {
Expand Down Expand Up @@ -31,13 +32,15 @@ class BitcoinPriceCommand extends Command {
});
}

log(`Current Bitcoin price: ${data.bpi.USD.rate} ${data.bpi.USD.symbol}`);

// Add all fields to the embed using addFields
embed.addFields(fields);

// Send the embed message
await interaction.editReply({ embeds: [embed] });
} catch (error) {
console.error('Error fetching Bitcoin price:', error);
logError('Error fetching Bitcoin price:', error);
if (!interaction.replied) {
await interaction.editReply({ content: 'Failed to retrieve Bitcoin price. Please try again later.', ephemeral: true });
}
Expand Down
3 changes: 2 additions & 1 deletion commands/GameUidDelete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { Command } = require('./classes/command.js');
const Discord = require('discord.js');
const { logError } = require('../utils/log');

class DeleteGameUID extends Command {
constructor(client) {
Expand Down Expand Up @@ -45,7 +46,7 @@ class DeleteGameUID extends Command {
]
});
} catch (err) {
console.error('Failed to delete game UID:', err);
logError('Failed to delete game UID:', err);

// Reply with an error message
await interaction.editReply({
Expand Down
3 changes: 2 additions & 1 deletion commands/GoogleAi.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { GoogleGenerativeAI } = require("@google/generative-ai");
const { Command } = require('./classes/command.js');
const { EmbedBuilder } = require('discord.js');
require('dotenv').config();
const { logError } = require('../utils/log');

const genAI = new GoogleGenerativeAI(process.env.GEMINI_TOKEN);

Expand Down Expand Up @@ -40,7 +41,7 @@ class AskGeminiCommand extends Command {
// Edit the message with the actual response
await interaction.editReply({ content: null, embeds: [embed] });
} catch (error) {
console.error('Error generating text:', error);
logError('Error generating text:', error);
await interaction.editReply({ content: 'Failed to retrieve response from Gemini AI. Please try again later.', ephemeral: true });
}
}
Expand Down
3 changes: 2 additions & 1 deletion commands/Joke.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const axios = require('axios');
const { Command } = require('./classes/command.js');
const { logError } = require('../utils/log');

class RandomJokeCommand extends Command {
constructor(client) {
Expand All @@ -22,7 +23,7 @@ class RandomJokeCommand extends Command {
// Send the punchline message after the delay
await interaction.followUp({ content: data.punchline });
} catch (error) {
console.error('Failed to retrieve joke:', error);
logError('Failed to retrieve joke:', error);
await interaction.editReply({ content: 'Failed to retrieve joke. Please try again later.', ephemeral: true });
}
}
Expand Down
Loading

0 comments on commit 55ca933

Please sign in to comment.