A modern, Node.js and browser-friendly ES6 WebSocket library for interacting with hack.chat servers. This engine provides an object-oriented interface, automatic reconnection, session management, and structured event handling.
- Node.js 14+ (This package uses ES Modules)
- NPM 6+
npm install hackchat-engineThis library uses ES Modules. You must use import syntax.
import { Client, Events } from 'hackchat-engine';
const botName = 'MyBot';
const botPass = 'secretPassword';
const channel = 'programming';
// initialize the client
const client = new Client({
isBot: true,
debug: false,
});
let isJoined = false;
// triggered when the server establishes or updates a session
client.on(Events.SESSION, (session) => {
if (isJoined || (Array.isArray(session.channels) && session.channels.includes(channel))) {
isJoined = true;
return;
}
// join the channel once the initial session is ready
client.join(botName, botPass, channel);
});
// triggered when the client successfully joins the channel
client.on(Events.ONLINE_SET, (data) => {
isJoined = true;
client.say(data.channel, 'Hello world! I am a bot.');
});
// reset join guard if the socket drops
client.on(Events.RECONNECTING, () => {
isJoined = false;
});
// triggered on every new message
client.on(Events.NEW_MESSAGE, (message) => {
if (!message.content || !message.user || message.user.username === botName) return;
if (message.content === '!ping') {
client.say(message.channel, `@${message.user.username} Pong!`);
}
});For a more in-depth example, see ./example.js.
You can pass an options object to the Client constructor to customize the connection.
const client = new Client({
// Connection details
ws: {
gateway: 'wss://hack.chat/chat-ws', // Default
// gateway: 'ws://127.0.0.1:6060/' // For local development
},
// Set to true to see internal logs and raw packets (default: false)
debug: false,
// If true, identifies as a bot to the server (default: true)
isBot: true,
// Optional previous JWT session token to restore on connect (default: false)
session: false,
// Optional array of WSEvents opcode strings to ignore
ignoredEvents: [],
});The client extends EventEmitter. You can listen using either the exported Events constants (recommended) or their raw string names:
Constant (Events.*) |
String Name | Payload | Description |
|---|---|---|---|
Events.CONNECTED |
connected |
Client |
WebSocket connection established. |
Events.SESSION |
session |
SessionStruct |
Server issued or updated a session (token, channels, restored, wallet). |
Events.READY |
ready |
— | Client has completed initial handshake and is ready. |
Events.DISCONNECT |
disconnect |
CloseEvent |
WebSocket closed intentionally via client.destroy(). |
Events.RECONNECTING |
reconnecting |
— | Connection lost; client is attempting to auto-reconnect. |
Events.ONLINE_SET |
channelJoined |
{ client, channel, users } |
Client joined a channel and received its initial user list. |
Events.NEW_MESSAGE |
message |
MessageStruct |
A new chat message was received. |
Events.USER_JOIN |
userJoined |
User |
A user joined a channel. |
Events.USER_LEAVE |
userLeft |
{ user, channel } |
A user left a channel. |
Events.USER_UPDATE |
userUpdate |
User |
A user changed their nick, flair, color, effect, or status. |
Events.CHANNEL_INFO |
information |
Information |
Server sent an informational message (text, channel, id, args). |
Events.CHANNEL_WARN |
warning |
WarningStruct |
Server sent a warning (e.g., rate limit). |
Events.CHANNEL_EMOTE |
emote |
Emote |
A user sent a /me emote. |
Events.CHANNEL_WHISPER |
whisper |
WhisperStruct |
Received a private whisper. |
Events.CHANNEL_INVITE |
invite |
Invite |
Received an invitation to another channel. |
Events.CHANNEL_CAPTCHA |
gotCaptcha |
{ CaptchaStruct } |
Server requires a captcha solution (CaptchaStruct). |
Events.CHANNEL_PASSWORD_REQ |
gotPasswordReq |
{ PasswordReqStruct } |
Channel requires a password to join (PasswordReqStruct). |
Events.UPDATE_MESSAGE |
updateMessage |
UpdateMessageStruct |
A previously sent message was edited or cleared. |
Events.PUB_CHANS |
publicchannels |
PubChannelsStruct |
Server returned the list of public channels. |
Events.HACK_ATTEMPT |
hackAttempt |
HackAttemptStruct |
A 3rd-party code suggestion arrived. |
Events.WALLET_INFO |
walletInfo |
WalletInfoStruct |
Wallet address lookup result. |
Events.SIGN_MESSAGE |
signMessage |
{ wallet, message } |
Server requested a Sign-In With Solana signature. |
Events.SIGN_TRANSACTION |
signTransaction |
{ tx, type, channel, from, imageUrl } |
Server requested a Solana transaction signature. |
Events.ERROR |
error |
Error |
Internal or WebSocket error. |
Events.WARN |
warn |
string |
Non-critical internal warning. |
Events.DEBUG |
debug |
string |
Verbose internal debug log. |
Note on
Events.SESSION: The server emits asessionevent whenever your session state changes (after joining, leaving, changing nick/color, connecting a wallet, etc.)—not only on initial connect. Always guardclient.join()insideEvents.SESSIONso your bot does not attempt to re-join on every token refresh.
client.join(name, password, channel, color): Authenticate and join a specific channel (coloris optional).client.leave(channel): Leave a joined channel.client.say(channel, text): Send a chat message to a channel.client.changeColor(hex): Change your nickname color (e.g.,'FFFFFF').client.updateMessage(customId, text, channel, mode): Edit a previously sent message (mode:'overwrite','append','prepend', or'complete').client.getChannels(): Request the public channel list.client.enableCaptcha(channel)/client.disableCaptcha(channel): Toggle channel captcha (requires permissions).client.lockChannel(channel)/client.unlockChannel(channel): Toggle channel lock (requires permissions).client.requestSiw(wallet, address, domain): Initiate a Sign-In With Solana request.client.sendSignature(signature, signedMessage): Submit a signed SIWS message for verification.client.sendSignedTransaction(signedTransaction): Submit a signed transaction.client.getWallet(target, channel): Look up a user's connected wallet byuseridornick.client.disconnectWallet(): Disconnect the currently attached wallet.client.ws.send(payload): Send a raw command packet directly over the WebSocket.client.destroy(): Clear timers and close the WebSocket connection.
client.myUser.changeUsername(newNick): Request a nickname change.client.myUser.blockUser(userid): Locally block a user by ID.
Retrieved from client.users or event payloads:
user.sendMessage(channel, text): Send a message to a channel.user.sendWhisper(channel, text): Send a private whisper to the user.user.sendInvite(channel, to): Invite the user to another channel.user.kick(channel, to)/user.ban(channel)/user.mute(channel)/user.unmute(channel): Moderation actions (require permissions).user.inChannel(channel): Check if the user is present in a channel.
message.reply(text): Reply directly to the channel theMessageStructoriginated from.whisper.reply(text): Send a private whisper back to the sender of aWhisperStruct.
If the server implements custom opcodes that are not natively mapped by the engine, you can register a listener for them:
client.onCommand('customEvent', (payload) => {
console.log('Received custom packet:', payload);
});Users are stored in an ExtMap (an extended Map with find, findKey, filter, some, and every).
// Get a user by ID
const user = client.users.get(12345);
// Find a user by name
const admin = client.users.find((u) => u.username === 'Admin');
if (admin) {
console.log(`${admin.username} is currently ${admin.isOnline ? 'Online' : 'Offline'}`);
}MIT