{"id":15017589,"url":"https://github.com/node-vk-bot-api/node-vk-bot-api","last_synced_at":"2025-04-04T22:01:48.250Z","repository":{"id":32808791,"uuid":"87635447","full_name":"node-vk-bot-api/node-vk-bot-api","owner":"node-vk-bot-api","description":"🤖 VK bot framework for Node.js, based on Bots Long Poll API and Callback API.","archived":false,"fork":false,"pushed_at":"2022-10-23T15:57:49.000Z","size":286,"stargazers_count":245,"open_issues_count":26,"forks_count":69,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-03-28T21:01:34.119Z","etag":null,"topics":["api","bot","bot-framework","bots","vk","vk-api","vk-bot","vk-sdk","vkontakte","vkontakte-sdk"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/node-vk-bot-api","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/node-vk-bot-api.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-04-08T13:23:04.000Z","updated_at":"2025-03-20T20:56:18.000Z","dependencies_parsed_at":"2023-01-14T22:18:20.015Z","dependency_job_id":null,"html_url":"https://github.com/node-vk-bot-api/node-vk-bot-api","commit_stats":{"total_commits":124,"total_committers":22,"mean_commits":5.636363636363637,"dds":0.6693548387096775,"last_synced_commit":"f77c7125fd6553d1007fa28809d3783a1559ad99"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-vk-bot-api%2Fnode-vk-bot-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-vk-bot-api%2Fnode-vk-bot-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-vk-bot-api%2Fnode-vk-bot-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-vk-bot-api%2Fnode-vk-bot-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/node-vk-bot-api","download_url":"https://codeload.github.com/node-vk-bot-api/node-vk-bot-api/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247256101,"owners_count":20909240,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","bot","bot-framework","bots","vk","vk-api","vk-bot","vk-sdk","vkontakte","vkontakte-sdk"],"created_at":"2024-09-24T19:50:43.382Z","updated_at":"2025-04-04T22:01:48.230Z","avatar_url":"https://github.com/node-vk-bot-api.png","language":"JavaScript","readme":"[![node-vk-bot-api](https://img.shields.io/npm/v/node-vk-bot-api.svg?style=flat-square)](https://www.npmjs.com/package/node-vk-bot-api/)\n![node-vk-bot-api](https://img.shields.io/badge/code%20style-airbnb-brightgreen.svg?style=flat-square)\n![node-vk-bot-api](https://img.shields.io/travis/node-vk-bot-api/node-vk-bot-api.svg?branch=master\u0026style=flat-square)\n\n# node-vk-bot-api\n\n🤖 VK bot framework for Node.js, based on [Bots Long Poll API](https://vk.com/dev/bots_longpoll) and [Callback API](https://vk.com/dev.php?method=callback_api).\n\n## Install\n\n```sh\n$ npm i node-vk-bot-api -S\n```\n\n## Usage\n\n```javascript\nconst VkBot = require('node-vk-bot-api');\n\nconst bot = new VkBot(process.env.TOKEN);\n\nbot.command('/start', (ctx) =\u003e {\n  ctx.reply('Hello!');\n});\n\nbot.startPolling();\n```\n\n## Webhooks\n\n```javascript\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst VkBot = require('node-vk-bot-api');\n\nconst app = express();\nconst bot = new VkBot({\n  token: process.env.TOKEN,\n  confirmation: process.env.CONFIRMATION,\n});\n\nbot.on((ctx) =\u003e {\n  ctx.reply('Hello!');\n});\n\napp.use(bodyParser.json());\n\napp.post('/', bot.webhookCallback);\n\napp.listen(process.env.PORT);\n```\n\n## Examples\n\n[There's a few simple examples.](/examples)\n\n## Community support\n\nAny questions you can ask in the [telegram chat](https://tele.click/joinchat/BXuo0kxMRNVyfdKKjMHpQQ). [russian/english]\n\n## Tests\n\n```sh\n$ npm test\n```\n\n\n## API\n\n```js\nconst api = require('node-vk-bot-api/lib/api');\n\napi('users.get', {\n  user_ids: 1,\n  access_token: process.env.TOKEN,\n}); // =\u003e Promise\n```\n\n## Error handling\n\n```js\n// bad\nbot.command('/start', (ctx) =\u003e {\n  ctx.reply('Hello, world!');\n});\n\n// not bad\nbot.command('/start', async (ctx) =\u003e {\n  try {\n    await ctx.reply('Hello, world!');\n  } catch (e) {\n    console.error(e);\n  }\n});\n\n// good\nbot.use(async (ctx, next) =\u003e {\n  try {\n    await next();\n  } catch (e) {\n    console.error(e);\n  }\n});\n\nbot.command('/start', async (ctx) =\u003e {\n  await ctx.reply('Hello, world!');\n});\n```\n\n```js\n// bad\nbot.startPolling();\n\n// good\nbot.startPolling((err) =\u003e {\n  if (err) {\n    console.error(err);\n  }\n});\n```\n\n## Methods\n\n* [constructor(settings)](#constructorsettings)\n* [.execute(method, settings)](#executemethod-settings)\n* [.use(middleware)](#usemiddleware)\n* [.command(triggers, ...middlewares)](#commandtriggers-middlewares)\n* [.event(triggers, ...middlewares)](#eventtriggers-middlewares)\n* [.on(...middlewares)](#onmiddlewares)\n* [.sendMessage(userId, message, attachment, keyboard, sticker)](#sendmessageuserid-message-attachment-keyboard-sticker)\n* [.startPolling([callback])](#startpollingcallback)\n* [.webhookCallback(...args)](#webhookcallbackargs)\n* [.stop()](#stop)\n* [.start()](#start)\n\n### constructor(settings)\n\nCreate bot.\n\n```javascript\n// Simple usage\nconst bot = new VkBot(process.env.TOKEN);\n\n// Advanced usage\nconst bot = new VkBot({\n  token: process.env.TOKEN,\n  group_id: process.env.GROUP_ID,\n  execute_timeout: process.env.EXECUTE_TIMEOUT, // in ms   (50 by default)\n  polling_timeout: process.env.POLLING_TIMEOUT, // in secs (25 by default)\n\n  // webhooks options only\n  secret: process.env.SECRET,                   // secret key (optional)\n  confirmation: process.env.CONFIRMATION,       // confirmation string\n});\n```\n\n### .execute(method, settings)\n\nExecute request to the VK API.\n\n```js\nconst response = await bot.execute('users.get', {\n  user_ids: 1,\n});\n``` \n\n### .use(middleware)\n\nAdd simple middleware.\n\n```javascript\nbot.use((ctx, next) =\u003e {\n  ctx.message.timestamp = new Date().getTime();\n\n  return next();\n});\n```\n\n### .command(triggers, ...middlewares)\n\nAdd middlewares with triggers for `message_new` event.\n\n```javascript\nbot.command('start', (ctx) =\u003e {\n  ctx.reply('Hello!');\n});\n```\n\n### .event(triggers, ...middlewares)\n\nAdd middlewares with triggers for selected events.\n\n```javascript\nbot.event('message_edit', (ctx) =\u003e {\n  ctx.reply('Your message was editted');\n});\n```\n\n### .on(...middlewares)\n\nAdd reserved middlewares without triggers.\n\n```javascript\nbot.on((ctx) =\u003e {\n  ctx.reply('No commands for you.');\n});\n```\n\n### .sendMessage(userId, message, attachment, keyboard, sticker)\n\nSend message to user.\n\n```javascript\n// Simple usage\nbot.sendMessage(145003487, 'Hello!', 'photo1_1');\n\n// Multiple recipients\nbot.sendMessage([145003487, 145003488], 'Hello!', 'photo1_1');\n\n// Advanced usage\nbot.sendMessage(145003487, {\n  message: 'Hello!',\n  lat: 59.939095,\n  lng: 30.315868,\n});\n```\n\n### .startPolling([callback])\n\nStart polling with optional callback.\n\n```js\nbot.startPolling((err) =\u003e {\n  if (err) {\n    console.error(err);\n  }\n});\n```\n\n### .webhookCallback(...args)\n\nGet webhook callback.\n\n```js\n// express\nbot.webhookCallback(req, res, next);\n\n// koa\nbot.webhookCallback(ctx, next);\n```\n\n### .stop()\n\nStop the bot. Disables any receiving updates from Long Poll or Callback APIs.\n\n```js\nbot.stop();\n```\n\n### .start()\n\nStart the bot after it was turned off via [.stop()](#stop) method. When you are using Long Poll API, you need to call [`.startPolling([callback])`](#startpollingcallback) again.\n\n```js\nbot.start();\n```\n\n## Context Structure\n\n* `message` - received message (pure object from VK API)\n    * `type` - received type event (e.g. message_new)\n    * ... other fields from VK API\n* `eventId` - callback's eventId\n* `groupId` - callback's groupId\n* `match?` - regexp match of your trigger\n* `clientInfo?` - received client info (pure object from VK API)\n* `bot` - instance of bot, you can call any methods via this instance\n\n## Context Methods\n\n* [.reply(message, attachment, markup, sticker)](#replymessage-attachment-keyboard-sticker)\n\n### .reply(message, attachment, markup, sticker)\n\nHelper method for reply to the current user.\n\n```javascript\nbot.command('start', (ctx) =\u003e {\n  ctx.reply('Hello!');\n});\n```\n\n## Markup\n\n### Keyboards\n\n* `Markup.keyboard(buttons, options)`: Create keyboard\n* `Markup.button(label, color, payload)`: Create custom button\n* `Markup.oneTime()`: Set oneTime to keyboard\n\n#### Simple usage\n\n```js\nctx.reply('Select your sport', null, Markup\n  .keyboard([\n    'Football',\n    'Basketball',\n  ])\n  .oneTime(),\n);\n```\n\n#### Advanced usage\n\n```js\n// custom buttons\nctx.reply('Hey!', null, Markup\n  .keyboard([\n    Markup.button({\n      action: {\n        type: 'open_link',\n        link: 'https://google.com',\n        label: 'Open Google',\n        payload: JSON.stringify({\n          url: 'https://google.com',\n        }),\n      },\n      color: 'default',\n    }),\n  ]),\n);\n\n// default buttons\nctx.reply('How are you doing?', null, Markup\n  .keyboard([\n    [\n      Markup.button('Normally', 'primary'),\n    ],\n    [\n      Markup.button('Fine', 'positive'),\n      Markup.button('Bad', 'negative'),\n    ],\n  ]),\n);\n```\n\n### .keyboard(buttons, options)\n\nCreate keyboard with optional settings.\n\n```js\n/*\n\n  Each string has maximum 2 columns.\n\n  | one   | two   |\n  | three | four  |\n  | five  | six   |\n\n */\n\nMarkup.keyboard([\n  'one',\n  'two',\n  'three',\n  'four',\n  'five',\n  'six',\n], { columns: 2 });\n```\n\n```js\n/*\n\n  By default, columns count for each string is 4.\n\n  | one | two | three |\n\n */\n\nMarkup.keyboard([\n  'one',\n  'two',\n  'three',\n]);\n```\n\n### .button(label, color, payload)\n\nCreate custom button.\n\n```js\nMarkup.button('Start', 'positive', {\n  foo: 'bar',\n});\n```\n\n### .oneTime()\n\nHelper method for create one time keyboard.\n\n```js\nMarkup\n  .keyboard(['Start', 'Help'])\n  .oneTime();\n```\n\n### .inline()\n\nHelpers method for create inline keyboard.\n\n```js\nMarkup\n  .keyboard(['Start', 'Help'])\n  .inline();\n```\n\n## Sessions\n\nStore anything for current user in local (or [redis](https://github.com/node-vk-bot-api/node-vk-bot-api-session-redis)) memory.\n\n### Usage\n\n```javascript\nconst VkBot = require('node-vk-bot-api');\nconst Session = require('node-vk-bot-api/lib/session');\n\nconst bot = new VkBot(process.env.TOKEN);\nconst session = new Session();\n\nbot.use(session.middleware());\n\nbot.on((ctx) =\u003e {\n  ctx.session.counter = ctx.session.counter || 0;\n  ctx.session.counter++;\n\n  ctx.reply(`You wrote ${ctx.session.counter} messages.`);\n});\n\nbot.startPolling();\n```\n\n### API\n\n#### Options\n\n* `key`: Context property name (default: `session`)\n* `getSessionKey`: Getter for session key\n\n##### Default `getSessionKey(ctx)`\n\n```js\nconst getSessionKey = (ctx) =\u003e {\n  const userId = ctx.message.from_id || ctx.message.user_id;\n\n  return `${userId}:${userId}`;\n};\n````\n\n## Stage\n\nScene manager.\n```javascript\nconst VkBot = require('node-vk-bot-api');\nconst Scene = require('node-vk-bot-api/lib/scene');\nconst Session = require('node-vk-bot-api/lib/session');\nconst Stage = require('node-vk-bot-api/lib/stage');\n\nconst bot = new VkBot(process.env.TOKEN);\nconst scene = new Scene('meet',\n  (ctx) =\u003e {\n    ctx.scene.next();\n    ctx.reply('How old are you?');\n  },\n  (ctx) =\u003e {\n    ctx.session.age = +ctx.message.text;\n\n    ctx.scene.next();\n    ctx.reply('What is your name?');\n  },\n  (ctx) =\u003e {\n    ctx.session.name = ctx.message.text;\n\n    ctx.scene.leave();\n    ctx.reply(`Nice to meet you, ${ctx.session.name} (${ctx.session.age} years old)`);\n  },\n);\nconst session = new Session();\nconst stage = new Stage(scene);\n\nbot.use(session.middleware());\nbot.use(stage.middleware());\n\nbot.command('/meet', (ctx) =\u003e {\n  ctx.scene.enter('meet');\n});\n\nbot.startPolling();\n```\n\n### API\n\n#### Stage\n\n* `constructor(...scenes)`: Register scenes\n\n#### Scene\n\n* `constructor(name, ...middlewares)`: Create scene\n* `.command(triggers, ...middlewares)`: Create commands for scene\n\n#### Context\n\n```js\nctx.scene.enter(name, [step]) // Enter in scene\nctx.scene.leave()             // Leave from scene\nctx.scene.next()              // Go to the next step in scene\nctx.scene.step                // Getter for step in scene\nctx.scene.step=               // Setter for step in scene\n```\n\n## License\n\nMIT.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-vk-bot-api%2Fnode-vk-bot-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnode-vk-bot-api%2Fnode-vk-bot-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-vk-bot-api%2Fnode-vk-bot-api/lists"}