Giter Club home page Giter Club logo

node-vk-bot-api's Introduction

node-vk-bot-api node-vk-bot-api node-vk-bot-api

node-vk-bot-api

🤖 VK bot framework for Node.js, based on Bots Long Poll API and Callback API.

Install

$ npm i node-vk-bot-api -S

Usage

const VkBot = require('node-vk-bot-api');

const bot = new VkBot(process.env.TOKEN);

bot.command('/start', (ctx) => {
  ctx.reply('Hello!');
});

bot.startPolling();

Webhooks

const express = require('express');
const bodyParser = require('body-parser');
const VkBot = require('node-vk-bot-api');

const app = express();
const bot = new VkBot({
  token: process.env.TOKEN,
  confirmation: process.env.CONFIRMATION,
});

bot.on((ctx) => {
  ctx.reply('Hello!');
});

app.use(bodyParser.json());

app.post('/', bot.webhookCallback);

app.listen(process.env.PORT);

Examples

There's a few simple examples.

Community support

Any questions you can ask in the telegram chat. [russian/english]

Tests

$ npm test

API

const api = require('node-vk-bot-api/lib/api');

api('users.get', {
  user_ids: 1,
  access_token: process.env.TOKEN,
}); // => Promise

Error handling

// bad
bot.command('/start', (ctx) => {
  ctx.reply('Hello, world!');
});

// not bad
bot.command('/start', async (ctx) => {
  try {
    await ctx.reply('Hello, world!');
  } catch (e) {
    console.error(e);
  }
});

// good
bot.use(async (ctx, next) => {
  try {
    await next();
  } catch (e) {
    console.error(e);
  }
});

bot.command('/start', async (ctx) => {
  await ctx.reply('Hello, world!');
});
// bad
bot.startPolling();

// good
bot.startPolling((err) => {
  if (err) {
    console.error(err);
  }
});

Methods

constructor(settings)

Create bot.

// Simple usage
const bot = new VkBot(process.env.TOKEN);

// Advanced usage
const bot = new VkBot({
  token: process.env.TOKEN,
  group_id: process.env.GROUP_ID,
  execute_timeout: process.env.EXECUTE_TIMEOUT, // in ms   (50 by default)
  polling_timeout: process.env.POLLING_TIMEOUT, // in secs (25 by default)

  // webhooks options only
  secret: process.env.SECRET,                   // secret key (optional)
  confirmation: process.env.CONFIRMATION,       // confirmation string
});

.execute(method, settings)

Execute request to the VK API.

const response = await bot.execute('users.get', {
  user_ids: 1,
});

.use(middleware)

Add simple middleware.

bot.use((ctx, next) => {
  ctx.message.timestamp = new Date().getTime();

  return next();
});

.command(triggers, ...middlewares)

Add middlewares with triggers for message_new event.

bot.command('start', (ctx) => {
  ctx.reply('Hello!');
});

.event(triggers, ...middlewares)

Add middlewares with triggers for selected events.

bot.event('message_edit', (ctx) => {
  ctx.reply('Your message was editted');
});

.on(...middlewares)

Add reserved middlewares without triggers.

bot.on((ctx) => {
  ctx.reply('No commands for you.');
});

.sendMessage(userId, message, attachment, keyboard, sticker)

Send message to user.

// Simple usage
bot.sendMessage(145003487, 'Hello!', 'photo1_1');

// Multiple recipients
bot.sendMessage([145003487, 145003488], 'Hello!', 'photo1_1');

// Advanced usage
bot.sendMessage(145003487, {
  message: 'Hello!',
  lat: 59.939095,
  lng: 30.315868,
});

.startPolling([callback])

Start polling with optional callback.

bot.startPolling((err) => {
  if (err) {
    console.error(err);
  }
});

.webhookCallback(...args)

Get webhook callback.

// express
bot.webhookCallback(req, res, next);

// koa
bot.webhookCallback(ctx, next);

.stop()

Stop the bot. Disables any receiving updates from Long Poll or Callback APIs.

bot.stop();

.start()

Start the bot after it was turned off via .stop() method. When you are using Long Poll API, you need to call .startPolling([callback]) again.

bot.start();

Context Structure

  • message - received message (pure object from VK API)
    • type - received type event (e.g. message_new)
    • ... other fields from VK API
  • eventId - callback's eventId
  • groupId - callback's groupId
  • match? - regexp match of your trigger
  • clientInfo? - received client info (pure object from VK API)
  • bot - instance of bot, you can call any methods via this instance

Context Methods

.reply(message, attachment, markup, sticker)

Helper method for reply to the current user.

bot.command('start', (ctx) => {
  ctx.reply('Hello!');
});

Markup

Keyboards

  • Markup.keyboard(buttons, options): Create keyboard
  • Markup.button(label, color, payload): Create custom button
  • Markup.oneTime(): Set oneTime to keyboard

Simple usage

ctx.reply('Select your sport', null, Markup
  .keyboard([
    'Football',
    'Basketball',
  ])
  .oneTime(),
);

Advanced usage

// custom buttons
ctx.reply('Hey!', null, Markup
  .keyboard([
    Markup.button({
      action: {
        type: 'open_link',
        link: 'https://google.com',
        label: 'Open Google',
        payload: JSON.stringify({
          url: 'https://google.com',
        }),
      },
      color: 'default',
    }),
  ]),
);

// default buttons
ctx.reply('How are you doing?', null, Markup
  .keyboard([
    [
      Markup.button('Normally', 'primary'),
    ],
    [
      Markup.button('Fine', 'positive'),
      Markup.button('Bad', 'negative'),
    ],
  ]),
);

.keyboard(buttons, options)

Create keyboard with optional settings.

/*

  Each string has maximum 2 columns.

  | one   | two   |
  | three | four  |
  | five  | six   |

 */

Markup.keyboard([
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
], { columns: 2 });
/*

  By default, columns count for each string is 4.

  | one | two | three |

 */

Markup.keyboard([
  'one',
  'two',
  'three',
]);

.button(label, color, payload)

Create custom button.

Markup.button('Start', 'positive', {
  foo: 'bar',
});

.oneTime()

Helper method for create one time keyboard.

Markup
  .keyboard(['Start', 'Help'])
  .oneTime();

.inline()

Helpers method for create inline keyboard.

Markup
  .keyboard(['Start', 'Help'])
  .inline();

Sessions

Store anything for current user in local (or redis) memory.

Usage

const VkBot = require('node-vk-bot-api');
const Session = require('node-vk-bot-api/lib/session');

const bot = new VkBot(process.env.TOKEN);
const session = new Session();

bot.use(session.middleware());

bot.on((ctx) => {
  ctx.session.counter = ctx.session.counter || 0;
  ctx.session.counter++;

  ctx.reply(`You wrote ${ctx.session.counter} messages.`);
});

bot.startPolling();

API

Options

  • key: Context property name (default: session)
  • getSessionKey: Getter for session key
Default getSessionKey(ctx)
const getSessionKey = (ctx) => {
  const userId = ctx.message.from_id || ctx.message.user_id;

  return `${userId}:${userId}`;
};

Stage

Scene manager.

const VkBot = require('node-vk-bot-api');
const Scene = require('node-vk-bot-api/lib/scene');
const Session = require('node-vk-bot-api/lib/session');
const Stage = require('node-vk-bot-api/lib/stage');

const bot = new VkBot(process.env.TOKEN);
const scene = new Scene('meet',
  (ctx) => {
    ctx.scene.next();
    ctx.reply('How old are you?');
  },
  (ctx) => {
    ctx.session.age = +ctx.message.text;

    ctx.scene.next();
    ctx.reply('What is your name?');
  },
  (ctx) => {
    ctx.session.name = ctx.message.text;

    ctx.scene.leave();
    ctx.reply(`Nice to meet you, ${ctx.session.name} (${ctx.session.age} years old)`);
  },
);
const session = new Session();
const stage = new Stage(scene);

bot.use(session.middleware());
bot.use(stage.middleware());

bot.command('/meet', (ctx) => {
  ctx.scene.enter('meet');
});

bot.startPolling();

API

Stage

  • constructor(...scenes): Register scenes

Scene

  • constructor(name, ...middlewares): Create scene
  • .command(triggers, ...middlewares): Create commands for scene

Context

ctx.scene.enter(name, [step]) // Enter in scene
ctx.scene.leave()             // Leave from scene
ctx.scene.next()              // Go to the next step in scene
ctx.scene.step                // Getter for step in scene
ctx.scene.step=               // Setter for step in scene

License

MIT.

node-vk-bot-api's People

Contributors

antosik avatar arseniy-gl avatar bifot avatar chappa74 avatar deletedev avatar dependabot[bot] avatar handlerug avatar ibakaidov avatar kapturoff avatar khataev avatar miklergm avatar nocell avatar pelmeh avatar redguys avatar seitbekir avatar spb-web avatar vope avatar yegormy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-vk-bot-api's Issues

Дополнительные поля для messages.send

Я бы хотел добавить параметры:
disable_mentions
dont_parse_links
Добавьте возможность в reply. Или просто дайте пользователям указывать JSON объект со всеми возможными параметрами для messages.send

Или если это возможно, то объясните как.)

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

При создании несколько объектов Scene происходит ошибка
(node:21594) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined at Stage.enter (/home/gkulik/WebstormProjects/vk-capture-bot/src/lib/stage.js:15:50) at Object.enter (/home/gkulik/WebstormProjects/vk-capture-bot/src/lib/stage.js:46:26) at bot.on (/home/gkulik/WebstormProjects/vk-capture-bot/app.js:54:23) at fn (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/command.js:11:18) at VkBot.module.exports (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/next.js:21:14) at VkBot.module.exports (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/next.js:24:17) at middleware (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/use.js:5:43) at /home/gkulik/WebstormProjects/vk-capture-bot/src/lib/stage.js:70:13 at fn (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/use.js:5:16) at VkBot.module.exports (/home/gkulik/WebstormProjects/vk-capture-bot/node_modules/node-vk-bot-api/lib/methods/next.js:21:14) (node:21594) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:21594) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

bot not response longpool

Бот не отвечает при использовании longpoolapi:
При отправке боту вложения с записью типа wall, с вложениями более 6 фотографий...
Если отправить в сообщения сообществ эту, то не работает:https://vk.com/wall407487806_537
Событие не отслеживается даже тут: bot.on(ctx => {

});

Если отправить эту, то работает:https://vk.com/wall407487806_520
И событие отслеживается.

В вебхуках данный пример работает вне зависимости от количества вложений в отправленной записи типа wall.

Как сделать несколько Stages?

Пытаюсь так:

// Первый
const scene = new Scene("confirmation", //steps);

var stage = new Stage(scene)
bot.use(stage.middleware());

// Второй
const scene2 = new Scene("confirmation2", //steps);

var stage2 = new Stage(scene2)
bot.use(stage2.middleware());

В итоге первый работает нормально, второй останавливается после первого сообщения.
Шаги аналогичны.

Возможный порог лимита при отправке запроса

for (let i = 0, j = Math.ceil(calls.length / 25); i < j; i++) {
const code = calls
.slice(i * 25, i * 25 + 25)
.join(',');
api('execute', {
code: `return { ${code} };`,
access_token: token,
})

Теоретически, при очереди в 2000 методов, возможна ошибка rate limit, так как не все 40 запросов могут быть обработаны в одну секунду и некоторые перейдут на следующую, а так как прошлые не успели обработаться, они будут засчитаны в следующую секунду, где запросов будет больше 20, что и вызовет ошибку

Возможно баг с работой сцен

Привет. Рандомно случается баг, что у некоторых новых пользователей при начале общения с ботом появляются кнопки из более глубоких сцен (которые они не должны видеть пока не "дойдут" до этой сцены).
Вот пример (скрин ниже). Бот должен был ответить сообщением про "Спортейдж" (здесь нормально), вместе с этими кнопками https://github.com/nnqq/bot/blob/master/index.js#L14 , но на скрине видно что бот отправил другую кнопку из более "глубокой" сцены https://github.com/nnqq/bot/blob/master/index.js#L966

2019-01-06 14 44 32

Репозиторий бота: https://github.com/nnqq/bot

Проблема!

const scene = new Scene('meet',
(ctx) => {
ctx.scene.next()
ctx.reply('How old are you?')
},
(ctx) => {
ctx.session.age = +ctx.message.text

ctx.scene.next()
ctx.reply('What is your name?')

},
(ctx) => {
ctx.session.name = ctx.message.text

ctx.scene.leave()
ctx.reply(`Nice to meet you, ${ctx.session.name} (${ctx.session.age} years old)`)

},
)
const session = new Session()
const stage = new Stage(scene)

bot.use(session.middleware())
bot.use(stage.middleware())

bot.command('/meet', (ctx) => {
ctx.scene.enter('meet')
})

Скрипт не является рабочим! При записи в ctx.session.age и выводе (${ctx.session.age} ответ Nan или undefined! В чем причина. Переписывал,как только мог. Не работает.

Ошибка при попытке запуска

`node_modules/node-vk-bot-api/lib/index.js:18
Object.entries({ ...methods, api, callExecute }).forEach(([key, method]) => {
^^^

SyntaxError: Unexpected token ...
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)`

node.js - v.8.1.2

Помогите разобраться.
Заранее благодарен.

Обработка переводов денег

Как можно обработать перевод денег? Понимаю что можно через bot.on(), но там очень неудобно и не уверен что безопасно так делать. Есть ли способ более удобный?

How to use payload in buttons?

Can't to get a payload from button.
bot.command('start', (ctx) => { ctx.reply('Hello', null, Markup .keyboard([ [Markup.button('First', 'positive', {qwe: 'asd'})] ])) })

  1. Send message 'start'
  2. Press button "First"
    And I can't find my payload data.

ApiError, хотя всё выполнилось без ошибки

Два дня назад я столкнулся с проблемой описанной здесь: #92
Сегодня увидел, что пришло обновление 3.3.4, где она исправлена. На деле же, теперь вместо undefined выводит:
image
А сообщение отправляется. По факту: ошибка лишняя.

Единый контекст сцен на всех пользователей

При обращении к боту от разных пользователей контекст и состояние сцены не уникальное для каждого пользователя.
Полностью воспроизводится на примере работы со сценами

Для воспроизвдения необходимо 2 пользователя U1, U2 и бот:

U1-B -> /meet
B-U1 -> How old are you?
U2-B -> hello
B-U2 -> What Is your name?

Подобное поведение описано #35

Воспроизвел на версии 2.4.2 и 2.4.0

Cannot read property 'toLowerCase' of undefined

При попытке отписать какое-либо сообщение в группу на стороне сервера возникает ошибка

(node:2676) UnhandledPromiseRejectionWarning: Error: TypeError: Cannot read property 'toLowerCase' of undefined
at VkBot.module.exports (C:\Users\79520\Desktop\wf\lib\methods\startPolling.js:39:11)
at process._tickCallback (internal/process/next_tick.js:68:7)

Не работает bot.startPolling()

Не работает bot.startPolling() , бот не реагирует на команды.
Ошибок в консоли никаких не выводится
Получается только отправлять сообщения bot.sendMessage(id, 'DDD')

Номер версии API 5.8

в lib/api.js на 7й строчке
v: 5.80,
заменить на
v: '5.80',

Иначе получается версия 5.8 и методы многие не срабатывают

TypeError: Converting circular structure to JSON

Code:

const VkBot = require('node-vk-bot-api')

const bot = new VkBot("MYTOKENHERE");

bot.command('/start', (ctx) => {
  ctx.reply('Hello!')
})

bot.startPolling(() => {
  console.log('Bot started.')
})

Error:

(node:12168) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
at JSON.stringify ()
at VkBot.module.exports (C:\Users\Yaroslav\Desktop\bots\vk bot\node_modules\node-vk-bot-api\lib\api.js:17:43)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12168) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:12168) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Keyboard rewrite bug

Single context for every keyboard, so if you create two keyboards at the one moment then the first keyboard will be equal to the second.

This test failed:

image

Правильная версия API

По какой-то причине VK использует версию API из настроек паблика, а не из кода.

Пришлось долго разбираться, пока не выяснил, что надо и в самом паблике установить версию 8.40.

Мб написать это в инструкции?

Как использовать payload?

Я в кнопку еще пишу пейлоад Markup.button('Button1', 'default', "asd")
Как мне получить его при нажатии на кнопку?

(node:29740) UnhandledPromiseRejectionWarning: undefined

При каждом запуске бота и при попытке отправить сообщение, ловлю эту ошибку.
Пробовал скрыть это этой функцией - process.on('unhandledRejection', error => {
});
Но при любом catch'e у самого метода вк ловится эта херня.
image
До этого пользовался старой версией модуля 2.4.9 с ней все было нормально, но на ней не было inline кнопок.

connect ETIMEDOUT 87.240.129.132:443

Работает сначала нормально первые 5-10 минут, потом постоянно ошибка:
В чем проблема может быть? Это решил на сервер бота закинуть, локально все работало нормально.
Error: Error: connect ETIMEDOUT 87.240.129.132:443 at module.exports (/root/chat-bot/bot/node_modules/node-vk-bot-api/lib/api.js:17:11) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)

Получить ссылку на вложение

Когда пользователь присылает боту фотографию во вложении, то я могу получить только ее идентификатор.
Как получить ссылку на файл? Метод photos.getById нельзя вызвать с ключом сообщества (

Ограничения на сетку клавиатуры

Разрешенная сетка клавиатуры 4*10, при создании разметки можно передать массив названий кнопок, из него автоматически будет собрана клавиатура в один ряд.
Нет проверки на допустимый размер клавиатуры.

Using with serverless

Hi, how can I use bot API with serverless?
Can I somehow wrap your package?

Thanks.

LongPoll Circular Structure unhandled exception

При отсутствующем подключении к интернету в режиме LongPoll
Версия: 2.4.10

throw (typeof err === 'object' ? JSON.stringify(err) : err);

(node:10551) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at VkBot.module.exports (bot/node_modules/node-vk-bot-api/lib/api.js:17:43)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10551) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:10551) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Exceptions are suppressed in command handlers

When I am throwing exception (even manually) from command handler (picture below), it gets suppressed and not handled by Sentry, other ravenjs-library and even by try-catch code expression:

image 2019-02-03 18 08 38

It should be handled and logged or passed to global scope handler (if exists).

Бот отвечает несколько раз.

bot.command('Начать', (ctx) => { ctx.reply('Hello!') })

Ввожу "Начать"
Бот отправляет 2 сообщения "Hello", бывает и больше.
В чем проблема может быть?

Проблема с Markup (клавиатурами).

package.json

"node-vk-bot-api": "^3.3.3"

index.js

const VkBot = require('node-vk-bot-api')
const Markup = require('node-vk-bot-api/lib/markup')
require('dotenv').config()

const bot = new VkBot(process.env.TOKEN)

bot.command('/start', ctx => {
  ctx.reply({
    message: 'Hello, world!',
    keyboard: Markup.keyboard(['foo', 'bar']).toJSON()
  })
})

bot.startPolling()

Console output

(node:16312) UnhandledPromiseRejectionWarning: #<Object>
(node:16312) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16312) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Пробовал try / catch, тот же output.
Пробовал код из примера, та же ошибка.

Проблема при обработке событий без поля text

Привет, пытался повесить на бота обработку события при подписке на группу (group_join), но бот никак не реагировал

 bot.event('group_join', (ctx) => {
       console.log('Im get group_join event')
 });

Порылся в исходниках, заметил, что при получении данного события вылетает на этом моменте:
./lib/methods/next.js:4

const message = ctx.message.text.toLowerCase()

посмотрел тело сообщения, которое приходит от vk, в нем отсутствует поле text как таковое,

{ user_id: id, join_type: 'join', type: 'group_join' }

пришлось добавить проверку на наличие text, так же, в данном случае не сработает ctx.reply('text'), поскольку поле peer_id заменено полем user_id, впрочем, здесь обошелся методом bot.send

Проверьте, пожалуйста.

UnhandledPromiseRejectionWarning: Error: ApiError

День не могу разобраться. Что не так?
Скрипт:

const VkBot = require('node-vk-bot-api')
var token = 'тутТокен';

const bot = new VkBot(token)

bot.on((ctx) => {
    var message = ctx.message.body;
    ctx.reply(message);
});

bot.startPolling()

Ответ при запуске:

[nodemon] starting `node index.js`
(node:10625) UnhandledPromiseRejectionWarning: Error: Request failed with status code 504
    at createError (/Users/markmoyseev/Documents/js/samp/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/Users/markmoyseev/Documents/js/samp/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/Users/markmoyseev/Documents/js/samp/node_modules/axios/lib/adapters/http.js:236:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1201:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:10625) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:10625) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Не работает дефолтная клава

код
ctx.reply('Hey!', null, Markup
.keyboard([
Markup.button({
action: {
type: 'open_link',
link: 'https://google.com',
label: 'Open Google',
payload: JSON.stringify({
url: 'https://google.com',
}),
},
color: 'default',
}),
]),
);
ошибка
(node:13512) UnhandledPromiseRejectionWarning: #
(node:13512) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13512) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Object Markup.

I included this module in my js application.

Please tell me what kind of object in your example is Markup?

Markup.keyboard(buttons, options): Create keyboard
Markup.button(label, color, payload): Create custom button
Markup.oneTime(): Set oneTime to keyboard

Where can i getting this object ?

Can't find a way to access reply_message // Как использовать ответ на сообщение?

There is a property of message object called "reply_message", listed in VK API. You can assign a message object to it to specify to which message bot is replying, However, I can't find a way to use this functionality in the bot API, because it seems that everything you provide in sendMessage method is interpreted as an attachment,

Во вконтактовском API указано свойство объекта сообщения "reply_message", которому можно присвоить объект сообщения, на которое бот отвечает. Не могу найти возможность использовать этот функционал в API бота, поскольку все, что передаешь в метод sendMessage воспринимается как attachment.

Node-Red support

Dear team

could you pls port this module to node-red? We are using node-red and can not use use node-vk-bot-api in node-red.

ctx.reply не отправит клавиатуру если передать сообщение как объект

При вызове ctx.reply с объектом первым аргументом, клавиатура просто не попадает в конечный execute, а вырезается в либе где то по дороге

ctx.reply({
  message: 'Test',
  dont_parse_links: 1,
}, null, Markup.keyboard(['Never appear']));

Сообщение будет валидно отправлено, но без клавиатуры потому что ее нету в execute

Сообщения вне коллбеков

Привет, хочу делать рассылку по времени.
В апи есть соллбеки и ответ шлется только на приходящее сообщение.
Вне коллбеков отправить сообщение через bot.execute?
Можно пример вызова описать для этого метода?

Rename package

"node" need to be removed from the package name. Ref: https://docs.npmjs.com/files/package.json#name

Don’t put “js” or “node” in the name. It’s assumed that it’s js, since you’re writing a package.json file, and you can specify the engine using the “engines” field. (See below.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.