Socket
Socket
Sign inDemoInstall

node-vk-bot-api

Package Overview
Dependencies
Maintainers
1
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-vk-bot-api - npm Package Compare versions

Comparing version 1.1.4 to 1.1.5

lib/methods/getForward.js

32

.eslintrc.js
module.exports = {
"env": {
"es6": true,
"node": true
'env': {
'es6': true,
'node': true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
'parserOptions': {
'ecmaVersion': 8,
'ecmaFeatures': {
'experimentalObjectRestSpread': true
}
},
"rules": {
"indent": [
"error", 2
'extends': 'eslint:recommended',
'rules': {
'indent': [
'error', 2
],
"linebreak-style": [
"error", "unix"
'linebreak-style': [
'error', 'unix'
],
"quotes": [
"error", "single"
'quotes': [
'error', 'single'
],
"semi": ["error", "never"]
'no-console': ['error', { allow: ['warn', 'error'] }],
'semi': ['error', 'never']
}
}

@@ -1,22 +0,25 @@

const request = require('request')
const axios = require('axios')
const { stringify } = require('querystring')
module.exports = (method, options = {}) => {
module.exports = async function (method, options = {}) {
if (!options.v) {
options.v = 5.68
options.v = this.v || 5.71
}
return new Promise((resolve, reject) => {
request({
url: `https://api.vk.com/method/${method}`,
method: 'post',
formData: options,
json: true
}, (err, res, body) => {
if (!err && res.statusCode === 200 && body.response) {
resolve(body)
} else {
reject(err)
}
})
})
if (!options.access_token) {
options.access_token = this.token
}
try {
const { data } = await axios.post(`https://api.vk.com/method/${method}`, stringify(options))
const { error } = data
if (error) {
throw data
}
return data
} catch (error) {
throw error
}
}

@@ -1,3 +0,1 @@

const executeHandler = require('./utils/executeHandler')
module.exports = class Bot {

@@ -9,31 +7,43 @@ constructor (token) {

this.v = 5.71
this.token = token
this.methods = {}
this.actions = { commands: {}, hears: {}, on: {} }
this.actions = { commands: [], hears: [], on: null, middlewares: [] }
this.methods = []
Object.assign(this, {
execute: require('./methods/execute').bind(this),
reply: require('./methods/reply').bind(this),
command: require('./methods/command').bind(this),
hears: require('./methods/hears').bind(this),
on: require('./methods/on').bind(this),
listen: require('./methods/listen').bind(this),
api: require('./api'),
getLastMessage: require('./utils/getLastMessage')
})
this.api = require('./api').bind(this)
this.use = require('./methods/use').bind(this)
this.command = require('./methods/command').bind(this)
this.hears = require('./methods/hears').bind(this)
this.on = require('./methods/on').bind(this)
this.reply = require('./methods/reply').bind(this)
this.handler = require('./methods/handler').bind(this)
this.listen = require('./methods/listen').bind(this)
this.loadParams = require('./methods/loadParams').bind(this)
this.getForward = require('./methods/getForward').bind(this)
this.execute = require('./methods/execute').bind(this)
this.executeHandler = require('./utils/executeHandler')
this.getLastMessage = require('./utils/getLastMessage')
setInterval(() => {
executeHandler(this.methods)
this.methods = {}
this.executeHandler(this.methods)
this.methods = []
}, (1000 / 20))
}
execute (method, settings, token, callback) {
return this.execute(method, settings, token, callback)
loadParams () {
return this.loadParams()
}
reply (peerId, message, attachment) {
return this.reply(peerId, message, attachment)
handler (ctx) {
return this.handler(ctx)
}
execute (method, settings, callback) {
return this.execute(method, settings, callback)
}
reply (peerId, message, attachment, callback) {
return this.reply(peerId, message, attachment, callback)
}
getLastMessage (update) {

@@ -55,2 +65,6 @@ return this.getLastMessage(update)

use (callback) {
return this.use(callback)
}
listen () {

@@ -57,0 +71,0 @@ return this.listen()

module.exports = function (command, callback) {
const list = typeof command === 'object' ? command : [ command ]
const string = list.map(item => item.toString().toLowerCase()).join(';')
const commands = typeof command === 'object' ? command : [ command ]
this.actions.commands[string] = callback
commands.forEach((command) => {
this.actions.commands.push({
command,
callback
})
})
return this
}

@@ -1,14 +0,20 @@

module.exports = function (method, settings, token, callback = () => {}) {
module.exports = function (method, settings, callback = () => {}) {
const { access_token = this.token } = settings
const code = `API.${method}(${JSON.stringify(settings)})`
if (!this.methods[token]) {
this.methods[token] = []
}
const otherTokenItems = this.methods.filter(item => item.access_token !== access_token)
const currentTokenItems = this.methods.find(item => item.access_token === access_token)
this.methods[token].push({
code,
callback
})
this.methods = [
...otherTokenItems,
{
access_token,
items: [
...(currentTokenItems ? currentTokenItems.items : []),
{ code, callback }
]
}
]
return this
}
module.exports = function (command, callback) {
const list = typeof command === 'object' && !(command instanceof RegExp)
? command : [command]
const string = list
.map(item => item instanceof RegExp ? item.toString() : item.toString().toLowerCase())
.join(';')
const commands = typeof command === 'object' && !(command instanceof RegExp)
? command : [ command ]
this.actions.hears[string] = callback
commands
.map((command) => {
return command instanceof RegExp
? (command.toString().split('/')[2] ? command : new RegExp(command.toString().split('/')[1], 'i'))
: new RegExp(command, 'i')
})
.forEach((command) => {
this.actions.hears.push({
command,
callback
})
})
return this
}

@@ -1,150 +0,46 @@

const rp = require('request-promise')
const axios = require('axios')
module.exports = function () {
const { commands, hears, on: reservedCallback } = this.actions
module.exports = async function () {
if (!this.longPollParams) {
return this.api('messages.getLongPollServer', {
need_pts: 1,
lp_version: 2,
access_token: this.token,
v: 5.65
})
.then((body) => {
if (!body.response || !body.response.server) {
throw new Error(JSON.stringify(body))
}
await this.loadParams()
this.longPollParams = body.response
this.listen()
})
.catch((err) => {
this.longPollParams = null
return this.listen()
})
return this.listen()
}
return rp({
url: `https://${this.longPollParams.server}`,
qs: {
...this.longPollParams,
act: 'a_check',
wait: 25,
mode: 2,
version: 2
},
json: true
})
.then((body) => {
if (body.failed) {
if (body.failed && body.ts) {
this.longPollParams.ts = body.ts
} else {
this.longPollParams = null
}
return this.listen()
try {
const { data: body } = await axios.get(`https://${this.longPollParams.server}`, {
params: {
...this.longPollParams,
act: 'a_check',
wait: 25,
mode: 2,
version: 2
}
})
if (body.failed) {
if (body.ts) {
this.longPollParams.ts = body.ts
this.longPollParams = { ...this.longPollParams, ts: body.ts }
} else {
this.longPollParams = null
}
this.listen()
return this.listen()
}
if (body.updates && body.updates.length) {
body.updates.forEach((update) => {
if (update[0] === 4 && (update[2] & 2) === 0) {
const ctx = {
user_id: update[3],
body: update[5],
attachments: update[6],
date: update[4],
message_id: update[1],
}
if (body.ts) {
this.longPollParams = { ...this.longPollParams, ts: body.ts }
}
if (update[6].from) {
ctx.from = +update[6].from
}
if (body.updates && body.updates.length) {
await Promise.all(body.updates.map(update => this.handler(update)))
}
const getForward = (ctx) => {
return new Promise((resolve) => {
if (!ctx.attachments || !ctx.attachments.fwd) {
resolve(null)
}
return this.listen()
} catch (error) {
this.longPollParams = null
console.error(`${new Date()}: Listening error!`, error)
this.execute('messages.getById', {
message_ids: ctx.message_id,
v: 5.67
}, this.token, (data) => {
resolve(this.getLastMessage(data.items[0]))
})
})
}
getForward(ctx)
.then((forward) => {
if (forward) {
ctx.forward = forward
ctx.original = { body: ctx.body }
ctx.body = forward.body
}
const attachmentsKeys = Object.keys(ctx.attachments).filter(key => key.search('attach') > -1 && key.search('type') === -1 && key.search('kind') === -1)
const attachments = []
attachmentsKeys.forEach((key) => {
const file = {}
file['type'] = ctx.attachments[`${key}_type`]
file[file.type] = ctx.attachments[key]
attachments.push(file)
})
ctx.attachments = attachments
ctx.body = ctx.body.replace(/<br>/g, '\n')
ctx.reply = (message, attachment) => this.reply(ctx.user_id, message, attachment)
ctx.sendMessage = (userId, message, attachment) => this.reply(userId, message, attachment)
const message = ctx.body.toLowerCase()
const commandKey = Object.keys(commands).filter(item => item.indexOf(message) > -1)[0]
const commandCallback = commands[commandKey]
const hearsKey = Object.keys(hears).filter((item) => {
const index = item.split(';')
.filter((item) => {
if (/^\/[\S]{1,}\/[a-z]{1,2}$/.test(item)) {
const string = item.substr(1).replace(/\/[a-z]{1,2}/i, '')
const type = item.substr(1).match(/\/[a-z]{1,2}/i)[0].substr(1)
return new RegExp(string, type).test(message)
} else {
return new RegExp(item, 'i').test(message)
}
})
return index.length
})[0]
const hearsCallback = hears[hearsKey]
if (commandCallback !== undefined) {
return commandCallback(ctx)
} else if (hearsCallback !== undefined) {
return hearsCallback(ctx)
} else if (reservedCallback !== undefined) {
return reservedCallback(ctx)
}
})
.catch((err) => {
this.longPollParams = null
return this.listen()
})
}
})
}
})
.catch((err) => {
this.longPollParams = null
return this.listen()
})
return this.listen()
}
}

@@ -1,9 +0,10 @@

module.exports = function (peer, message, attachment) {
module.exports = function (peer, message, attachment, callback) {
this.execute('messages.send', {
peer_id: peer,
message: message,
random_id: Number(`${Math.floor(Math.random() * 1e4)}${Date.now()}`),
attachment: attachment
}, this.token, null)
}, callback)
return this
}

@@ -5,14 +5,16 @@ module.exports = (body, callbacks) => {

if (error) {
throw error
throw new Error(JSON.stringify(error))
} else if (execute_errors) {
throw execute_errors
throw new Error(JSON.stringify(execute_errors))
}
response.forEach((item, i) => {
const callback = callbacks[i]
if (response) {
response.forEach((data, i) => {
const callback = callbacks[i]
if (typeof callback === 'function') {
callback(item)
}
})
if (typeof callback === 'function') {
callback({ data })
}
})
}
}

@@ -5,17 +5,15 @@ const api = require('../api')

module.exports = (methods) => {
Object.entries(methods)
.map(([ token, methods ]) => ({ token, methods }))
.forEach(({ token, methods }) => {
const code = methods.map(item => item.code)
const callbacks = methods.map(item => item.callback)
methods.forEach(({ access_token, items }) => {
const codes = items.map(({ code }) => code)
const callbacks = items.map(({ callback }) => callback)
for (let i = 0, j = Math.ceil(code.length / 25); i < j; i++) {
api('execute', {
code: `return [ ${code.slice(i * 25, i * 25 + 25).join(',')} ];`,
access_token: token
})
.then(body => callbackHandler(body, callbacks))
.catch(err => callbackHandler(err, callbacks))
}
})
for (let i = 0, j = Math.ceil(codes.length / 25); i < j; i++) {
api('execute', {
code: `return [ ${codes.slice(i * 25, i * 25 + 25)} ];`,
access_token
})
.then(data => callbackHandler(data, callbacks))
.catch(err => callbackHandler(err, callbacks))
}
})
}

@@ -1,2 +0,2 @@

module.exports = getLastMessage = (update) => {
const getLastMessage = (update) => {
if (update.fwd_messages && update.fwd_messages.length) {

@@ -8,1 +8,3 @@ return getLastMessage(update.fwd_messages[0])

}
module.exports = getLastMessage
{
"name": "node-vk-bot-api",
"version": "1.1.4",
"version": "1.1.5",
"description": "API for VK bots on long poll.",
"main": "index.js",
"scripts": {
"test": "node examples/simple.js",
"lint": "eslint ."
"lint": "eslint .",
"lint-fix": "eslint . --fix"
},

@@ -39,4 +39,3 @@ "repository": {

"dependencies": {
"request": "^2.81.0",
"request-promise": "^4.2.1"
"axios": "^0.17.1"
},

@@ -47,4 +46,12 @@ "directories": {

"devDependencies": {
"eslint": "^4.11.0"
"eslint": "^3.19.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-node": "^5.2.1",
"eslint-plugin-promise": "^3.6.0",
"eslint-plugin-standard": "^3.0.1"
},
"engines": {
"node": ">=8.0.0"
}
}

@@ -6,3 +6,3 @@ [![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/)

API for VK bots on long poll.
API for VK bots, based on [Long Poll](https://vk.com/dev/using_longpoll).

@@ -32,2 +32,3 @@ ## Install

* [constructor(options)](#constructoroptions)
* [.use(callback)](#usecallback)
* [.command(command, callback)](#commandcommand-callback)

@@ -40,3 +41,3 @@ * [.hears(command, callback)](#hearscommand-callback)

| Parameter | Type | Requried |
| Parameter | Type | Required |
|:-----------|:---------:| ---------:|

@@ -51,6 +52,22 @@ | token | string | yes |

### .use(callback)
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| callback | function | yes |
Add middleware.
```js
bot.use(ctx => ctx.date = new Date())
bot.on(({ date }) => {
// Fri Nov 24 2017 16:00:21 GMT+0300 (MSK)
})
```
### .command(command, callback)
| Parameter | Type | Requried |
|:-----------|:---------:| ---------:|
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| command | string | yes |

@@ -62,5 +79,3 @@ | callback | function | yes |

```javascript
bot.command('start', ({ reply }) => {
reply('This is start!')
})
bot.command('start', ({ reply }) => reply('This is start!'))
```

@@ -70,5 +85,5 @@

| Parameter | Type | Requried |
|:-----------|:---------:| ---------:|
| command | string | yes |
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| command | string/regexp | yes |
| callback | function | yes |

@@ -79,5 +94,3 @@

```javascript
bot.hears(/(car|tesla)/, ({ reply }) => {
reply('I love Tesla!')
})
bot.hears(/(car|tesla)/, ({ reply }) => reply('I love Tesla!'))
```

@@ -87,3 +100,3 @@

| Parameter | Type | Requried |
| Parameter | Type | Required |
|:-----------|:---------:| ---------:|

@@ -106,26 +119,29 @@ | callback | function | yes |

* [.reply(message, attachment)](#replymessage-attachment)
* [.sendMessage(peer, command, callback)](#sendmessagepeerid-command-callback)
* [.reply(peer_id, message, attachment, callback)](#replypeer_id-message-attachment-callback)
### .reply(message, attachment)
### .reply(peer_id, message, attachment, callback)
| Parameter | Type | Requried |
|:-----------|:---------:| --------------------------------:|
| message | string | yes (no, if setten attachment) |
| attachment | string | yes (no, if setten message) |
Send a message to the current user.
| Parameter | Type | Requried |
| -----------|:----------------:| ---------:|
| user_id | number or array | yes |
| message | string | yes (no, if setten attachment) |
| attachment | string | yes (no, if setten message) |
| callback | function | no |
### .sendMessage(peer, command, callback)
Send a message to user.
| Parameter | Type | Requried |
|:-----------|:---------:| --------------------------------:|
| peer | number | yes |
| message | string | yes (no, if setten attachment) |
| attachment | string | yes (no, if setten message) |
```javascript
bot.command('start', (ctx) => {
// with shortcut from context
ctx.reply('Hi, this is start!')
// function from context
ctx.sendMessage(ctx.peer_id, 'Hi, this is start!')
// simple usage
bot.reply(ctx.peer_id, 'Hi, this is start!')
})
```
Send a message to any user.
## License
MIT.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc