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 🙏

© 2026 – Pkg Stats / Ryan Hefner

misterbot

v0.1.0

Published

SDK oficial de Mister Bot: envío de mensajes de WhatsApp con cola anti-ban y verificación de número por código (OTP).

Downloads

21

Readme

misterbot

SDK oficial de Mister Bot — el gateway HTTP que expone WhatsApp (vía Baileys) a tus apps.

Envía mensajes de texto y multimedia que el servidor encola con jitter anti-ban, y trae un flujo listo para validar números de celular por código (OTP).

Necesitás un token de API (mbk_…) que crea un admin desde el panel de Mister Bot, y la URL base de tu instancia.

Instalación

npm install misterbot

Requiere Node >= 18 (usa fetch, FormData y Blob globales). En el browser también funciona si pasás un token con CORS habilitado.

Uso rápido

import { MisterBotClient } from 'misterbot'

const mb = new MisterBotClient({
  baseUrl: 'https://wa.miempresa.com',
  token: 'mbk_xxxxxxxxxxxxxxxx',
  sessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', // opcional si el token tiene sesión fija
})

const { id } = await mb.sendText({
  to: '5491133334444',
  text: '¡Hola! Probando la API.',
})

const estado = await mb.getStatus(id)
console.log(estado.status) // 'sent' | 'delivered' | 'read' | ...

sendText/sendMedia resuelven cuando el servidor despachó el mensaje por la cola anti-ban; por eso un envío puede tardar (delays aleatorios entre mensajes). Ajustá timeoutMs si hace falta.

Enviar multimedia

// Desde datos binarios (Buffer, Uint8Array, ArrayBuffer o Blob)
await mb.sendMedia({
  to: '5491133334444',
  data: miBuffer,
  mimeType: 'image/jpeg',
  filename: 'foto.jpg',
  caption: 'Mirá esto',
})

// Conveniencia en Node: directo desde un archivo del disco
await mb.sendMediaFile({
  to: '5491133334444',
  path: './facturas/0001.pdf',
  caption: 'Tu factura',
})

Validación de número por código (OTP)

const otp = mb.otp({
  ttlMs: 5 * 60 * 1000, // vigencia del código (default 5 min)
  codeLength: 6,         // dígitos (default 6)
  maxAttempts: 3,        // intentos antes de invalidar (default 3)
})

// 1. Mandar el código
await otp.send('5491133334444')

// 2. Verificar lo que ingresó el usuario
const r = await otp.verify('5491133334444', '123456')
if (r.ok) {
  // número validado
} else {
  // r.reason: 'mismatch' | 'expired' | 'not_found' | 'too_many_attempts'
}

Store de códigos

Por defecto el estado vive en memoria (MemoryCodeStore), suficiente para un solo proceso. Si corrés varias instancias o querés que sobreviva reinicios, inyectá tu propio store (Redis, DB, etc.):

import { MisterBotClient, type CodeStore } from 'misterbot'

const redisStore: CodeStore = {
  async get(key) {
    const raw = await redis.get(`otp:${key}`)
    return raw ? JSON.parse(raw) : undefined
  },
  async set(key, value) {
    await redis.set(`otp:${key}`, JSON.stringify(value), 'PX', value.expiresAt - Date.now())
  },
  async delete(key) {
    await redis.del(`otp:${key}`)
  },
}

const otp = mb.otp({ store: redisStore })

Mensaje personalizado

const otp = mb.otp({
  template: (code, ttlMs) =>
    `Tu código MiApp es ${code}. Vence en ${Math.round(ttlMs / 60000)} min.`,
})

Esperar confirmación de envío

const { id } = await mb.sendText({ to, text })
const final = await mb.waitUntilSent(id, { minStatus: 'delivered', timeoutMs: 30_000 })
console.log(final.status)

Manejo de errores

import { MisterBotError } from 'misterbot'

try {
  await mb.sendText({ to, text })
} catch (err) {
  if (err instanceof MisterBotError) {
    if (err.isQuotaError) {
      // cuota agotada: NO reintentar en loop, esperá al día siguiente
    } else if (err.isRetryable) {
      // 5xx: reintentá con backoff
    }
    console.error(err.code, err.status) // ej: 'session_not_connected', 409
  }
}

Códigos comunes: invalid_token (401), session_not_connected (409), session_not_found (404), daily_quota_exceeded / TOTAL_QUOTA_EXCEEDED (429).

API

| Método | Descripción | |--------|-------------| | new MisterBotClient(opts) | baseUrl, token, sessionId?, timeoutMs?, fetch? | | sendText({ to, text, sessionId? }) | Envía texto. Devuelve { id }. | | sendMedia({ to, data, mimeType, filename?, caption?, sessionId? }) | Envía binario. | | sendMediaFile({ to, path, mimeType?, caption?, sessionId? }) | Lee y envía un archivo (Node). | | getStatus(id) | Estado del mensaje. | | listSessions() | Sesiones que el token puede usar. | | waitUntilSent(id, opts?) | Pollea hasta estado terminal. | | otp(opts?) | Crea un OtpManager (send / verify). |

Desarrollo

npm install
npm run build      # genera dist/ (ESM + CJS + tipos) con tsup
npm run typecheck