vk-io

repository·master·Indexed 20 days ago

https://github.com/negezor/vk-io

A Node.js module for interacting with the VK API, providing a 1-to-1 mapping of API methods and an ecosystem for building complex VK bots. The ecosystem includes specialized modules such as @vk-io/authorization for advanced authentication, @vk-io/scenes for multi-step user flows, @vk-io/hear for message pattern handling, @vk-io/streaming for the VK Streaming API, and @vk-io/stateless-prompt for state-free user prompting. Requires Node.js 12.20.0 or newer.

Tokens
52.6K
Snippets
149
Records
206
Agent score
68%

What's inside vk-io

  1. Explore the vk-io ecosystem

    master

    The vk-io ecosystem includes several specialized modules for bot development and advanced functionality:

    • Core Extensions:

      • @vk-io/authorization: Advanced authorization (e.g., login/password).
      • @vk-io/session: Session management.
      • @vk-io/scenes: Middleware-based scene management.
      • @vk-io/hear: Implementation of 'hears' (listening for specific patterns).
      • @vk-io/streaming: Working with the VK Streaming API.
      • @vk-io/stateless-prompt: Stateless prompt implementation.
    • Third-party/Add-ons:

      • vk-io-redis-storage: Redis storage for @vk-io/session.
      • nestjs-vk: Integration for NestJS.
      • vk-io-question: Promise-based prompts.
      • vk-io-pages: Dynamic pagination.
      • henta: A simple VK bot engine.
  2. How VK-IO Scenes work

    master

    VK-IO Scenes provides a middleware-based implementation for managing multi-step user flows (scenes) in VK bots.

    To use it, you typically need:

    1. A Session Manager (e.g., from @vk-io/session) to persist user state across messages.
    2. A Scene Manager to handle the scene lifecycle.
    3. Middleware registration: You must attach the sceneManager.middleware and sceneManager.middlewareIntercept to your update listeners to ensure scenes are processed and entry points are handled.
    4. Scene Definition: Use StepScene to define a sequence of steps. Each step is a function that processes the current context and decides whether to move to the next step using context.scene.step.next() or exit.
    5. Scene Entry: Trigger a scene by calling context.scene.enter('scene_id') within an update handler.
    import { VK } from 'vk-io';
    import { SessionManager } from '@vk-io/session';
    import { SceneManager, StepScene } from '@vk-io/scenes';
    
    const vk = new VK({ token: 'YOUR_TOKEN' });
    const sessionManager = new SessionManager();
    const sceneManager = new SceneManager();
    
    // Register middleware
    vk.updates.on('message_new', sessionManager.middleware);
    vk.updates.on('message_new', sceneManager.middleware);
    vk.updates.on('message_new', sceneManager.middlewareIntercept);
    
    // Define and add a scene
    sceneManager.addScenes([
        new StepScene('signup', [
            async (context) => {
                // Step 1 logic
                return context.scene.step.next();
            },
            async (context) => {
                // Step 2 logic
                return context.scene.step.next();
            }
        ])
    ]);
    
    // Enter a scene via command
    vk.updates.on('message_new', (context, next) => {
        if (context.text === '/signup') {
            return context.scene.enter('signup');
        }
        return next();
    });
    
    vk.updates.start();
  3. How stateless prompts work in @vk-io/stateless-prompt

    master

    The @vk-io/stateless-prompt module implements a middleware-based approach to prompting users without requiring server-side state management.

    The workflow is as follows:

    1. The bot sends a message containing a unique suffix (a special text string) at the end of the message.
    2. When the user replies to that specific message, the module checks if the reply contains the same suffix.
    3. If the suffix is present, the module triggers the configured handler with the user's message content.
    4. If the suffix is missing, the middleware is skipped, allowing other handlers to process the message normally.
  4. Understand Messages Conversation and Member structures

    master

    The MessagesConversation object represents a chat or direct message thread. Key fields include last_message_id, unread_count, and mentions (an array of message IDs).

    To understand the participants within a conversation, use MessagesConversationMember. This object provides details about a specific member, such as is_admin, is_owner, join_date, and can_kick (indicating if the member can be removed by others).

    interface MessagesConversation {
        last_message_id: number;
        last_conversation_message_id: number;
        in_read: number;
        out_read: number;
        unread_count: number;
        is_marked_unread: boolean | number;
        mentions: number[];
        important: boolean | number;
        unanswered: boolean | number;
        special_service_type: "business_notify";
        [key: string]: any;
    }
    
    interface MessagesConversationMember {
        can_kick: boolean | number;
        request_date: number;
        invited_by: number;
        is_admin: boolean | number;
        is_owner: boolean | number;
        is_message_request: boolean | number;
        join_date: number;
        member_id: number;
        [key: string]: any;
    }
  5. Define conditions for event listening in @vk-io/hear

    master

    When using @vk-io/hear, you can specify conditions to filter which events trigger a handler. Conditions can be simple values or complex objects that match properties of the event context.

    Supported condition types include:

    • Primitive values: string, number, or boolean (exact match).
    • Regular Expressions: RegExp for pattern matching.
    • Arrays: An array of any of the above (matches if the value satisfies any element in the array).
    • Object Conditions: An object where keys correspond to properties in the event context. Each property in the object can be a single condition or an array of conditions.

    If you provide an object condition, the listener will only trigger if all specified properties match their respective conditions.

    // Example of how conditions might be structured conceptually
    // (Actual usage depends on the specific event object being listened to)
    
    // Single value condition
    const condition1 = 'some_value';
    const condition2 = /pattern/.test;
    
    // Array of conditions (OR logic)
    const condition3 = ['value1', 'value2'];
    
    // Object condition (AND logic across keys)
    const condition4 = {
        id: 123,
        type: ['message', 'edit'],
        status: /active/
    };
  6. How API request modes work

    master

    The API class uses a worker system to manage how requests are processed. You can control this via apiMode:

    • sequential (Default): Requests are processed one after another in the order they were called. This is the safest mode for avoiding rate limits.
    • parallel: All requests are sent through the execute method to be batched together. Note that certain methods (like upload methods) are unsupported in this mode.
    • parallel_selected: Only the methods listed in apiExecuteMethods are collected and sent via execute. All other methods are handled in sequential mode.

    To change the mode at runtime, you can call api.updateWorker(), which will transition the current queue to a new worker type.