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.2.0 to 2.0.0

.eslintrc.json

18

examples/simple.js

@@ -1,12 +0,12 @@

const API = require('../index')
const { token } = require('../config')
const VkBot = require('../lib')
const bot = new API(token)
const bot = new VkBot({
token: process.env.TOKEN,
group_id: process.env.GROUP_ID,
})
bot.command('start', ({ reply }) => reply('This is start!'))
bot.on((ctx) => {
ctx.reply('Hello!')
})
bot.hears(/(car|tesla)/, ({ reply }) => reply('I love Tesla!'))
bot.on(({ reply }) => reply('What?'))
bot.listen()
bot.startPolling()
const axios = require('axios')
const { stringify } = require('querystring')
module.exports = async function (method, options = {}) {
if (!options.v) {
options.v = this.v || 5.71
}
if (!options.access_token) {
options.access_token = this.token
}
module.exports = async function (method, settings = {}) {
try {
const { data } = await axios.post(`https://api.vk.com/method/${method}`, stringify(options))
const { error } = data
const { data } = await axios.post(`https://api.vk.com/method/${method}`, stringify({
v: 5.80,
...settings,
}))
if (error) {
throw data
if (data.error) {
throw new Error(JSON.stringify(data))
}
return data
} catch (error) {
throw error
} catch (err) {
throw new Error(err)
}
}

@@ -1,71 +0,57 @@

module.exports = class Bot {
constructor (token) {
if (!token) {
throw 'Token is required'
const methods = require('./methods')
const api = require('./api')
const { callExecute } = require('./utils')
class VkBot {
constructor(settings) {
if (!settings.token) {
throw new Error('You must set token param in settings')
} else if (!settings.group_id) {
throw new Error('You must set group_id param in settings')
}
this.v = 5.71
this.token = token
this.actions = { commands: [], hears: [], on: null, middlewares: [] }
this.longPollParams = null
this.middlewares = []
this.methods = []
this.settings = settings
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')
Object.entries({ ...methods, api, callExecute }).forEach(([key, method]) => {
this[key] = method.bind(this)
})
setInterval(() => {
this.executeHandler(this.methods)
this.callExecute(this.methods)
this.methods = []
}, (1000 / 20))
}, settings.executeTimeout || 50)
}
loadParams () {
return this.loadParams()
use(middleware) {
this.use(middleware)
}
handler (ctx) {
return this.handler(ctx)
command(triggers, ...middlewares) {
this.command(triggers, ...middlewares)
}
execute (method, settings, callback) {
return this.execute(method, settings, callback)
event(triggers, ...middlewares) {
this.command(triggers, ...middlewares)
}
reply (peerId, message, attachment, callback) {
return this.reply(peerId, message, attachment, callback)
on(...middlewares) {
this.command([], ...middlewares)
}
getLastMessage (update) {
return this.getLastMessage(update)
next(ctx, idx) {
return this.next(ctx, idx)
}
command (command, callback) {
return this.command(command, callback)
sendMessage(userId, ...args) {
this.sendMessage(userId, ...args)
}
hears (command, callback) {
return this.hears(command, callback)
startPolling(timeout) {
return this.startPolling(timeout)
}
}
on (callback) {
return this.on(callback)
}
use (callback) {
return this.use(callback)
}
listen () {
return this.listen()
}
}
module.exports = VkBot

@@ -1,8 +0,10 @@

module.exports = function (command, callback) {
const commands = typeof command === 'object' ? command : [ command ]
const toArray = value => (Array.isArray(value) ? value : [value])
commands.forEach((command) => {
this.actions.commands.push({
command,
callback
module.exports = function (triggers, ...middlewares) {
middlewares.forEach((fn) => {
const idx = this.middlewares.length
this.middlewares.push({
fn: ctx => fn(ctx, () => this.next(ctx, idx)),
triggers: toArray(triggers).map(item => item.toLowerCase()),
})

@@ -9,0 +11,0 @@ })

module.exports = function (method, settings, callback = () => {}) {
const { access_token = this.token } = settings
const code = `API.${method}(${JSON.stringify(settings)})`
this.methods.push({
code: `API.${method}(${JSON.stringify(settings)})`,
callback,
})
const otherTokenItems = this.methods.filter(item => item.access_token !== access_token)
const currentTokenItems = this.methods.find(item => item.access_token === access_token)
this.methods = [
...otherTokenItems,
{
access_token,
items: [
...(currentTokenItems ? currentTokenItems.items : []),
{ code, callback }
]
}
]
return this
}

@@ -1,5 +0,9 @@

module.exports = function (callback) {
this.actions.middlewares.push(callback)
module.exports = function (middleware) {
const idx = this.middlewares.length
this.middlewares.push({
fn: ctx => middleware(ctx, () => this.next(ctx, idx)),
})
return this
}
}
{
"name": "node-vk-bot-api",
"version": "1.2.0",
"description": "API for VK bots on long poll.",
"main": "index.js",
"version": "2.0.0",
"description": "🤖 Vk bot framework for Node.js",
"main": "lib/index.js",
"scripts": {
"lint": "eslint .",
"lint-fix": "eslint . --fix"
"eslint": "eslint .",
"eslint:fix": "eslint . --fix"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bifot/node-vk-bot-api.git"
"url": "git+https://github.com/node-vk-bot-api/node-vk-bot-api.git"
},

@@ -35,5 +35,5 @@ "keywords": [

"bugs": {
"url": "https://github.com/bifot/node-vk-bot-api/issues"
"url": "https://github.com/node-vk-bot-api/node-vk-bot-api/issues"
},
"homepage": "https://github.com/bifot/node-vk-bot-api#readme",
"homepage": "https://github.com/node-vk-bot-api/node-vk-bot-api#readme",
"dependencies": {

@@ -45,13 +45,10 @@ "axios": "^0.17.1"

},
"devDependencies": {
"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"
},
"devDependencies": {
"eslint": "^4.19.1",
"eslint-config-airbnb-base": "^13.0.0",
"eslint-plugin-import": "^2.13.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, based on [Long Poll](https://vk.com/dev/using_longpoll).
🤖 VK bot framework for Node.js, based on [Bots Long Poll API](https://vk.com/dev/bots_longpoll).

@@ -12,125 +12,188 @@ ## Install

```sh
$ npm i node-vk-bot-api
$ npm i node-vk-bot-api@2 -S # bots longpoll api
$ npm i node-vk-bot-api@1 -S # user longpoll api
```
## Example
## Usage
```javascript
const API = require('node-vk-bot-api')
const VkBot = require('node-vk-bot-api')
const bot = new API(process.env.TOKEN)
const bot = new VkBot({
token: process.env.TOKEN,
group_id: process.env.GROUP_ID
})
bot.command('start', ({ reply }) => reply('This is start!'))
bot.hears(/(car|tesla)/, ({ reply }) => reply('I love Tesla!'))
bot.on(({ reply }) => reply('What?'))
bot.command('/start', (ctx) => {
ctx.reply('Hello!')
})
bot.listen()
bot.startPolling()
```
## Examples
[There's a few simple examples.](/examples)
## Methods
* [constructor(options)](#constructoroptions)
* [.use(callback)](#usecallback)
* [.command(command, callback)](#commandcommand-callback)
* [.hears(command, callback)](#hearscommand-callback)
* [.on(callback)](#oncallback)
* [.listen()](#listen)
* [constructor(settings)](#constructorsettings)
* [.use(middleware)](#usemiddleware)
* [.command(triggers, ...middlewares)](#commandtriggers-middlewares)
* [.event(triggers, ...middlewares)](#eventtriggers-middlewares)
* [.on(...middlewares)](#onmiddlewares)
* [.sendMessage(userId, message, attachment, keyboard, sticker)](#sendmessageuserid-message-attachment-keyboard-sticker)
* [.startPolling()](#startpollingtimeout)
### constructor(options)
### constructor(settings)
| Parameter | Type | Required |
|:-----------|:---------:| ---------:|
| token | string | yes |
Create bot.
```javascript
const bot = new API(process.env.TOKEN)
const bot = new VkBot({
token: process.env.TOKEN,
group_id: process.env.GROUP_ID
})
```
### .use(callback)
### .use(middleware)
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| callback | function | yes |
Add simple middleware.
Add middleware.
```javascript
bot.use((ctx, next) => {
ctx.message.timestamp = new Date().getTime()
next()
})
```
```js
bot.use(ctx => ctx.date = new Date())
### .command(triggers, ...middlewares)
bot.on(({ date }) => {
// Fri Nov 24 2017 16:00:21 GMT+0300 (MSK)
Add middlewares with triggers for `message_new` event.
```javascript
bot.command('start', (ctx) => {
ctx.reply('Hello!')
})
```
### .command(command, callback)
### .event(triggers, ...middlewares)
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| command | string | yes |
| callback | function | yes |
Add middlewares with triggers for selected events.
Add command w/ strict match.
```javascript
bot.event('message_edit', (ctx) => {
ctx.reply('Your message was editted')
})
```
### .on(...middlewares)
Add reserved middlewares without triggers.
```javascript
bot.command('start', ({ reply }) => reply('This is start!'))
bot.on((ctx) => {
ctx.reply('No commands for you.')
})
```
### .hears(command, callback)
### .sendMessage(userId, message, attachment, keyboard, sticker)
| Parameter | Type | Required |
| -----------|:---------:| ---------:|
| command | string/regexp | yes |
| callback | function | yes |
Send message to user.
Add command w/ match like RegEx.
```javascript
// Simple usage
bot.sendMessage(145003487, 'Hello!', 'photo1_1')
```javascript
bot.hears(/(car|tesla)/, ({ reply }) => reply('I love Tesla!'))
// Advanced usage
bot.sendMessage(145003487, {
message: 'Hello!',
lat: 59.939095,
lng: 30.315868
})
```
### .on(callback)
### .startPolling([timeout])
| Parameter | Type | Required |
|:-----------|:---------:| ---------:|
| callback | function | yes |
Start polling with given timeout (25 by default).
Add reserved callback.
```js
bot.startPolling()
```
## Context Methods
* [.reply(message, attachment, keyboard, sticker)](#replymessage-attachment-keyboard-sticker)
### .reply(message, attachment, keyboard, sticker)
Helper method for reply to the current user.
```javascript
bot.on(({ reply }) => {
reply('What?')
bot.command('start', (ctx) => {
ctx.reply('Hello!')
})
```
### .listen()
## Markup
Start listen.
Add keyboard in message.
## Context Methods
```javascript
const VkBot = require('node-vk-bot-api')
const Markup = require('node-vk-bot-api/lib/markup')
* [.reply(peer_id, message, attachment, callback)](#replypeer_id-message-attachment-callback)
const bot = new VkBot({
token: process.env.TOKEN,
group_id: process.env.GROUP_ID,
})
### .reply(peer_id, message, attachment, callback)
bot.command('/sport', (ctx) => {
ctx.reply('Select your sport', null, Markup
.keyboard([
'Football',
'Basketball',
])
.oneTime())
})
bot.command('/mood', (ctx) => {
ctx.reply('How are you doing?', null, Markup
.keyboard([
[
Markup.button('Normally', 'primary'),
],
[
Markup.button('Fine', 'positive'),
Markup.button('Bad', 'negative'),
],
]))
})
```
| 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 |
## Sessions
Send a message to user.
Store anything for current user in local memory.
```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!')
const VkBot = require('node-vk-bot-api')
const Session = require('node-vk-bot-api/lib/session')
const bot = new VkBot({
token: process.env.TOKEN,
group_id: process.env.GROUP_ID,
})
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()
```

@@ -137,0 +200,0 @@

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