Skip to main content
VK-IO provides a collection of helper functions for common operations like parameter encoding, HTML decoding, and peer type detection.

Execute Helpers

Functions for working with VK’s execute method.

getExecuteParams

Converts parameters object to JSON string for execute method.
import { getExecuteParams } from 'vk-io';

const params = {
  user_ids: [1, 2, 3],
  fields: ['photo_100', 'city'],
  count: 100
};

const encoded = getExecuteParams(params);
// '{"user_ids":"1,2,3","fields":"photo_100,city","count":100}'
params
Record<string, object | string>
required
Parameters object to encode.
Returns: string - JSON string with nested objects converted to strings.

getExecuteMethod

Generates VKScript code for calling API method in execute.
import { getExecuteMethod } from 'vk-io';

const code = getExecuteMethod('users.get', {
  user_ids: [1, 2, 3],
  fields: ['photo_100']
});
// 'API.users.get({"user_ids":"1,2,3","fields":"photo_100"})'
method
string
required
VK API method name.
params
Record<string, object | string>
default:"{}"
Method parameters.
Returns: string - VKScript method call code.

getChainReturn

Generates return statement for execute with multiple methods.
import { getChainReturn } from 'vk-io';

const methods = [
  'API.users.get({"user_ids":1})',
  'API.groups.getById({"group_id":1})',
  'API.wall.get({"owner_id":1,"count":10})'
];

const code = getChainReturn(methods);
// 'return [API.users.get({"user_ids":1}),API.groups.getById({"group_id":1}),API.wall.get({"owner_id":1,"count":10})];'
methods
string[]
required
Array of VKScript method calls.
Returns: string - VKScript return statement.

resolveExecuteTask

Resolves promises from execute batch based on results.
import { resolveExecuteTask } from 'vk-io';

const tasks = [
  { resolve: (value) => {}, reject: (error) => {} },
  { resolve: (value) => {}, reject: (error) => {} },
  { resolve: (value) => {}, reject: (error) => {} }
];

const result = {
  response: [{ id: 1 }, false, { id: 3 }],
  errors: [{ error_code: 5, error_msg: 'Auth failed' }]
};

resolveExecuteTask(tasks, result);
// tasks[0] resolves with { id: 1 }
// tasks[1] rejects with error
// tasks[2] resolves with { id: 3 }
tasks
Array<{ resolve, reject }>
required
Array of task objects with resolve/reject functions.
result
object
required
Execute result with responses and errors.
Returns: void

Utility Functions

getRandomId

Generates random ID for messages and other entities.
import { getRandomId } from 'vk-io';

const randomId = getRandomId();
// e.g., 45829374650000

await vk.api.messages.send({
  peer_id: 123456,
  message: 'Hello!',
  random_id: getRandomId()
});
Returns: number - Random integer based on current timestamp.
Random IDs are used to prevent duplicate message sends. VK API will reject messages with the same random_id sent within a short time period.

delay

Creates a promise that resolves after specified milliseconds.
import { delay } from 'vk-io';

// Wait 1 second
await delay(1000);

// Use in retry logic
for (let i = 0; i < 3; i++) {
  try {
    await vk.api.messages.send({ ... });
    break;
  } catch (error) {
    if (i < 2) {
      await delay(1000 * (i + 1));
    }
  }
}
delayed
number
required
Number of milliseconds to delay.
Returns: Promise<void> - Promise that resolves after delay.

unescapeHTML

Decodes HTML entities in text from VK API.
import { unescapeHTML } from 'vk-io';

const encoded = 'Hello &amp; welcome!&lt;br&gt;New line &quot;here&quot;';
const decoded = unescapeHTML(encoded);
// 'Hello & welcome!\nNew line "here"'
text
string
required
Text with HTML entities.
Returns: string - Decoded text. Decodes:
  • &lt; → <
  • &gt; → >
  • &amp; → &
  • &quot; → "
  • <br> → \n

pickProperties

Extracts specified properties from object.
import { pickProperties } from 'vk-io';

const user = {
  id: 1,
  first_name: 'Pavel',
  last_name: 'Durov',
  photo_100: 'https://...',
  city: { id: 1, title: 'Moscow' }
};

const limited = pickProperties(user, ['id', 'first_name', 'last_name']);
// { id: 1, first_name: 'Pavel', last_name: 'Durov' }
params
T
required
Source object.
properties
K[]
required
Array of property keys to extract.
Returns: Pick<T, K> - New object with only specified properties.

getPeerType

Determines peer type from peer ID.
import { getPeerType } from 'vk-io';

getPeerType(1);           // 'user'
getPeerType(-1);          // 'group'
getPeerType(2000000001);  // 'chat'
id
number
required
Peer ID to check.
Returns: string - One of: 'user', 'group', 'chat', 'email'. Peer ID Ranges:
  • Positive (1 to 2,000,000,000): User
  • Negative: Group/Community
  • Above 2,000,000,000: Chat

Advanced Helpers

applyMixins

Applies mixin classes to a target class (used internally).
import { applyMixins } from 'vk-io';

class Base {}
class Mixin1 {
  method1() {}
}
class Mixin2 {
  method2() {}
}

applyMixins(Base, [Mixin1, Mixin2]);
// Base now has method1 and method2
derivedCtor
any
required
Target constructor to apply mixins to.
baseCtors
any[]
required
Array of mixin constructors.
Returns: void

showDeprecatedMessage

Displays deprecation warning in console.
import { showDeprecatedMessage } from 'vk-io';

showDeprecatedMessage('Method oldMethod() is deprecated, use newMethod() instead');
// Output: \u001b[31mDeprecated:\u001b[39m Method oldMethod() is deprecated, use newMethod() instead
message
string
required
Deprecation message to display.
Returns: void

Usage Examples

Building Execute Code

import { getExecuteMethod, getChainReturn } from 'vk-io';

const methods = [
  getExecuteMethod('users.get', { user_ids: 1 }),
  getExecuteMethod('groups.getById', { group_id: 1 }),
  getExecuteMethod('wall.get', { owner_id: 1, count: 10 })
];

const code = getChainReturn(methods);

const result = await vk.api.execute({ code });

Peer Type Detection

import { getPeerType } from 'vk-io';

const handleMessage = async (message) => {
  const peerType = getPeerType(message.peerId);
  
  switch (peerType) {
    case 'user':
      console.log('Message from user');
      break;
    case 'chat':
      console.log('Message from chat');
      break;
    case 'group':
      console.log('Message from group');
      break;
  }
};

Retry with Delay

import { delay } from 'vk-io';

const retryRequest = async (fn, retries = 3) => {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === retries - 1) throw error;
      
      const delayMs = 1000 * Math.pow(2, i); // Exponential backoff
      console.log(`Retry ${i + 1}/${retries} after ${delayMs}ms`);
      await delay(delayMs);
    }
  }
};

const result = await retryRequest(() => 
  vk.api.users.get({ user_ids: 1 })
);

Clean HTML Content

import { unescapeHTML } from 'vk-io';

const wall = await vk.api.wall.get({ owner_id: 1, count: 10 });

const posts = wall.items.map(post => ({
  id: post.id,
  text: unescapeHTML(post.text),
  date: new Date(post.date * 1000)
}));

Filter Object Properties

import { pickProperties } from 'vk-io';

const users = await vk.api.users.get({
  user_ids: [1, 2, 3],
  fields: ['photo_100', 'city', 'verified', 'followers_count']
});

// Extract only needed fields for response
const limitedUsers = users.map(user => 
  pickProperties(user, ['id', 'first_name', 'last_name', 'photo_100'])
);

Constants

PEER_CHAT_ID_OFFSET

Offset value for chat peer IDs.
import { PEER_CHAT_ID_OFFSET } from 'vk-io';

console.log(PEER_CHAT_ID_OFFSET); // 2000000000

// Convert chat local ID to peer ID
const chatId = 1;
const peerId = PEER_CHAT_ID_OFFSET + chatId;
// peerId = 2000000001
VK uses 2,000,000,000 as the base offset for chat IDs. Local chat ID 1 becomes peer ID 2000000001.

Build docs developers (and LLMs) love