Skip to content

Commit

Permalink
implemented component based system
Browse files Browse the repository at this point in the history
Added modular components for the bot, with component scoped enabling
  • Loading branch information
3ddelano committed Jun 12, 2021
1 parent 0dcdf9a commit f95400f
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 23 deletions.
29 changes: 29 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module.exports = {
"env": {
"node": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-console": "off"
}
};
34 changes: 29 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ A self hosted Discord bot to display your pc stats.
- ### View or share your pc stats to other devices
- ### Easy to host
- ### One of a kind
- ### Modular design


# Installation
Expand All @@ -35,11 +36,34 @@ For the first run, click on the invite link in the terminal and add the bot to w
## config.json
This is the configuration file used by the program.

| Key | Type | Value |
| -------- | ------- | --------------------------------------------------------------- |
| token | string | The token of the bot from Discord Developer Page |
| clientID | string | The client ID of the bot from Discord Developer Page |
| interval | integer | The time in seconds to wait before updating the stats each time |
| Key | Type | Value |
| ---------- | ------- | ---------------------------------------------------------------- |
| token | string | The token of the bot from Discord Developer Page |
| clientID | string | The client ID of the bot from Discord Developer Page |
| interval | integer | The time in seconds to wait before updating the stats each time |
| components | object | An object with key as component name and value as enabled status |

## Available Components

| Name | Description |
| ----------- | -------------------------------------------- |
| battery | Shows battery percentage and charging status |
| memoryUsage | Shows used memory and total memory |
| cpuUsage | Shows CPU usage percentage |

## Example config.json
```json
{
"token": "your bot token",
"clientID": "your bot client id",
"interval": 30,
"components": {
"battery": true,
"cpuUsage": true,
"memoryUsage": true
}
}
```

## Bugs / Suggestions
Report any bugs / glitches, or make a suggestion using the github issues section or join the support server [Join Server](https://discord.gg/FZY9TqW).
Expand Down
9 changes: 9 additions & 0 deletions components/battery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const info = require("systeminformation");
exports.update = async () => {
let batteryData = await info.battery();
let payload = ':battery: **Battery:**: No battery found.'
if (batteryData.hasBattery) {
payload = `:battery: **Battery:** ${batteryData.percent}% ${batteryData.isCharging ? '(Charging)' : '(Not Charging)'}`;
}
return payload;
}
7 changes: 7 additions & 0 deletions components/cpuUsage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const info = require("systeminformation");
exports.update = async () => {
const currentLoad = (await info.currentLoad().then(data => data.currentLoad)).toFixed(2);

const payload = `:gear: **CPU Usage:** ${currentLoad}%`;
return payload;
}
11 changes: 11 additions & 0 deletions components/memoryUsage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const os = require("os");
const conversionFactor = 9.3132 * 1e-10;

exports.update = async () => {

let totalMem = (os.totalmem() * conversionFactor).toFixed(2);
let usedMem = (totalMem - (os.freemem() * conversionFactor)).toFixed(2);

let payload = `:tools: **Memory Usage:** ${usedMem} GB / ${totalMem} GB`;
return payload;
}
9 changes: 7 additions & 2 deletions config_example.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
"token": "token from bot section of discord developer page",
"clientID": "client id from oauth2 section of discord developer page"
"interval": 30
"clientID": "client id from oauth2 section of discord developer page",
"interval": 30,
"components": {
"battery": true,
"cpuUsage": true,
"memoryUsage": true
}
}
38 changes: 22 additions & 16 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const info = require("systeminformation");
const os = require("os");
const fs = require("fs");
const moment = require("moment");

Expand All @@ -9,30 +7,36 @@ const client = new Discord.Client();

let MESSAGE;

const conversionFactor = 9.3132 * 1e-10;
// load enabled components
const component_names = fs.readdirSync('./components/');
const components = new Map();
component_names.forEach(file_name => {
if (!file_name.endsWith('.js')) return;

const file = require(`./components/${file_name}`);

const component_name = file_name.split('.js').join('');

if (config.components[component_name])
components.set(component_name, file);
});

async function update() {
if (!MESSAGE) return console.log('Unable to fetch channel or message.');
let payload = '';
let currentLoad = (await info.currentLoad().then(data => data.currentLoad)).toFixed(2);
let batteryData = await info.battery();
if (batteryData.hasBattery) {
payload += `:battery: **Battery:** ${batteryData.percent}% ${batteryData.isCharging ? '(Charging)' : '(Not Charging)'}\n`;
}

let totalMem = (os.totalmem() * conversionFactor).toFixed(2);
let usedMem = (totalMem - (os.freemem() * conversionFactor)).toFixed(2);
let payload = '';

payload += `:gear: **CPU Usage:** ${currentLoad}%\n`;
payload += `:tools: **Memory Usage:** ${usedMem} GB / ${totalMem} GB\n`;
const promises = [];
components.forEach(component => promises.push(component.update()));

const values = await Promise.all(promises);
payload = values.join('\n');

payload += `\n:timer: **Last Updated:** ${moment().format("hh:mm:ss A DD-MM-YYYY")} `;
MESSAGE.edit(payload);
setTimeout(update, config.interval * 1000);
}


client.on('ready', async () => {
client.user.setPresence({ activity: { name: 'Watching s.help' }, status: 'active' })
console.log(`Logged in as ${client.user.tag} !`);
Expand All @@ -41,6 +45,8 @@ client.on('ready', async () => {
let channel = await client.channels.fetch(config.channelID);
MESSAGE = await channel.messages.fetch(config.messageID);
update();
} else {
console.log("Waiting for s.start");
}
});

Expand All @@ -49,7 +55,7 @@ client.on('message', async (message) => {
if (message.content === 's.start') {
if (config.messageID) return message.reply("stats has already started.");

let msg = await message.channel.send("Starting...");
let msg = await message.channel.send("Updatig stats...");
config.messageID = msg.id;
config.channelID = msg.channel.id;
MESSAGE = msg;
Expand All @@ -58,7 +64,7 @@ client.on('message', async (message) => {
}
if (message.content === 's.ping') {
const msg = await message.channel.send('Ping?')
msg.edit(`Pong! Latency is ${Math.round(msg.createdTimestamp - message.createdTimestamp)} ms.API Latency is ${Math.round(client.ws.ping)} ms`)
msg.edit(`Pong! Latency is ${Math.round(msg.createdTimestamp - message.createdTimestamp)} ms. API Latency is ${Math.round(client.ws.ping)} ms`)
}
if (message.content === 's.help') {
const help = [
Expand Down

0 comments on commit f95400f

Please sign in to comment.