vk-bot-api
Advanced tools
Comparing version 1.3.1 to 1.4.0
254
lib/vk.js
'use strict'; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
@@ -15,2 +13,3 @@ | ||
/* eslint-disable camelcase */ | ||
require('babel-polyfill'); | ||
@@ -40,3 +39,3 @@ var EventEmitter = require('eventemitter3'); | ||
* Например, если указать [1, 2e9+12], то бот будет отвечать только на сообщения Дурова и чата #12 | ||
* @param {String | RegExp | Array} options.prefix Имя бота, с которого должны начинаться сообщения. | ||
* @param {RegExp} options.prefix Имя бота, с которого должны начинаться сообщения. | ||
* Если не указывать, то будет отвечать на все сообщения. Может быть: Строкой, Регулярным выражением, Массивом | ||
@@ -55,3 +54,3 @@ * со строками и регулярными выражениями | ||
_ref$prefix = _ref.prefix, | ||
prefix = _ref$prefix === undefined ? '' : _ref$prefix, | ||
prefix = _ref$prefix === undefined ? false : _ref$prefix, | ||
_ref$timeout = _ref.timeout, | ||
@@ -62,3 +61,5 @@ timeout = _ref$timeout === undefined ? 5000 : _ref$timeout, | ||
_ref$prefixOnlyForGro = _ref.prefixOnlyForGroups, | ||
prefixOnlyForGroups = _ref$prefixOnlyForGro === undefined ? false : _ref$prefixOnlyForGro; | ||
prefixOnlyForGroups = _ref$prefixOnlyForGro === undefined ? false : _ref$prefixOnlyForGro, | ||
_ref$LPMessages = _ref.LPMessages, | ||
LPMessages = _ref$LPMessages === undefined ? false : _ref$LPMessages; | ||
@@ -76,2 +77,4 @@ _classCallCheck(this, VkBot); | ||
_this.msgtype = LPMessages ? 1 : 0; | ||
_this.API = new APIcaller({ token: token, v: v, timeout: timeout }); | ||
@@ -86,4 +89,6 @@ _this.lp = new LongPoll(_this.API, 25, _this.processUpdate.bind(_this)); | ||
var _ref2 = _asyncToGenerator(regeneratorRuntime.mark(function _callee(update) { | ||
var checkPrefix, isChat, answered, _msg, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, reg, result, _msg2, _msg3, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, _reg, _result; | ||
var _this2 = this; | ||
var checkPrefix, getMsg, isChat, chatId, msgId, body, extra, handled, msg, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, r, result, _msg, _msg2, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, _r, _result; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
@@ -94,48 +99,53 @@ while (1) { | ||
checkPrefix = function checkPrefix(text, prefix) { | ||
var toReturn = false; | ||
return text.search(prefix) === 0; | ||
}; | ||
if (Array.isArray(prefix)) { | ||
prefix.forEach(function (value) { | ||
if (typeof value === 'string') { | ||
if (text.toLowerCase().startsWith(value)) toReturn = true; | ||
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { | ||
if (text.search(value) === 0) toReturn = true; | ||
} | ||
return false; | ||
}); | ||
} else if (typeof prefix === 'string') { | ||
if (text.toLowerCase().startsWith(prefix)) toReturn = true; | ||
} else if ((typeof prefix === 'undefined' ? 'undefined' : _typeof(prefix)) === 'object') { | ||
if (text.search(prefix) === 0) toReturn = true; | ||
} | ||
return toReturn; | ||
getMsg = function getMsg(message_ids) { | ||
return _this2.API.call('messages.getById', { message_ids: message_ids }).then(function (res) { | ||
return res.items[0]; | ||
}); | ||
}; | ||
isChat = update[3] > 2e9; | ||
answered = false; | ||
chatId = update[3]; | ||
msgId = update[1]; | ||
body = update[6]; | ||
extra = update[7]; | ||
handled = false; | ||
if (!(isChat && (!this.chats.length || this.chats.includes(update[3]) | ||
// для чатов | ||
if (!(isChat && (!this.chats.length || this.chats.includes(chatId) | ||
// чатов нет ^ чат в списке разрешенных ^ | ||
) && (!this.prefix || checkPrefix(update[6], this.prefix) | ||
) && (!this.prefix || checkPrefix(body, this.prefix) | ||
// ^ префикса нет ^ начинается с префикса | ||
))) { | ||
_context.next = 31; | ||
_context.next = 40; | ||
break; | ||
} | ||
_context.next = 6; | ||
return this.API.call('messages.getById', { | ||
// получаем расширенную информацию о сообщении | ||
message_ids: update[1] | ||
}); | ||
if (!this.msgtype) { | ||
_context.next = 13; | ||
break; | ||
} | ||
case 6: | ||
_msg = _context.sent; | ||
_context.t0 = update; | ||
_context.next = 16; | ||
break; | ||
_msg = _msg.items[0]; | ||
this.emit('message', _msg); // сообщаем о сообщении | ||
case 13: | ||
_context.next = 15; | ||
return getMsg(msgId); | ||
if (!_msg.body) { | ||
_context.next = 29; | ||
case 15: | ||
_context.t0 = _context.sent; | ||
case 16: | ||
msg = _context.t0; | ||
this.emit('message', msg); | ||
if (!body) { | ||
_context.next = 38; | ||
break; | ||
@@ -147,24 +157,26 @@ } | ||
_iteratorError = undefined; | ||
_context.prev = 13; | ||
_context.prev = 22; | ||
for (_iterator = this.textRegexpCallbacks[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
reg = _step.value; | ||
result = reg.regexp.exec(_msg.body); | ||
r = _step.value; | ||
result = r.regexp.exec(body); | ||
if (result) { | ||
answered = true;reg.callback(_msg, result); | ||
handled = true; | ||
r.callback(msg, result); | ||
} | ||
if (!handled) this.emit('unhandled', msg); | ||
} | ||
_context.next = 21; | ||
_context.next = 30; | ||
break; | ||
case 17: | ||
_context.prev = 17; | ||
_context.t0 = _context['catch'](13); | ||
case 26: | ||
_context.prev = 26; | ||
_context.t1 = _context['catch'](22); | ||
_didIteratorError = true; | ||
_iteratorError = _context.t0; | ||
_iteratorError = _context.t1; | ||
case 21: | ||
_context.prev = 21; | ||
_context.prev = 22; | ||
case 30: | ||
_context.prev = 30; | ||
_context.prev = 31; | ||
@@ -175,7 +187,7 @@ if (!_iteratorNormalCompletion && _iterator.return) { | ||
case 24: | ||
_context.prev = 24; | ||
case 33: | ||
_context.prev = 33; | ||
if (!_didIteratorError) { | ||
_context.next = 27; | ||
_context.next = 36; | ||
break; | ||
@@ -186,55 +198,75 @@ } | ||
case 27: | ||
return _context.finish(24); | ||
case 36: | ||
return _context.finish(33); | ||
case 28: | ||
return _context.finish(21); | ||
case 37: | ||
return _context.finish(30); | ||
case 29: | ||
_context.next = 65; | ||
case 38: | ||
_context.next = 82; | ||
break; | ||
case 31: | ||
if (!(isChat && (!this.chats.length || this.chats.includes(update[3])) && update[7].source_act // если сообщение специальное | ||
case 40: | ||
if (!( // для спец.сообщений типа создания чата или изменения его названия | ||
isChat && (!this.chats.length || this.chats.includes(chatId)) && extra.source_act // если сообщение специальное | ||
)) { | ||
_context.next = 39; | ||
_context.next = 52; | ||
break; | ||
} | ||
_context.next = 34; | ||
return this.API.call('messages.getById', { | ||
// получаем расширенную информацию о сообщении | ||
message_ids: update[1] | ||
}); | ||
if (!this.msgtype) { | ||
_context.next = 45; | ||
break; | ||
} | ||
case 34: | ||
_msg2 = _context.sent; | ||
_context.t2 = update; | ||
_context.next = 48; | ||
break; | ||
_msg2 = _msg2.items[0]; | ||
this.emit(_msg2.action, _msg2); | ||
_context.next = 65; | ||
case 45: | ||
_context.next = 47; | ||
return getMsg(msgId); | ||
case 47: | ||
_context.t2 = _context.sent; | ||
case 48: | ||
_msg = _context.t2; | ||
this.emit(extra.source_act, _msg); | ||
_context.next = 82; | ||
break; | ||
case 39: | ||
if (!(!isChat && (!this.chats.length || this.chats.includes(update[3])) && (this.prefixOnlyForGroups || checkPrefix(update[6], this.prefix)) | ||
case 52: | ||
if (!( // для пользоватей | ||
!isChat && (!this.chats.length || this.chats.includes(chatId)) && (this.prefixOnlyForGroups || checkPrefix(body, this.prefix)) | ||
// ^ если префикс только для групп или начинается с префикса ^ | ||
)) { | ||
_context.next = 65; | ||
_context.next = 82; | ||
break; | ||
} | ||
_context.next = 42; | ||
return this.API.call('messages.getById', { | ||
// получаем расширенную информацию о сообщении | ||
message_ids: update[1] | ||
}); | ||
if (!this.msgtype) { | ||
_context.next = 57; | ||
break; | ||
} | ||
case 42: | ||
_msg3 = _context.sent; | ||
_context.t3 = update; | ||
_context.next = 60; | ||
break; | ||
_msg3 = _msg3.items[0]; | ||
this.emit('message', _msg3); // сообщаем о сообщении | ||
case 57: | ||
_context.next = 59; | ||
return getMsg(msgId); | ||
if (!_msg3.body) { | ||
_context.next = 65; | ||
case 59: | ||
_context.t3 = _context.sent; | ||
case 60: | ||
_msg2 = _context.t3; | ||
this.emit('message', _msg2); | ||
if (!body) { | ||
_context.next = 82; | ||
break; | ||
@@ -246,24 +278,26 @@ } | ||
_iteratorError2 = undefined; | ||
_context.prev = 49; | ||
_context.prev = 66; | ||
for (_iterator2 = this.textRegexpCallbacks[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { | ||
_reg = _step2.value; | ||
_result = _reg.regexp.exec(_msg3.body); | ||
_r = _step2.value; | ||
_result = _r.regexp.exec(body); | ||
if (_result) { | ||
answered = true;_reg.callback(_msg3, _result); | ||
handled = true; | ||
_r.callback(_msg2, _result); | ||
} | ||
if (!handled) this.emit('unhandled', _msg2); | ||
} | ||
_context.next = 57; | ||
_context.next = 74; | ||
break; | ||
case 53: | ||
_context.prev = 53; | ||
_context.t1 = _context['catch'](49); | ||
case 70: | ||
_context.prev = 70; | ||
_context.t4 = _context['catch'](66); | ||
_didIteratorError2 = true; | ||
_iteratorError2 = _context.t1; | ||
_iteratorError2 = _context.t4; | ||
case 57: | ||
_context.prev = 57; | ||
_context.prev = 58; | ||
case 74: | ||
_context.prev = 74; | ||
_context.prev = 75; | ||
@@ -274,7 +308,7 @@ if (!_iteratorNormalCompletion2 && _iterator2.return) { | ||
case 60: | ||
_context.prev = 60; | ||
case 77: | ||
_context.prev = 77; | ||
if (!_didIteratorError2) { | ||
_context.next = 63; | ||
_context.next = 80; | ||
break; | ||
@@ -285,12 +319,9 @@ } | ||
case 63: | ||
return _context.finish(60); | ||
case 80: | ||
return _context.finish(77); | ||
case 64: | ||
return _context.finish(57); | ||
case 81: | ||
return _context.finish(74); | ||
case 65: | ||
if (!answered) this.emit('unhandled', msg); | ||
case 66: | ||
case 82: | ||
case 'end': | ||
@@ -300,3 +331,3 @@ return _context.stop(); | ||
} | ||
}, _callee, this, [[13, 17, 21, 29], [22,, 24, 28], [49, 53, 57, 65], [58,, 60, 64]]); | ||
}, _callee, this, [[22, 26, 30, 38], [31,, 33, 37], [66, 70, 74, 82], [75,, 77, 81]]); | ||
})); | ||
@@ -326,3 +357,4 @@ | ||
var peer = msg.chat_id ? msg.chat_id + 2e9 : msg.user_id; | ||
var isLP = Array.isArray(msg); | ||
var peer = isLP ? msg[3] : msg.chat_id ? msg.chat_id + 2e9 : msg.user_id; | ||
if (this.forward && peer > 2e9) params.forward_messages = msg.id; | ||
@@ -329,0 +361,0 @@ params = Object.assign(params, { peer_id: peer, message: text }); |
{ | ||
"name": "vk-bot-api", | ||
"version": "1.3.1", | ||
"version": "1.4.0", | ||
"description": "Tool to make VK chat bots", | ||
@@ -5,0 +5,0 @@ "main": "./lib/vk.js", |
@@ -49,10 +49,10 @@ ## vk-bot-api | ||
|-----------|---------|-----|--------------| | ||
| options | Объект со всеми параметрами | Объект | | | ||
| options.token | Обязательный. Токен | Строка | | | ||
| options.v | Используемая версия VK API | Число | 5 | | ||
| options.chats | Список id чатов и пользователей, на сообщения которых бот будут отвечать. Если не указывать, то будет отвечать на все сообщения. ID беседы = 2e9 + номер беседы. <br> Например, если указать `[1, 2e9+12]`, то бот будет отвечать только на сообщения Дурова и чата #12 | Массив | Пуст | | ||
| options.prefix | Имя бота, с которого должны начинаться сообщения. Если не указывать, то будет отвечать на все сообщения. | Строка, Регулярное выражение, Массив со строками и регулярными выражениями | | | ||
| options.timeout | Таймаут для обращений к VK API. | Число | 5 | | ||
| options.autoForwardInChats | Если true, то бот будет автоматически пересылать сообщения отправителя в ответе. | Логический | false | ||
| options.prefixOnlyForGroups | Если true, то префикс будет проверяться только в беседах, а в диалогах с пользователями будет отвечать на все | Логический | false | ||
| token | Токен | Строка | | | ||
| v | Используемая версия VK API | Число | 5 | | ||
| chats | Список id чатов и пользователей, на сообщения которых бот будут отвечать. Если не указывать, то будет отвечать на все сообщения. ID беседы = 2e9 + номер беседы. <br> Например, если указать `[1, 2e9+12]`, то бот будет отвечать только на сообщения Дурова и чата #12 | Массив | Пуст | | ||
| prefix | Имя бота, с которого должны начинаться сообщения. Если не указывать, то будет отвечать на все сообщения. | Регулярное выражение | | | ||
| timeout | Таймаут для обращений к VK API. | Число | 5 | | ||
| autoForwardInChats | Если true, то бот будет автоматически пересылать сообщения отправителя в ответе. | Логический | false | ||
| prefixOnlyForGroups | Если true, то префикс будет проверяться только в беседах, а в диалогах с пользователями будет отвечать на все | Логический | false | ||
| LPMessages | Если true, то сообщения будут приходить не в виде объекта [сообщения](https://vk.com/dev/message), а в виде [массива, который присылает LongPoll - сервер](https://vk.com/dev/using_longpoll). Иначе сначала бот получит объект, используя API. | Логический | false | | ||
@@ -59,0 +59,0 @@ ## Запросы к VK API |
42985
6
759
3