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

node-botx

v0.2.9

Published

TypeScript библиотека для работы с BotX API - платформой для создания чат-ботов

Readme

node-botx

TypeScript библиотека для работы с BotX API - платформой для создания чат-ботов.

Установка

npm install node-botx
# или
pnpm add node-botx
# или
yarn add node-botx

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

Основной бот

import { Bot, BotAccountWithSecret } from 'node-botx';

const bot = new Bot({
  collectors: [],
  botAccounts: [
    new BotAccountWithSecret(
      'your-bot-id',
      'your-cts-url',
      'your-bot-secret'
    )
  ]
});

// Обработка сообщений
bot.onMessage(async (message) => {
  await bot.sendMessage({
    chatId: message.chatId,
    body: 'Привет!'
  });
});

SmartApp RPC с декораторами

Библиотека поддерживает создание RPC-методов для смартаппов с использованием декораторов, что делает код более читаемым и структурированным:

import { 
  Bot, 
  HandlerCollector,
  SmartAppEvent
} from 'node-botx';
import {
  RPCArgsBaseModel,
  RPCRouter,
  SmartAppRPC,
  RPCResultResponse,
  RPCErrorExc,
  RPCError,
  RpcMethod,
  RpcController,
  SmartAppInstance
} from 'node-botx';

// Класс аргументов для RPC метода с валидацией
class SumArgs extends RPCArgsBaseModel {
  constructor(data?: Record<string, any>) {
    super(data);
    this.a = data?.a || 0;
    this.b = data?.b || 0;
  }
  
  a: number;
  b: number;
}

class UserArgs extends RPCArgsBaseModel {
  constructor(data?: Record<string, any>) {
    super(data);
    this.userId = data?.userId || "";
  }
  
  userId: string;
}

// Создаем роутер для RPC методов
const rpcRouter = new RPCRouter();

// Пример класса с декораторами (аналог Python версии)
@RpcController(rpcRouter)
class UserService {
  
  @RpcMethod("get_user_info")
  async getUserInfo(smartapp: SmartAppInstance): Promise<RPCResultResponse<any>> {
    // Имитация получения информации о пользователе
    const userInfo = {
      id: "12345",
      name: "John Doe",
      email: "[email protected]",
      role: "user"
    };

    return new RPCResultResponse(userInfo);
  }

  @RpcMethod("sum")
  async sum(smartapp: SmartAppInstance, args: SumArgs): Promise<RPCResultResponse<number>> {
    const result = args.a + args.b;
    return new RPCResultResponse(result);
  }

  @RpcMethod("multiply")
  async multiply(smartapp: SmartAppInstance, args: SumArgs): Promise<RPCResultResponse<number>> {
    const result = args.a * args.b;
    return new RPCResultResponse(result);
  }

  @RpcMethod("get_user")
  async getUser(smartapp: SmartAppInstance, args: UserArgs): Promise<RPCResultResponse<any>> {
    if (!args.userId) {
      throw new RPCErrorExc(
        new RPCError(
          "User ID is required",
          "USER_ID_REQUIRED",
          { field: "userId" }
        )
      );
    }

    return new RPCResultResponse({ 
      id: args.userId, 
      name: "John Doe",
      email: "[email protected]"
    });
  }
}

// Создаем экземпляр сервиса (автоматически регистрирует все методы)
new UserService();

// Создаем SmartApp RPC менеджер
const smartappRPC = new SmartAppRPC([rpcRouter]);

// Создаем коллектор для обработки событий
const collector = new HandlerCollector();

// Обработчик smartapp событий
collector.smartappEvent(
  async (event: SmartAppEvent, bot: Bot): Promise<void> => {
    await smartappRPC.handleSmartappEvent(event, bot);
  }
);

// Обработчик синхронных smartapp событий
collector.syncSmartappEvent(
  async (event: SmartAppEvent, bot: Bot) => {
    return await smartappRPC.handleSyncSmartappEvent(event, bot);
  }
);

// Создаем бота
const bot = new Bot({
  collectors: [collector],
  botAccounts: [
    new BotAccountWithSecret(
      'your-bot-id',
      'your-cts-url',
      'your-bot-secret'
    )
  ]
});

Особенности SmartApp RPC

  • Декораторы - использование @RpcMethod и @RpcController для удобного определения RPC методов
  • Автоматическая регистрация - все методы автоматически регистрируются при создании экземпляра класса
  • Автоматическая валидация аргументов - аргументы автоматически валидируются при создании экземпляра класса
  • Поддержка мидлварей - можно добавлять кастомные мидлвари для обработки запросов
  • Обработка исключений - встроенная система обработки ошибок с пользовательскими обработчиками
  • Типизация - полная TypeScript поддержка с дженериками
  • Совместимость с Python - API полностью совместим с Python версией pybotx-smartapp-rpc

Основные возможности

  • Отправка и получение сообщений
  • Работа с файлами и вложениями
  • Управление чатами и пользователями
  • Поддержка стикеров
  • Системные события
  • SmartApp RPC с декораторами - создание RPC-методов для смартаппов с использованием декораторов
  • Автоматическая валидация данных с помощью class-validator
  • TypeScript поддержка
  • Совместимость с Python pybotx-smartapp-rpc

Требования

  • Node.js 16+
  • TypeScript 4.9+

Лицензия

MIT