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

@green-api/maxbot-chatbot-ts

v1.0.1

Published

TypeScript SDK for MAX Bot API

Readme

MAX BOT API Chatbot (TypeScript)

@green-api/maxbot-chatbot-ts — это фреймворк для создания масштабируемых ботов для MAX BOT API на языке TypeScript (Node.js). Построенная на основе @green-api/maxbot-api-client-ts, эта библиотека предоставляет удобный маршрутизатор, автоматическое обновление данных и надежный менеджер состояний (FSM) для построения многошаговых диалоговых сценариев.

Для использования библиотеки потребуется получить токен бота в консоли разработчика MAX bot.
Ознакомиться с инструкцией можно по ссылке.

API

Документацию по REST API MAX можно найти по ссылке https://dev.max.ru/docs-api. Библиотека является оберткой для REST API, поэтому документация по указанной выше ссылке также применима к используемым здесь моделям и параметрам запроса.

Документацию по MAX BOT API можно найти по ссылке green-api.com/max-bot-api/docs.

Поддержка

Support Support Support

Руководства и новости

Guides News News

Установка

Убедитесь, что у вас установлена версия Node.js версии не ниже 18

node -v

Установите библиотеки:

npm install @green-api/maxbot-chatbot-ts

Использование и примеры

1. Инициализация бота

Чтобы начать получать и отвечать на сообщения, настройте бота, используя ваш base_url и token, затем запустите механизм получения обновлений.

import { MaxBotAPI } from '@green-api/maxbot-api-client-ts';
import { Bot } from '@green-api/maxbot-chatbot-ts';

async function bootstrap() {
    const api = new MaxBotAPI({
        base_url: "https://platform-api.max.ru", /* Base url for MAX API requests */
        token: "YOUR_BOT_TOKEN",                 /* Max bot token */
    });

    const myBot = new Bot(api);

    try {
        await myBot.start();
    } catch (error) {
        console.error("Error starting bot:", error);
    }
}

bootstrap();

2. Маршрутизация команд и сообщений

Встроенный маршрутизатор упрощает обработку команд, обратных вызовов (колбеков) и обновлений.

import { UpdateType, Format } from '@green-api/maxbot-api-client-ts';

myBot.router.command("/start", async (n) => {
    await n.reply("Hello! Welcome to the MAX Bot.");
});

myBot.router.register(UpdateType.MessageCreated, async (n) => {
    const text = n.text();
    if (text === "ping") {
        await n.reply("pong", Format.Markdown);
    }
});

myBot.router.callback("accept_rules_payload", async (n) => {
    await n.reply("*Thank you for accepting the rules!*", Format.Markdown);
    await n.answerCallback("Rules accepted");
});

3. Управление состояниями и сцены (FSM)

Для сложных ботов (например, для регистрации пользователей, викторин или пошаговых форм) используйте Менеджер состояний (StateManager) и сцены (Scene). Сцена инкапсулирует конкретную ситуацию в диалоге и изолирует её логику.

class RegistrationScene implements Scene {
    async start(n: Notification): Promise<void> {
        const text = n.text();
        
        if (text === "/start") {
            await n.reply("Let's register! What is your *login*?");
            return;
        }
        
        if (text.length >= 4) {
            n.setData({ login: text });
            await n.reply(`**Login** \`${text}\` accepted. Now enter your **password**:`);
            n.activateNextScene(new PasswordScene());
        } else {
            await n.reply("Login must be **at least 4 characters long**.");
        }
    }
}

class PasswordScene implements Scene {
    async start(n: Notification): Promise<void> {
        const password = n.text();
        const data = n.getData<{ login: string }>();
        
        await n.reply(`Success! Profile created.\nLogin: \`${data?.login}\`\nPass: \`${password}\``);
        
        n.activateNextScene(new RegistrationScene());
    }
}

const stateManager = new MapStateManager({ step: "start" });
stateManager.setStartScene(new RegistrationScene());

myBot.withStateManager(stateManager);

4. Ответ с медиафайлами

Объект Notification предоставляет удобные методы для отправки медиа, файлов, локаций и контактов. Библиотека автоматически обрабатывает задержки готовности файлов.

myBot.router.command("/photo", async (n) => {
    await n.replyWithMedia(
        "Check out this image!",
        "https://example.com/image.png",
        Format.Markdown
    );
});

5. Эхо-бот

Полный пример запуска бота, который дублирует все входящие текстовые сообщения, кроме команд:

import { MaxBotAPI, UpdateType } from '@green-api/maxbot-api-client-ts';
import { Bot, MapStateManager } from '@green-api/maxbot-chatbot-ts';

async function main() {
    const api = new MaxBotAPI({
        base_url: "https://platform-api.max.ru", /* Base url for MAX API requests */
        token: "YOUR_BOT_TOKEN",                 /* Max bot token */
    });

    const bot = new Bot(api);
    bot.withStateManager(new MapStateManager({}));

    bot.router.register(UpdateType.MessageCreated, async (n) => {
        const text = n.text();

        if (text && !text.startsWith('/')) {
            await n.reply(`**Echo:** ${text}`);
        }
    });

    process.on('SIGINT', () => {
        console.log("Shutting down...");
        bot.stop();
        process.exit(0);
    });

    try {
        await bot.start();
    } catch (error) {
        console.error("Bot initialization error:", error);
    }
}

main();