npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@brussell98/megane

v0.13.0

Published

A cluster management system for Discord bots

Downloads

22

Readme

Megane

A sharding manager for Discord bots. Megane distributes your shards across (logical) CPU cores. Megane uses Eris to interface with the Discord API. Based on Kurasuta.

Features

  • Automatic clustering and sharding of your bot across CPU cores
  • Central data store that all clusters can access and modify
  • Simple and extensible way to get users, channels, and guilds from other clusters
  • Run eval over IPC
  • Restart individual clusters instead of the whole bot at once
  • Create worker processes to interact with APIs or do other expensive or central tasks
  • Automatic and extensible collection of statistics

Features to add before 1.0:

  • (IPC) Optional messages in text channels
  • Change cpuUsage recording to return diff since last check

Features to be added after 1.0:

  • Rolling restart helper
  • Re-sharding
  • Improve IPC usability (need suggestions)

Considerations

Splitting your bot into multiple processes should not be done unless needed. Megane has some downsides compared to how a normal bot works. Make sure you consider these first:

  • Developing will be more complicated due to the need to use ipc and lack of a complete local cache
  • Fetching users, channels, guilds, or other structures from other processes will remove the ability to use methods without manually recreating them. Certain properties may also be missing after converting to plain objects

Using

Package name: @brussell98/megane

You can see working examples by browsing the examples folder

Getting Started

You will have at least two main files:

  1. A file for your "master" process, which creates a new ShardManager. We will call this file "index.js"
  2. A file for your "cluster" process (the worker), which extends BaseClusterWorker. We will call this file "bot.js"

In your index.js file you should have some code similar to this:

const { isMaster } = require('cluster');
const { ShardManager } = require('@brussell98/megane');

const manager = new ShardManager({
	path: __dirname + '/bot.js',
	token: 'Your bot token'
});

manager.spawn(); // You should await this

if (isMaster) {
	// Master process code here
	manager.on('error', error => console.error(error)); // Not handling these errors will kill everything when any error is emitted
	manager.on('debug', message => console.log(message));
	manager.on('clusterReady', cluster => console.log(`Cluster ${cluster.id} ready`));
	manager.once('allClustersReady', () => console.log('All clusters ready'));
}

This will create a new ShardManager which will run bot.js on separate processes. The worker file (bot.js) must implement a BaseClusterWorker. This will be demonstrated next.

Note the isMaster block. Your index.js file will be run each time a worker is created. Any code you only want to run on the master process must check if it's running on the master process.

Next, your bot.js file should implement a ClusterWorker, like so:

const { BaseClusterWorker } = require('@brussell98/megane');

module.exports = class BotWorker extends BaseClusterWorker {
	constructor(manager) {
		super(manager);
	}

	async launch() {
		// Anything you want to run when the worker starts
		// This is run after the IPC is initialized
		await this.client.connect(); // Connect eris to Discord
	}
}

Services

In many cases you will have tasks that are used by all clusters. One example is updating Twitch API data. You can create a service to handle this and it will run in its own process, accessible by all clusters. Add the following code to your index.js file:

if (isMaster) {
	// ...
	manager.on('serviceReady', service => console.log(`Service ${service.name} ready`));

	manager.registerService(__dirname + '/service.js', { name: 'example-service', timeout: 60e3 });
}

This will register a service named "example-service" and spawn a worker. The service worker is implemented similarly to a cluster worker.

Here is an example of what your service.js file should look like:

const { BaseServiceWorker } = require('@brussell98/megane');

module.exports = class ServiceWorker extends BaseServiceWorker {
	constructor(manager) {
		super(manager);
	}

	async launch() {
		// Anything you want to run when the worker starts
		// This is run after the IPC is initialized
		await this.sendReady(); // Required to be sent before `timeout`
	}

	// Handles SERVICE_COMMAND events
	handleCommand(data, receptive) {
		if (data.op === 'PING')
			return receptive && this.asResponse('PONG');

		if (receptive)
			return this.asError(new Error('Unknown command'));
	}
}

Your bot can then send commands like this:

const reply = await this.ipc.sendCommand('example-service', { op: 'PING' }, { receptive: true });
console.log(reply); // PONG

Diagram

Master:
index.js -> ShardManager -> Clusters
						 -> Services
						 -> MasterIPC

ClusterWorker:
index.js -> ShardManager -> bot.js -> ClusterWorkerIPC

ServiceWorker:
index.js -> ShardManager -> service.js -> ServiceWorkerIPC

Documentation

Refer to DOCUMENTATION.md

Changelog

Refer to CHANGELOG.md

Naming

This was created to be used for Mirai Bot for Discord. The bot is named after the anime character Mirai Kuriyama (栗山 未来), who notably wears red glasses [Megane (めがね)].