Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dockerize project #2

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Config files
config.json

# Node.js
npm-debug.log
yarn-debug.log
yarn-error.log
.npm
.env

# IDE/Editor specific
.vscode/
.idea/
*.swp
*.swo~

# OS specific
.DS_Store
Thumbs.db

# Logs
*.log
logs/

# Docker
.docker/
docker-compose.override.yml
7 changes: 0 additions & 7 deletions Bot/config.json

This file was deleted.

122 changes: 90 additions & 32 deletions Bot/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,53 @@
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const axios = require('axios');
const config = require('./config.json');
const fs = require('fs');
const path = require('path');

function validateConfig(config) {
const requiredFields = [
'token',
'guildID',
'channelID',
'clientID',
'updateTime',
'embedColor',
'urls',
'monitorGroups',
'uptimeKumaAPIKey'
];

for (const field of requiredFields) {
if (!(field in config)) {
throw new Error(`Missing required field: ${field}`);
}
}

return config;
}

function loadConfig() {
try {
const newConfig = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json'), 'utf8'));
return validateConfig(newConfig);
} catch (error) {
console.error('Error loading config:', error);
return null;
}
}

let config = loadConfig();

fs.watch(path.join(__dirname, '../config.json'), (eventType, filename) => {
if (eventType === 'change') {
console.log('Config file changed, reloading...');
const newConfig = loadConfig();
if (newConfig) {
config = newConfig;
console.log('Config reloaded successfully');
updateMessages().catch(console.error);
}
}
});

const client = new Client({
intents: [
Expand All @@ -10,25 +57,23 @@ const client = new Client({
]
});

let monitorMessages = {
Gaming: null,
Discord: null,
Web: null
};
let monitorMessages = Object.keys(config.monitorGroups).reduce((acc, groupName) => {
acc[groupName] = null;
return acc;
}, {});

client.once('ready', async () => {
console.log('Bot is online!');

const channel = await client.channels.fetch(config.channelID);
if (channel && channel.isTextBased()) {
await clearChannel(channel);
} else {
console.error(`Unable to find text channel with ID ${config.channelID}`);
}
// Call the function to update messages immediately
await updateMessages();
// Set interval to update messages every 30 seconds
setInterval(updateMessages, config.updatetime * 1000);
console.log('Sleeping for', config.updateTime, 'seconds');
setInterval(updateMessages, config.updateTime * 1000);
});

async function updateMessages() {
Expand All @@ -45,25 +90,30 @@ async function updateMessages() {
return;
}

const response = await axios.get('<YOUR_BACKEND_URL>');
const monitors = response.data;

const gamingMonitors = monitors.filter(monitor => [
'Lobby', 'Skyblock', 'Survival', 'Creative', 'KitPvP', 'Factions', 'Prison', 'Skywars'
].includes(monitor.monitor_name));

const discordMonitors = monitors.filter(monitor => [
'Discord bot', 'Status bot'
].includes(monitor.monitor_name));

const webMonitors = monitors.filter(monitor => [
'web1', 'web2', 'web3'
].includes(monitor.monitor_name));

await sendMonitorsMessage(channel, 'Gaming', gamingMonitors);
await sendMonitorsMessage(channel, 'Discord', discordMonitors);
await sendMonitorsMessage(channel, 'Web', webMonitors);

try {
console.log('Attempting to fetch from:', config.urls.backend);
const response = await axios.get(config.urls.backend);
console.log('Response received:', response.status);
const monitors = response.data;
if (!Array.isArray(monitors)) {
console.error('Monitors is not an array:', monitors);
return;
}
for (const [groupName, monitorNames] of Object.entries(config.monitorGroups)) {
const groupMonitors = monitors.filter(monitor =>
monitorNames.includes(monitor.monitor_name)
);
await sendMonitorsMessage(channel, groupName, groupMonitors);
}
} catch (error) {
console.error('Error details:', {
config: error.config,
url: config.urls.backend,
status: error.response?.status,
data: error.response?.data
});
throw error;
}
} catch (error) {
console.error('Error:', error);
}
Expand Down Expand Up @@ -93,10 +143,10 @@ async function sendMonitorsMessage(channel, category, monitors) {

let embed = new EmbedBuilder()
.setTitle(`${category} Monitor`)
.setColor('#0099ff')
.setColor(config.embedColor)
.setDescription(description)
.setFooter({ text: `Last updated: ${new Date().toLocaleString()}` })
.setURL('<YOUR_UPTIMEKUMA_URL>');
.setURL(config.urls.uptimeKumaDashboard);

try {

Expand All @@ -116,7 +166,14 @@ async function sendMonitorsMessage(channel, category, monitors) {
console.log(`${new Date().toLocaleString()} | Sent ${category} monitors message`);
}
} catch (error) {
console.error(`Failed to send/update ${category} monitors message:`, error);
try{
const newMessage = await channel.send({ embeds: [embed] });
monitorMessages[category] = newMessage.id;
console.log(`${new Date().toLocaleString()} | Sent ${category} monitors message`);
}
catch(error){
console.error(`Failed to send/update ${category} monitors message:`, error);
}
}
}

Expand All @@ -129,6 +186,7 @@ async function clearChannel(channel) {
console.error('Error clearing channel:', error);
}
}

client.login(config.token).catch(error => {
console.error('Error logging in:', error);
});
116 changes: 86 additions & 30 deletions Bot/index_with_comments.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,57 @@
// Import required classes from discord.js and axios for making HTTP requests
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const axios = require('axios');
const config = require('./config.json');
const fs = require('fs');

// Validate the config object
function validateConfig(config) {
const requiredFields = [
'token',
'guildID',
'channelID',
'clientID',
'updateTime',
'embedColor',
'urls',
'monitorGroups',
'uptimeKumaAPIKey'
];

for (const field of requiredFields) {
if (!(field in config)) {
throw new Error(`Missing required field: ${field}`);
}
}

return config;
}

// Function to load config
function loadConfig() {
try {
const newConfig = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json'), 'utf8'));
return validateConfig(newConfig);
} catch (error) {
console.error('Error loading config:', error);
return null;
}
}

let config = loadConfig();

// Watch for config file changes
fs.watch(path.join(__dirname, '../config.json'), (eventType, filename) => {
if (eventType === 'change') {
console.log('Config file changed, reloading...');
const newConfig = loadConfig();
if (newConfig) {
config = newConfig;
console.log('Config reloaded successfully');
// Optionally trigger an immediate update
updateMessages().catch(console.error);
}
}
});

// Create a new Discord client instance with specified intents
const client = new Client({
Expand All @@ -12,12 +62,11 @@ const client = new Client({
]
});

// Object to store the IDs of the monitor messages
let monitorMessages = {
Gaming: null,
Discord: null,
Web: null
};
// Initialize monitorMessages with all groups from config
let monitorMessages = Object.keys(config.monitorGroups).reduce((acc, groupName) => {
acc[groupName] = null;
return acc;
}, {});

// Event listener for when the bot is ready
client.once('ready', async () => {
Expand All @@ -36,6 +85,7 @@ client.once('ready', async () => {
// Call the function to update messages immediately
await updateMessages();
// Set interval to update messages every configured seconds
console.log('Sleeping for', config.updateTime, 'seconds');
setInterval(updateMessages, config.updatetime * 1000);
});

Expand All @@ -56,27 +106,33 @@ async function updateMessages() {
return;
}

// Make a GET request to the backend to fetch monitor data
const response = await axios.get('<YOUR_BACKEND_URL>');
const monitors = response.data;

// Filter monitors into categories
const gamingMonitors = monitors.filter(monitor => [
'Lobby', 'Skyblock', 'Survival', 'Creative', 'KitPvP', 'Factions', 'Prison', 'Skywars'
].includes(monitor.monitor_name));

const discordMonitors = monitors.filter(monitor => [
'Discord bot', 'Status bot'
].includes(monitor.monitor_name));

const webMonitors = monitors.filter(monitor => [
'web1', 'web2', 'web3'
].includes(monitor.monitor_name));

// Send or update monitor messages in the channel
await sendMonitorsMessage(channel, 'Gaming', gamingMonitors);
await sendMonitorsMessage(channel, 'Discord', discordMonitors);
await sendMonitorsMessage(channel, 'Web', webMonitors);
try {
// Make a GET request to the backend to fetch monitor data
console.log('Attempting to fetch from:', config.urls.backend);
const response = await axios.get(config.urls.backend);
console.log('Response received:', response.status);
const monitors = response.data;

// Process each monitor group from config
if (!Array.isArray(monitors)) {
console.error('Monitors is not an array:', monitors);
return;
}
for (const [groupName, monitorNames] of Object.entries(config.monitorGroups)) {
const groupMonitors = monitors.filter(monitor =>
monitorNames.includes(monitor.monitor_name)
);
await sendMonitorsMessage(channel, groupName, groupMonitors);
}
} catch (error) {
console.error('Error details:', {
config: error.config,
url: config.urls.backend,
status: error.response?.status,
data: error.response?.data
});
throw error;
}

} catch (error) {
console.error('Error:', error);
Expand Down Expand Up @@ -110,10 +166,10 @@ async function sendMonitorsMessage(channel, category, monitors) {
// Create the embed message
let embed = new EmbedBuilder()
.setTitle(`${category} Monitor`)
.setColor('#0099ff')
.setColor(config.embedColor)
.setDescription(description)
.setFooter({ text: `Last updated: ${new Date().toLocaleString()}` })
.setURL('<YOUR_UPTIMEKUMA_URL>');
.setURL(config.urls.backend);

try {
// Check if there is an existing message to update or send a new one
Expand Down
Loading