Socket
Socket
Sign inDemoInstall

vk-next

Package Overview
Dependencies
65
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.4 to 0.1.0-alpha.1

jsconfig.json

6

lib/api/bindMethods.js
module.exports = function (module) {
let methods = {}
const methods = {}
for (let methodName of Object.keys(module)) {
let method = module[methodName].bind(this)
for (const methodName of Object.keys(module)) {
const method = module[methodName].bind(this)
methods[methodName] = method

@@ -7,0 +7,0 @@ }

const request = require('request-promise')
const parse = require('../utils/parseLongpoolResponse')
const parse = require('../utils/parseLongpollResponse')
/**
* Creates controller for LongPool
* Creates controller for LongPoll
*/
class LongpoolController {
constructor (api, { key, server, ts }) {
class LongpollController {
constructor (api, store, { key, server, ts }) {
this.api = api
this.store = store
this.key = key

@@ -35,15 +36,23 @@ this.server = server

/**
* Call LongPool server for recieve new updates
* Call LongPoll server for recieve new updates
*/
async _call () {
if (this.started) {
let options = {
uri: `https://${this.server}?act=a_check&key=${this.key}&ts=${this.ts}&wait=25&mode=2&version=2`
}
const { server, key, ts } = this
let response = JSON.parse(await request(options))
const { timestamp, updates } = JSON.parse(await request({
uri: server,
qs: {
key,
ts,
wait: 25,
act: 'a_check',
mode: 2,
version: 2
}
}))
this.ts = response.ts
let events = parse(response.updates)
const events = parse(response.updates)

@@ -53,3 +62,3 @@ this.callbacks.map(callback => {

if (callback.type === event.type) {
callback.callback(event.data)
this.store.process(event.data, callback)
}

@@ -64,2 +73,2 @@ })

module.exports = LongpoolController
module.exports = LongpollController

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

const crypto = require('crypto')
const crypto = require('nanoid')

@@ -14,19 +14,8 @@ class RequestController {

add (request) {
let id = crypto.createHmac('sha256', 'https://vk.cc/7A4bYf')
.update(request.method + Date.now() + Math.random())
.digest('hex')
request.id = crypto()
request.id = id
let callback = {}
let promise = new Promise((resolve, reject) => {
callback.resolve = resolve
callback.reject = reject
})
this.callbacks[id] = callback
this.callbacks[request.id] = Promise
this.queue.requests.push(request)
return promise
return this
}

@@ -33,0 +22,0 @@

const API = require('./api')
const LongpoolController = require('./controllers/LongpoolController')
const LongpollController = require('./controllers/LongpoolController')
const BotLongpollController = require('./controllers/BotLongpollController')
const Store = require('./stores/LocalStore')

@@ -20,2 +22,4 @@ class Next {

this.api.init(this.queue)
this.store = new Store(this.api)
}

@@ -28,3 +32,7 @@

try {
let server = await this.api.messages.getLongPollServer({
if (this.queue.isGroup) {
throw new Error('LongPoll API is not avaible for groups. Use startBotPooling()')
}
const server = await this.api.messages.getLongPollServer({
lp_version: 2,

@@ -34,21 +42,39 @@ need_pts: false

this.longpool = new LongpoolController(this.api, server)
this.longpool.start()
this.longpoll = new LongpollController(this.api, this.store, server)
this.longpoll.start()
} catch (err) {
console.log(err)
throw err
}
}
/**
* Start pooling for group
* @param {Number} groupId Group ID
*/
async startBotPooling (groupId) {
if (!this.queue.isGroup) throw new Error('Bot LongPoll API is not avaible for users. Use startPooling()')
try {
const server = await this.api._call('groups.getLongPollServer', { // GitHub schema is not updated yet :(
group_id: groupId
})
console.log(server)
this.longpoll = new BotLongpollController(this.api, this.store, server)
this.longpoll.start()
} catch (err) {
throw err
}
}
stopPooling () {
this.longpool.stop()
this.longpoll.stop()
}
on (type, callback) {
if (this.longpool) {
switch (type) {
case 'message': {
this.longpool.subscribe(type, callback)
break
}
}
if (this.longpoll) {
this.longpoll.subscribe(type, callback)
} else {
throw new Error('LongPoll is not initialized yet')
}

@@ -55,0 +81,0 @@ }

@@ -13,16 +13,19 @@ const request = require('request-promise')

method,
params = [],
params = {},
access_token = this.token, // eslint-disable-line
v = '5.69'
v = '5.73'
) {
const options = {
method: 'POST',
uri: `https://api.vk.com/method/${method}`,
qs: {
formData: {
...params,
access_token, // eslint-disable-line
v,
...params
v
}
}
return request(options)
console.log('debug', options)
return request.post(options)
}
{
"name": "vk-next",
"version": "0.0.4",
"version": "0.1.0-alpha.1",
"description": "VK API Library based on code generation with bots support",

@@ -16,5 +16,5 @@ "main": "lib/index.js",

"dependencies": {
"escodegen": "^1.9.0",
"json-schema-ref-parser": "^4.0.4",
"mkdirp": "^0.5.1",
"nanoid": "^1.0.1",
"request": "^2.83.0",

@@ -21,0 +21,0 @@ "request-promise": "^4.2.2"

# VK-Next
> Библиотека для ВК, основанная на кодогенерации методов API с поддержкой удобного написания ботов
> Библиотека для VK API, поддерживающая LongPoll API, новый Bot LongPoll API и Callback API, основанная на кодогенерации методов из JSON схемы
С данной библиотекой вы можете как создавать ботов, так и сделать свой клиент благодаря полной поддержке всего API
[![npm](https://img.shields.io/npm/v/vk-next.svg)](https://www.npmjs.com/package/vk-next)
# Внимание
* Библиотека вероятнее всего будет менять архитектуру до релиза стабильной версии 1.0.0 и сейчас активно дорабатывается и рефакторится
* Документация еще не заполнена полностью, по всем вопросам пишите в чаты библиотеки:
* https://t.me/vknext
* https://vk.me/join/AJQ1d8yOLAN7dEz4zzRnqEyM
## Roadmap
- Поддержка VK API ✅
- Удобный интерфейс для ботов
- Роуты для сообщений ✅
- Хранилище сессий
- Локализация
- Утилиты для работы (генерация битовой маски, ссылки для токена)
## Настройка
## Получение сообщений
В данный момент библиотека поддерживает 2 типа получения событий: Bot Longpoll API и Longpoll API, в будущем будет поддержка Callback API
Пример для Bot Longpoll API
```javascript
vk.on('message_new', (ctx, message) => {
console.log('new message: ' + message.body)
})
```
Пример для Longpoll API
```javascript
vk.on(4, (ctx, message) => {
console.log('new message: ' + message.text)
})
```
## Роутинг
Пример роута
```javascript
const { BaseRoute } = require('vk-next')
class TestRoute extends BaseRoute {
test (ctx, message) {
ctx.api.messages.send({
peer_id: ctx.userId,
message: 'Test!'
})
}
default (ctx, message) {
ctx.api.messages.send({
peer_id: ctx.userId,
message: 'You wrote: ' + message.text
})
}
get commands () {
return {
'/test': 'test',
}
}
}
module.exports = TestRoute
```
```javascript
ctx.use(TestRoute)
```
## LICENSE

@@ -12,0 +77,0 @@ The MIT License (MIT)

SocketSocket SOC 2 Logo

Product

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc