mercys.js
Official SDK for building bots on Mercys — a small, typed client with a familiar builder-style API.
- Typed events mapped from the Mercys gateway (Socket.IO)
- Typed REST client for every bot-usable route
Message helpers: real reply (with replyTo), fetchReference, edit, delete; channel.send with file uploads
- Roles, permission overwrites, kick/ban, and a built-in permission calculator (
PERMISSIONS, computePermissions)
- Built-in prefix command helper
- Auto reconnect, automatic 429 retry (honors
Retry-After), clear errors
- Zero dependency on Mercys internals (only
socket.io-client), ESM + CJS, Node 18+
Install
npm install mercys.js
Quick start
- Create a bot with your user token (
POST /api/bots, see docs/bots/GUIDE.md) and copy its token
(shown once; only a hash is stored server-side).
- As a server owner, add the bot to your server (
POST /api/servers/:id/bots { botId }).
- Run:
import { Client } from 'mercys.js';
const client = new Client({ token: process.env.MERCYS_TOKEN!, baseUrl: 'http://localhost:4100' });
client.on('ready', (me) => console.log(`Logged in as ${me.username}`));
client.on('messageCreate', async (msg) => {
if (msg.content === '!ping') await msg.reply('pong');
});
await client.login();
Commands
const client = new Client({ token, commands: { prefix: '!' } });
client.commands.add({
name: 'say',
aliases: ['echo'],
description: 'Repeat text',
usage: '<text>',
run: async ({ args, rest, reply, message }) => {
await reply(rest);
},
});
client.commands.add({ name: 'help', run: ({ reply }) => reply(client.commands.helpText()) });
client.on('commandError', (err, { command }) => console.error(`!${command} failed`, err));
Arguments are split on whitespace; "quoted text" stays one argument. Messages from bots
(including your own) are ignored by the command helper (ignoreBots: false to change).
Events
| Client event |
Gateway event |
Payload |
ready |
ready (first) |
SelfUser, full ready payload |
resumed |
ready (after reconnect) |
SelfUser, payload |
messageCreate |
message:create |
Message (with helpers) |
messageUpdate |
message:update |
Message |
messageDelete |
message:delete |
{ id, channelId, serverId } |
typingStart |
typing:start |
{ channelId, userId } |
presenceUpdate |
presence:update |
{ userId, status } |
userUpdate |
user:update |
PublicUser |
serverCreate |
server:create |
ServerListEntry (bot was added) |
serverUpdate |
server:update |
Server |
serverDelete |
server:delete |
{ id } |
channelCreate |
channel:create |
Channel |
channelDelete |
channel:delete |
{ id, serverId } |
memberJoin |
member:join |
Member |
memberLeave |
member:leave |
{ serverId, userId } |
voiceState |
voice:state |
VoiceParticipantState |
voiceLeave |
voice:leave |
{ userId, channelId, serverId } |
raw |
(all) |
(eventName, payload) |
disconnect / reconnecting / error / commandError |
— |
— |
client.user, client.servers (Map) and client.voiceStates (Map) are kept in sync.
REST
client.rest is a RestClient authenticated with Authorization: Bot <token>:
await client.rest.getServers();
await client.rest.getChannels(serverId);
await client.rest.getMembers(serverId);
await client.rest.getMessages(channelId, { limit: 20, before });
await client.rest.sendMessage(channelId, 'hi');
await client.rest.editMessage(messageId, 'edited');
await client.rest.deleteMessage(messageId);
await client.rest.getUser(userId);
await client.rest.updateMe({ bio: 'I am a bot' });
await client.rest.createInvite(serverId, { maxUses: 5 });
await client.rest.getVoiceStates(serverId);
await client.rest.leaveServer(serverId);
// raw access:
await client.rest.request('GET', '/health');
Replies, files, permissions (0.2)
await msg.reply('pong'); // real reply (replyToId)
await msg.reply('selam', { mention: true }); // "@ali selam"
const original = await msg.fetchReference(); // Message | null
await msg.channel.send({
content: 'Rapor ekte',
files: [{ name: 'rapor.txt', data: Buffer.from('...') }], // Buffer | Uint8Array | ArrayBuffer | Blob
replyTo: msg, // or a message id
});
msg.attachments; msg.attachmentUrls; // incoming files
import { PERMISSIONS } from 'mercys.js';
if (await client.can(PERMISSIONS.KICK_MEMBERS, msg.serverId)) await client.rest.kickMember(msg.serverId, userId);
await client.rest.createRole(serverId, { name: 'Mod', permissions: PERMISSIONS.KICK_MEMBERS, color: '#e67e22' });
await client.rest.addMemberRole(serverId, userId, roleId);
await client.rest.setChannelOverwrite(channelId, { targetType: 'role', targetId: serverId, allow: 0, deny: PERMISSIONS.SEND_MESSAGES });
await client.rest.banMember(serverId, userId, 'spam');
Events added in 0.2: channelUpdate, roleCreate, roleUpdate, roleDelete, memberUpdate. See CHANGELOG.md.
Friends, DMs, boosts & vanity URL (0.3)
import { computeBoostLevel, MAX_BOOSTS_PER_USER } from 'mercys.js';
client.on('serverUpdate', (s) => console.log(s.name, 'Takviye seviyesi', s.boostLevel, s.vanityUrl));
// Level 3 (10 boosts) or approved Partner, MANAGE_SERVER:
await client.rest.setVanityUrl(serverId, 'mercys-tr'); // mercys.cc/mercys-tr → rest.joinInvite('mercys-tr')
computeBoostLevel(5); // 2 (thresholds 2 / 5 / 10, Partner → 3)
// Friends & DMs — USER token (`authScheme: 'Bearer'`); bots cannot have friends.
const user = new RestClient({ baseUrl, token: jwt, authScheme: 'Bearer' });
await user.sendFriendRequest('@ali'); // 403 friend_requests_disabled / friend_request_no_mutual
await user.acceptFriend(userId); // PUT /friends/:userId
await user.removeFriend(userId); // decline / cancel / unfriend (alias declineFriend)
const dm = await user.openDm(userId);
await user.sendDmMessage(dm.id, 'selam'); // 403 dm_disabled | dm_no_mutual_friend | dm_awaiting_approval
await user.decideDmRequest(dm.id, 'accept'); // or 'reject' (channel deleted)
Events added in 0.3: friendUpdate, friendDelete, dmChannel, dmMessageCreate, dmMessageDelete.
Boosting and Partner applications are human-only (403 bots_forbidden) and are not wrapped.
Shortcuts: client.channel(id).send(text), client.send(channelId, text), msg.channel.fetchMessages(),
client.setPresence('dnd'), client.sendTyping(channelId).
Bot management routes (listBots, createBot, resetBotToken, deleteBot, addBotToServer) need a
user token: new RestClient({ baseUrl, token: jwt, authScheme: 'Bearer' }).
Security
- Use
https:// for anything but localhost. For a trusted private network (e.g. a Docker host name) pass allowInsecureHttp: true.
- Keep the token in an environment variable and never log it.
- Text from users or an AI can't mass-ping:
@everyone, @here and roles are defused unless you opt in per message:
await channel.send({ content: '@everyone Bakım 22:00', allowedMentions: { everyone: true } });
await channel.send({ content: mentionRole(roleId), allowedMentions: { roles: [roleId] } });
Never opt in on text you didn't write. rest.request() is raw and doesn't sanitize.
- Guard commands.
permissions checks the member who ran the command, not the bot:
const client = new Client({ token, baseUrl, commands: { onBlocked: (b) => console.log(b.reason) } });
client.commands.add({ name: 'kick', permissions: PERMISSIONS.KICK_MEMBERS, cooldownMs: 5000, run: kick });
Errors & rate limits
- Non-2xx REST responses throw
MercysApiError (status, code, message, method, path, retryAfter).
Network failures use status: 0, code: 'network_error'.
- HTTP 429 is retried automatically up to
rest.maxRetries (default 3), waiting Retry-After seconds
(capped by maxRetryDelayMs).
- Login problems (bad token, server unreachable with
reconnect: false, no ready in readyTimeoutMs)
reject login() with MercysGatewayError.
Options
new Client({
token, // required
baseUrl: 'http://localhost:4100',
commands: { prefix: '!', caseInsensitive: true, ignoreBots: true },
reconnect: true,
reconnectDelayMax: 30_000,
readyTimeoutMs: 15_000,
rest: { maxRetries: 3, timeoutMs: 15_000, maxRetryDelayMs: 60_000, fetch },
socket: { /* socket.io-client options */ },
});
Development
npm run build -w mercys.js # dist/ (ESM + CJS + .d.ts)
npm test -w mercys.js
npm run example:ping -w mercys.js # needs MERCYS_TOKEN
Credits
Built with Claude Code (AI-assisted development, reviewed and tested by the Mercys team). Not affiliated with or endorsed by Anthropic.
License: MIT