How to properly communicate between shards?

I tried something like this, but it ended up sending hundreds of messages when it should have sent one, or otherwise just crashing out. I can't seem to find a good guide or example on how to set up a way for one shard to communicate something to all shards.
// Index.ts
manager.spawn()
.then(shards => {
shards.forEach(shard => {
shard.on('message', message => {
manager.broadcast(message);
});
});
})
.catch(console.error);
// Index.ts
manager.spawn()
.then(shards => {
shards.forEach(shard => {
shard.on('message', message => {
manager.broadcast(message);
});
});
})
.catch(console.error);
// Bot.ts
process.on('message', (message: string) => {
let data;
try {
data = JSON.parse(message);
} catch {
return;
// Ignore
}

console.log(data.message);
});

/// On an event:
process.send(JSON.stringify({ message: 'Hello World!'}));
// Bot.ts
process.on('message', (message: string) => {
let data;
try {
data = JSON.parse(message);
} catch {
return;
// Ignore
}

console.log(data.message);
});

/// On an event:
process.send(JSON.stringify({ message: 'Hello World!'}));
2 Replies
d.js toolkit
d.js toolkit2w ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
Sheepolution
SheepolutionOP6d ago
Nope I changed it to the following, and it looks like this works? No errors so far.
manager.spawn()
.then(shards => {
shards.forEach(shard => {
shard.on('message', message => {
if (typeof message !== 'string') {
return;
}

if (message.startsWith('__EVENT:')) {
try {
manager.broadcast(message);
} catch {
// Ignore
}
}
});
});
})
.catch(console.error);
manager.spawn()
.then(shards => {
shards.forEach(shard => {
shard.on('message', message => {
if (typeof message !== 'string') {
return;
}

if (message.startsWith('__EVENT:')) {
try {
manager.broadcast(message);
} catch {
// Ignore
}
}
});
});
})
.catch(console.error);
// Bot.ts
process.on('message', (message: string) => {
if (typeof message !== 'string') {
return;
}

if (!message.startsWith('__EVENT:')) {
return;
}

const parts = message.split(':');
const command = parts[1];

if (command == 'hello') {
console.log('Hello World!');
}
});

/// On an event
process.send('__EVENT:hello');
// Bot.ts
process.on('message', (message: string) => {
if (typeof message !== 'string') {
return;
}

if (!message.startsWith('__EVENT:')) {
return;
}

const parts = message.split(':');
const command = parts[1];

if (command == 'hello') {
console.log('Hello World!');
}
});

/// On an event
process.send('__EVENT:hello');
Want results from more Discord servers?
Add your server