Get Express Package CPU, RAM and Disk to display for my Discord Bot

I’m trying to make a bot info command which will display the project’s cpu ram and disk space. How could I get this information?

1 Like

Hi @Fyrlex!

You can read these files:

/sys/fs/cgroup/memory/memory.soft_limit_in_bytes
/sys/fs/cgroup/memory/memory.stat
/sys/fs/cgroup/cpu/cpu.cfs_quota_us
/sys/fs/cgroup/cpu/cpu.cfs_period_us
/sys/fs/cgroup/cpu/cpuacct.usage

For the values you see in the Status pane, memory usage is the total_rss line from/sys/fs/cgroup/memory/memory.stat minus Node’s process.memoryUsage().rss. Disk space comes from the check() method from the NPM package diskusage.

The percentages we display in the status bar are calculations over sliding averages of historical data, and we tweak these a little periodically to provide better info. You’re unlikely to be able to achieve an exact match for those values at any given point.

Hope this helps!

4 Likes

RAM Usage: process.memoryUsage().heapUsed / 1024 / 1024;

You can get most of the things from memoryUsage() method, it returns:

{
  rss: 1000,
  heapTotal: 1000,
  heapUsed: 1000,
  external: 1000
}

Note that that only reports on the current process and heap usage, so it’s only a portion of the full memory usage within the project.

2 Likes

What about for disk and cpu usage?

Is there something else you’re looking for that wasn’t in my initial reply?

I didn’t completely understand what you had written. I was looking for something like what @chroventer had posted.

What I do need is the maximum CPU (for max) and was wondering what the equation would be for it. Bolt stated above how to get the ram but it’s different for the CPU.

Currently I have this:

let cpu = Math.round(process.cpuUsage().system)
let cpupercent = Math.round((cpu * max) / 1000) / 10;

let ram = Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 10) / 10;
let rampercent = Math.round((ram / 512) * 1000) / 10;

Here’s a function to get memory usage fairly accurately:

function getMemoryUsage() {
  let total_rss = require('fs').readFileSync("/sys/fs/cgroup/memory/memory.stat", "utf8").split("\n").filter(l => l.startsWith("total_rss"))[0].split(" ")[1]; 
  return Math.round( Number(total_rss) / 1e6 ) - 60;
}

Explained here.

Sorry this is months later. Where exactly would I have that in my command? I have total_rss outside of it as a variable in a command and it says undefined.

  let total_rss = require('fs').readFileSync("/sys/fs/cgroup/memory/memory.stat", "utf8").split("\n").filter(l => l.startsWith("total_rss"))[0].split(" ")[1];
  let rampercent = Math.round((total_rss / 512) * 1000) / 10; 
  return Math.round( Number(total_rss) / 1e6 ) - 60;
}
  
  let disk = "N/A"
  
  let botname = bot.user.username;
  let botinfoembed = new Discord.RichEmbed()
  
  .setColor("#9a00ff")
  .setAuthor(`${botname} - Statistics`, bot.user.displayAvatarURL)
  .addField("CPU:", cpu + " - " + cpupercent + "%", true)
  .addField("RAM:", total_rss + "/512MB - " + rampercent + "%", true)```

I think we’d need to see a little more context here to know for sure what’s going on. If you’re saying that you’re trying to use total_rss as a value elsewhere in your code but it’s returning undefined then the } character on the 4th line of your code snippet leads me to believe perhaps you’re defining total_rss in a block and it’s not defined outside that block.

let total_rss;
let rampercent;
function getMemoryUsage() {
  total_rss += require('fs').readFileSync("/sys/fs/cgroup/memory/memory.stat", "utf8").split("\n").filter(l => l.startsWith("total_rss"))[0].split(" ")[1];
  rampercent += Math.round((total_rss / 512) * 1000) / 10; 
  return Math.round( Number(total_rss) / 1e6 ) - 60;

}

let botname = bot.user.username;
let botinfoembed = new Discord.RichEmbed()

    .setColor("#9a00ff")
    .setAuthor(`${botname} - Statistics`, bot.user.displayAvatarURL)
    .addField("RAM:", total_rss + "/512MB - " + rampercent + "%", true)
    .addField("Open Source:", "__https://github.com/Fyrlex/Magic8__")
    .setFooter("Developed by Fyrlex#2740 on Tuesday, 8/28/2018 by Fyrlex#2740")
    .setTimestamp()

message.channel.send(botinfoembed);

This is still returning undefined, should the botinfoembed be in the function? <didn’t work

From that snippet it looks like you’re not calling getMemoryUsage() anywhere, so the value for rampercent and total_rss are both what they were initialized to. Since you’re not initializing them at declaration they’re undefined at that point.

I think you need to call getMemoryUsage() before you set up botinfoembed.

How do I call getMemoryUsage()? Does there need to be more than function getMemoryUsage()?

let memory = getMemoryUsage()
botinfoembed
.addField(“RAM:”, memory + "/512MB - " + Math.round((memory / 512 )) * 100) + “%”, true)

Having the same problem here. I don’t understand much from the above.

returns NaN, what to do?

let memory = getMemoryUsage();

let string = `Here is my memory: ${memory}/512 MB (${Math.round((memory * 100)/ 512 )}%)`


function getMemoryUsage() {
  let total_rss = require('fs').readFileSync("/sys/fs/cgroup/memory/memory.stat", "utf8").split("\n").filter(l => l.startsWith("total_rss"))[0].split(" ")[1]; 
  return Math.round( Number(total_rss) / 1e6 ) - 60;
}
1 Like

thank you so much
works

I got a great code for that kind of command. It has more than CPU, RAM, and Disk viewing.

`
const notSupported = “The operating system used to host this bot is not supported for this command.”
const full = ‘█’
const empty = ‘░’
const precision = 20

  const freeRAM = os.freemem()
  const usedRAM = os.totalmem() - freeRAM;
  
  const diagramMaker = (used, free) => {
    const total = used + free;
    used = Math.round((used / total) * precision)
    free = Math.round((free / total) * precision)
    return full.repeat(used) + empty.repeat(free)
  }
  
  let cpuUsage;
  
  const p1 = osu.cpu.usage().then(cpuPercentage => {
    cpuUsage = cpuPercentage;
  })
  
  let processes;
  
  const p2 = osu.proc.totalProcesses().then(process => {
    processes = process;
  })
  
  let driveUsed, driveFree;
  
  const p3 = osu.drive.info().then(i => {
    driveUsed = i.usedPercentage;
    driveFree = i.freePercentage;
  }).catch(() => {
    driveUsed = false;
  })
  
  let networkUsage, networkUsageIn, networkUsageOut;
  
  const p4 = osu.netstat.inOut().then(i => {
    networkUsage = i.total;
    networkUsageIn = networkUsage.inputMb;
    networkUsageOut = networkUsage.outputMb;
  }).catch(() => {
    networkUsage = false;
  })
  
  await Promise.all([p1, p2, p3, p4]);
  
  const embed = new Discord.MessageEmbed()
    .setColor('#800080')
    .setDescription('Here is the bot stats!')
    .setAuthor('Hexx#3560', 'https://cdn.discordapp.com/avatars/754809998789443605/3f4f8e73962c81e9b992830b464ffe86.png?size=256')
    .addField(`Main Package Version:`, `Discord.js Version: 12.2.0\nDiscord.js-Commando Version: 0.10.0\nNode.js Version: 12.x`)
    .addField(`Used:`,(`RAM: ${diagramMaker(usedRAM, freeRAM)} [${Math.round(100 * usedRAM / (usedRAM + freeRAM))}%]\n`+
    `CPU: ${diagramMaker(cpuUsage, 100-cpuUsage)} [${Math.round(cpuUsage)}%]\n`+
    `HEXX PROCESS: ${(process.memoryUsage().heapUsed / 1000000).toFixed(2)}MB\n`+
    `STORAGE: ${driveUsed ? `${diagramMaker(driveUsed, driveFree)} [${Math.round(driveUsed)}%]` : notSupported}\n`+
    `PROCESSES: ${processes != 'not supported'? processes : notSupported}`).trim())
    .addField(`Machine Specs:`,`CPU Count: ${osu.cpu.count()}\nCPU Model: ${os.cpus()[0].model}\nCPU Speed: ${os.cpus()[0].speed}MHz
${osu.os.platform() != "win32" ? `Storage: ${diagramMaker(driveUsed,driveFree)} [${driveUsed}%]`: ""}`)
    .addField(`System Specs:`,`System Type: ${osu.os.type()}\nSystem Architecture: ${osu.os.arch()}\nSystem Platform: ${osu.os.platform()}`)
    .addField(`Network Stats:`,`${networkUsage ? `Input Speed: ${networkUsageIn}\nOutput Speed: ${networkUsageOut}` : notSupported}`)
    .setTimestamp()
    .setFooter('Hexx#3560', 'https://cdn.discordapp.com/avatars/754809998789443605/3f4f8e73962c81e9b992830b464ffe86.png?size=256');
    
  message.channel.send(embed);`

I have a code that shows more than CPU, RAM and Disk usage. You can edit it to your likings.

      const notSupported = "The operating system used to host this bot is not supported for this command."
      const full = '█'
      const empty = '░'
      const precision = 20
      
      const freeRAM = os.freemem()
      const usedRAM = os.totalmem() - freeRAM;
      
      const diagramMaker = (used, free) => {
        const total = used + free;
        used = Math.round((used / total) * precision)
        free = Math.round((free / total) * precision)
        return full.repeat(used) + empty.repeat(free)
      }
      
      let cpuUsage;
      
      const p1 = osu.cpu.usage().then(cpuPercentage => {
        cpuUsage = cpuPercentage;
      })
      
      let processes;
      
      const p2 = osu.proc.totalProcesses().then(process => {
        processes = process;
      })
      
      let driveUsed, driveFree;
      
      const p3 = osu.drive.info().then(i => {
        driveUsed = i.usedPercentage;
        driveFree = i.freePercentage;
      }).catch(() => {
        driveUsed = false;
      })
      
      let networkUsage, networkUsageIn, networkUsageOut;
      
      const p4 = osu.netstat.inOut().then(i => {
        networkUsage = i.total;
        networkUsageIn = networkUsage.inputMb;
        networkUsageOut = networkUsage.outputMb;
      }).catch(() => {
        networkUsage = false;
      })
      
      await Promise.all([p1, p2, p3, p4]);
      
      const embed = new Discord.MessageEmbed()
        .setColor('#800080')
        .setDescription('Here is the bot stats!')
        .setAuthor('Hexx#3560', 'https://cdn.discordapp.com/avatars/754809998789443605/3f4f8e73962c81e9b992830b464ffe86.png?size=256')
        .addField(`Main Package Version:`, `Discord.js Version: 12.2.0\nDiscord.js-Commando Version: 0.10.0\nNode.js Version: 12.x`)
        .addField(`Used:`,(`RAM: ${diagramMaker(usedRAM, freeRAM)} [${Math.round(100 * usedRAM / (usedRAM + freeRAM))}%]\n`+
        `CPU: ${diagramMaker(cpuUsage, 100-cpuUsage)} [${Math.round(cpuUsage)}%]\n`+
        `HEXX PROCESS: ${(process.memoryUsage().heapUsed / 1000000).toFixed(2)}MB\n`+
        `STORAGE: ${driveUsed ? `${diagramMaker(driveUsed, driveFree)} [${Math.round(driveUsed)}%]` : notSupported}\n`+
        `PROCESSES: ${processes != 'not supported'? processes : notSupported}`).trim())
        .addField(`Machine Specs:`,`CPU Count: ${osu.cpu.count()}\nCPU Model: ${os.cpus()[0].model}\nCPU Speed: ${os.cpus()[0].speed}MHz
    ${osu.os.platform() != "win32" ? `Storage: ${diagramMaker(driveUsed,driveFree)} [${driveUsed}%]`: ""}`)
        .addField(`System Specs:`,`System Type: ${osu.os.type()}\nSystem Architecture: ${osu.os.arch()}\nSystem Platform: ${osu.os.platform()}`)
        .addField(`Network Stats:`,`${networkUsage ? `Input Speed: ${networkUsageIn}\nOutput Speed: ${networkUsageOut}` : notSupported}`)
        .setTimestamp()
        .setFooter('Hexx#3560', 'https://cdn.discordapp.com/avatars/754809998789443605/3f4f8e73962c81e9b992830b464ffe86.png?size=256');
        
      message.channel.send(embed);
2 Likes