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

max-io

v0.1.1

Published

TypeScript framework for Max messenger bots

Downloads

363

Readme

Max IO — TypeScript-фреймворк для разработки чат-ботов в мессенджере Max. Библиотека даёт middleware-runtime, typed context, long polling, webhook, upload helpers, клавиатуры и дополнительные модули для session/scene/i18n.

Возможности

| Возможность | Что даёт | | ------------------ | -------------------------------------------------------------------------------------- | | Middleware-runtime | bot.use, bot.on, bot.command, bot.hears, bot.action | | Typed Context | ctx.reply, ctx.message, ctx.args, ctx.payload, ctx.state, ctx.api | | Long polling | bot.start(), marker API, режим для разработки и тестирования | | Webhook | bot.start({ webhook }), webhookCallback, createWebhook, deleteWebhook | | Upload | image/video/audio/file, progress, timeout, AbortSignal, retry attachment.not.ready | | Клавиатуры | inline keyboard, open_app, message, clipboard, reply keyboard types | | Модули | max-io/lib/session, max-io/lib/scene, max-io/lib/i18n |

Установка

npm i max-io
yarn add max-io

Требуется Node.js >=14.13.1.

Первый бот

Создайте токен бота в Max и передайте его через переменную окружения MAX_BOT_TOKEN.

import 'dotenv/config';

import { Bot, Keyboard } from 'max-io';

const bot = new Bot(process.env.MAX_BOT_TOKEN!);

bot.command('start', async (ctx) => {
  await ctx.reply('Привет! Я бот на Max IO.', {
    attachments: [
      Keyboard.inlineKeyboard([
        [Keyboard.button.callback('Проверить callback', 'demo:callback')],
      ]),
    ],
  });
});

bot.command('echo', async (ctx) => {
  const text = ctx.payload || 'Напиши /echo любой текст';
  await ctx.reply(text);
});

bot.action('demo:callback', async (ctx) => {
  await ctx.answerOnCallback({ notification: 'Callback получен' });
});

bot.start().then();

Команды поддерживают payload и args:

bot.command('ban', async (ctx) => {
  const [userId, ...reasonParts] = ctx.args ?? [];
  const reason = reasonParts.join(' ');

  await ctx.reply(`userId=${userId}; reason=${reason || 'не указана'}`);
});

Подробнее: docs/01-first-bot.md и docs/02-listen-and-respond.md.

Webhook за минуту

import 'dotenv/config';

import { Bot } from 'max-io';

const bot = new Bot(process.env.MAX_BOT_TOKEN!);

bot.command('ping', async (ctx) => {
  await ctx.reply('pong from webhook');
});

await bot.start({
  webhook: {
    domain: 'https://example.com',
    port: 3000,
    secret: process.env.MAX_WEBHOOK_SECRET,
  },
});

Если path не указан, max-io создаёт безопасный стабильный path по токену. При запуске webhook по умолчанию удаляются старые подписки с другими URL; при запуске polling удаляются все webhook-подписки.

Подробнее: docs/webhook.md.

Polling marker

marker нужен, чтобы продолжить long polling с конкретной позиции. Если marker не передать, Max API возвращает только последнее обновление, поэтому события, накопившиеся пока бот был недоступен, не будут прочитаны автоматически.

const bot = new Bot(process.env.MAX_BOT_TOKEN!, {
  polling: { marker: Number(process.env.MAX_POLLING_MARKER) || undefined },
});
// или
bot.polling.setMarker(123456);
console.log(bot.polling.marker);
// или
await bot.start({ marker: bot.polling.marker });

Long polling стоит использовать для разработки и ручной проверки. Для production Max рекомендует Webhook; с 11.05.2026 для polling заявлены ограничения: 2 RPS, timeout 30 секунд, batch до 100 событий и TTL событий 24 часа.

Upload и вложения

bot.command('video', async (ctx) => {
  const video = await ctx.api.uploadVideo({
    source: './public/video.mp4',
    onProgress: ({ loaded, total }) => {
      if (total) console.log(`upload ${Math.round((loaded / total) * 100)}%`);
    },
  });

  await ctx.reply('Видео загружено', {
    attachments: [video.toJson()],
  });
});

Подробнее: docs/03-attachments-and-uploads.md.

Клавиатуры

const keyboard = Keyboard.inlineKeyboard([
  [Keyboard.button.callback('Callback', 'payload')],
  [Keyboard.button.openApp('Открыть mini app', 'my_bot', 'demo')],
  [Keyboard.button.clipboard('Скопировать', 'promo-code')],
]);

Подробнее: docs/04-keyboards.md.

Дополнительные модули

import { I18n } from 'max-io/lib/i18n';
import { SceneManager, StepScene } from 'max-io/lib/scene';
import { SessionManager } from 'max-io/lib/session';
  • max-io/lib/session — session middleware с memory/Redis storage.
  • max-io/lib/scene — сцены и step-сценарии поверх session.
  • max-io/lib/i18n — YAML-локализация с поддержкой session.

Подробнее: docs/05-sessions-scenes-i18n.md.

Документация

Entry points

| Import | Назначение | | -------------------- | -------------------------------------------------------- | | max-io | Runtime, Bot, Context, Api, helpers, основные типы | | max-io/types | Публичные типы Bot API | | max-io/lib/session | Session middleware | | max-io/lib/scene | Scene manager | | max-io/lib/i18n | I18n middleware |

Примеры

В репозитории есть отдельные TypeScript-проекты для ручной проверки:

Полезные модули

  • nestjs-max — интеграция Max IO с NestJS.

Статус API

Max Bot API развивается, а часть поведения зависит от серверной реализации и клиента Max. В проекте есть ручные сценарии проверки для upload, webhook, reply keyboard, chat admin API и video details. Если поведение API не подтверждено схемой или живой проверкой, лучше фиксировать это отдельно перед изменением публичных типов.

Лицензия

MIT. Подробности по сторонним ориентирам и лицензиям см. в THIRD_PARTY_NOTICES.md.