Skip to main content

Contexts

Context classes represent different types of VK events and updates. All contexts extend the base Context class and provide type-safe access to event data.

Base Context Class

The foundational class for all event contexts.

Properties

type
string
The context type (e.g., ‘message’, ‘message_event’, ‘wall_post’)
subTypes
string[]
Array of sub-types (e.g., [‘message_new’], [‘message_edit’])
state
S
Custom state object for storing data across middleware
$groupId
number | undefined
Group ID for group events

Methods

is(types)

Checks if the context matches any of the specified types or sub-types.
types
(Type | SubType)[]
required
Array of types to check against
if (context.is(['message', 'message_new'])) {
  // Handle message
}
Returns: boolean

toJSON()

Returns JSON representation of the context. Returns: object

MessageContext

Represents an incoming or outgoing message.

Type

  • type: 'message'
  • subTypes: 'message_new' | 'message_edit' | 'message_reply' | event types

Properties

id
number
Message ID
conversationMessageId
number
Message ID within the conversation
peerId
number
Destination ID (user, chat, or community)
senderId
number
Sender ID
text
string | undefined
Message text
createdAt
number
Message timestamp
isOutbox
boolean
Whether the message is outgoing
isImportant
boolean
Whether the message is marked as important
hasText
boolean
Whether the message has text
hasReplyMessage
boolean
Whether the message is a reply
hasForwards
boolean
Whether the message has forwarded messages
hasMessagePayload
boolean
Whether the message has a payload
hasGeo
boolean
Whether the message has geolocation
isChat
boolean
Whether the message is from a chat
isUser
boolean
Whether the sender is a user
isGroup
boolean
Whether the sender is a group
isEvent
boolean
Whether this is a service message (chat event)
eventType
MessageContextPayloadEventType | undefined
Event type for service messages
eventMemberId
number | undefined
User ID involved in the event
eventText
string | undefined
Event text (e.g., new chat title)
attachments
(Attachment | ExternalAttachment)[]
Message attachments
forwards
MessageForwardsCollection
Forwarded messages collection
replyMessage
MessageContext | undefined
Reply message context
messagePayload
any
Message payload (from keyboards)
geo
object | undefined
Geolocation data
$match
RegExpMatchArray
Regex match result (from hear middleware)

Methods

loadMessagePayload(options?)

Loads full message data from VK API if not already loaded.
options.force
boolean
default:"false"
Force reload even if already loaded
await message.loadMessagePayload();
console.log(message.attachments);
Returns: Promise<void>

send(text, params?)

Sends a message to the same conversation.
text
string | IMessageContextSendOptions
required
Message text or options object
params
IMessageContextSendOptions
Additional send parameters
await context.send('Hello!');

await context.send('Hello!', {
  attachment: 'photo123_456',
  keyboard: Keyboard.builder()
    .textButton({ label: 'Button' })
    .toString(),
});

await context.send({
  message: 'Hello!',
  sticker_id: 123,
});
Returns: Promise<MessageContext>

reply(text, params?)

Replies to the message.
text
string | IMessageContextSendOptions
required
Reply text or options object
params
IMessageContextSendOptions
Additional send parameters
await context.reply('This is a reply');
Returns: Promise<MessageContext>

sendSticker(stickerId)

Sends a sticker to the conversation.
stickerId
number
required
Sticker ID
await context.sendSticker(123);
Returns: Promise<MessageContext>

sendPhoto(source, params?)

Uploads and sends a photo.
source
IUploadSourceMedia
required
Photo source (file path, buffer, stream, or URL)
params
IMessageContextSendOptions
Additional send parameters
await context.sendPhoto('./photo.jpg', {
  message: 'Check this out!',
});
Returns: Promise<MessageContext>

sendDocument(source, params?)

Uploads and sends a document.
source
IUploadSourceMedia
required
Document source
params
IMessageContextSendOptions
Additional send parameters
Returns: Promise<MessageContext>

sendAudioMessage(source, params?)

Uploads and sends a voice message.
source
IUploadSourceMedia
required
Audio source (must be OGG format)
params
IMessageContextSendOptions
Additional send parameters
Returns: Promise<MessageContext>

markAsRead()

Marks the message as read.
await context.markAsRead();
Returns: Promise<1>

editMessage(options)

Edits the message (only for messages sent by the bot).
options
object
required
Edit parameters (message, attachment, keyboard, etc.)
await context.editMessage({
  message: 'Updated text',
});
Returns: Promise<1>

deleteMessage(options?)

Deletes the message.
options
object
Delete options (spam, delete_for_all)
await context.deleteMessage({ delete_for_all: 1 });
Returns: Promise<1>

renameChat(title)

Renames the chat (only works in chats).
title
string
required
New chat title
Returns: Promise<1>

setActivity()

Sets “typing” activity in the conversation.
await context.setActivity();
Returns: Promise<1>

IMessageContextSendOptions

Usage Example

import { MessageContext } from 'vk-io';

vk.updates.on('message_new', async (context: MessageContext) => {
  if (context.hasText && context.text === '/start') {
    await context.send('Welcome!', {
      keyboard: Keyboard.builder()
        .textButton({ label: 'Help' })
        .toString(),
    });
  }

  if (context.hasAttachments) {
    for (const attachment of context.attachments) {
      if (attachment.type === 'photo') {
        console.log('Received photo:', attachment.toString());
      }
    }
  }

  if (context.hasReplyMessage) {
    await context.send('Thanks for replying!');
  }
});

MessageEventContext

Represents a callback button click event.

Type

  • type: 'message_event'
  • subTypes: 'message_event'

Properties

userId
number
User ID who clicked the button
peerId
number
Conversation ID
conversationMessageId
number
Message ID within the conversation
eventId
string
Event ID (valid for 1 minute)
eventPayload
any
Button payload

Methods

answer(eventData)

Sends an event answer (shows snackbar, opens link, or opens app).
eventData
MessageEventAction
required
Event action to perform
// Show snackbar
await context.answer({
  type: 'show_snackbar',
  text: 'Button clicked!',
});

// Open link
await context.answer({
  type: 'open_link',
  link: 'https://example.com',
});

// Open VK app
await context.answer({
  type: 'open_app',
  app_id: 123,
  hash: 'navigation',
});
Returns: Promise<1>

send(text, params?)

Sends a message to the conversation.
text
string | IMessageContextSendOptions
required
Message text or options
Returns: Promise<MessageContext>

MessageEventAction Types

Usage Example

import { MessageEventContext } from 'vk-io';

vk.updates.on('message_event', async (context: MessageEventContext) => {
  const { eventPayload } = context;

  if (eventPayload.action === 'like') {
    await context.answer({
      type: 'show_snackbar',
      text: 'Thanks for liking!',
    });
  }

  if (eventPayload.action === 'buy') {
    await context.answer({
      type: 'open_link',
      link: 'https://shop.example.com',
    });
  }
});

WallPostContext

Represents a wall post event.

Type

  • type: 'wall_post'
  • subTypes: 'wall_post_new' | 'wall_repost'

Properties

id
number
Post ID
ownerId
number
Wall owner ID
fromId
number
Author ID
createdAt
number
Post timestamp
text
string
Post text
signerId
number | undefined
Signer ID (if signed)
attachments
(Attachment | ExternalAttachment)[]
Post attachments
isRepost
boolean
Whether the post is a repost

CommentContext

Represents a comment event (wall, photo, video, market).

Type

  • type: 'comment'
  • subTypes: Various comment types

Properties

id
number
Comment ID
ownerId
number
Owner ID
fromId
number
Author ID
text
string
Comment text
attachments
(Attachment | ExternalAttachment)[]
Comment attachments

Other Context Types

VK-IO provides many other context types:
  • TypingContext - User typing events
  • VoteContext - Poll vote events
  • GroupMemberContext - Group join/leave events
  • GroupUserContext - User block/unblock events
  • LikeContext - Like add/remove events
  • MarketOrderContext - Market order events
  • MessageFlagsContext - Message flag changes
  • MessagesReadContext - Message read receipts
  • NewAttachmentsContext - New attachments in chat
  • DialogFlagsContext - Dialog flag changes
  • FriendActivityContext - Friend online/offline
  • DonutSubscriptionContext - Donut subscription events
  • VKPayTransactionContext - VK Pay transaction events
  • VKAppPayloadContext - VK App events
All follow similar patterns with type-specific properties and methods.

Mixins

Some contexts include additional functionality through mixins:

Attachmentable Mixin

Contexts with attachments include these methods:

hasAttachments(type?)

Checks if the context has attachments.
type
AttachmentType | AttachmentTypeString
Optional attachment type to filter
if (context.hasAttachments()) {
  console.log('Has attachments');
}

if (context.hasAttachments('photo')) {
  console.log('Has photos');
}
Returns: boolean

getAttachments(type?)

Returns attachments, optionally filtered by type.
type
AttachmentType | AttachmentTypeString
Optional attachment type to filter
const photos = context.getAttachments('photo');
const videos = context.getAttachments('video');
Returns: Attachment[]

State Management

All contexts support a state property for passing data between middleware:
interface MyState {
  user?: User;
  language?: string;
}

vk.updates.on<MessageContext<MyState>>('message_new', async (context, next) => {
  context.state.user = await getUser(context.senderId);
  context.state.language = 'en';
  await next();
});

vk.updates.on<MessageContext<MyState>>('message_new', async (context) => {
  console.log(context.state.user); // Available here
});

Complete Example

import { VK, MessageContext, MessageEventContext, Keyboard } from 'vk-io';

const vk = new VK({ token: 'YOUR_TOKEN' });

vk.updates.on('message_new', async (context: MessageContext) => {
  if (context.text === '/start') {
    await context.send('Welcome!', {
      keyboard: Keyboard.builder()
        .callbackButton({
          label: 'Click me',
          payload: { action: 'greet' },
        })
        .toString(),
    });
  }

  if (context.hasAttachments('photo')) {
    const photos = context.getAttachments('photo');
    await context.send(`You sent ${photos.length} photo(s)`);
  }
});

vk.updates.on('message_event', async (context: MessageEventContext) => {
  if (context.eventPayload.action === 'greet') {
    await context.answer({
      type: 'show_snackbar',
      text: 'Hello from callback!',
    });
  }
});

vk.updates.start().catch(console.error);

Build docs developers (and LLMs) love