Socket
Socket
Sign inDemoInstall

node-vk-bot

Package Overview
Dependencies
51
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.2 to 1.0.3

test/test.ts

15

build/index.d.ts
/// <reference types="node" />
import { EventEmitter } from 'events';
import * as stream from 'stream';
import { VKError, VKExecuteResponse, VKResponse } from './interfaces/APIResponses';
import { UploadedPhoto } from './interfaces/UploadedPhoto';
import { Message } from './interfaces/Message';
import { UserEvent } from './interfaces/UserEvent';
import { MessageSendParams } from './interfaces/MessageSendParams';
import UploadedPhoto from './interfaces/UploadedPhoto';
import Message from './interfaces/Message';
import UserEvent from './interfaces/UserEvent';
import MessageSendParams from './interfaces/MessageSendParams';
export interface Options {

@@ -16,2 +17,3 @@ token: string;

}
export declare type replyFunc = (text?: string, params?: MessageSendParams) => Promise<VKResponse>;
export declare class Bot extends EventEmitter {

@@ -28,6 +30,7 @@ options: Options;

stop(): this;
get(pattern: RegExp, listener: (msg?: Message, exec?: RegExpExecArray) => any): this;
uploadPhoto(path: string): Promise<UploadedPhoto>;
get(pattern: UserEvent['pattern'], listener: UserEvent['listener']): this;
getPayload(jsonString: string, listener: (msg?: Message, reply?: replyFunc) => void): void;
uploadPhoto(photo: string | stream.Stream): Promise<UploadedPhoto>;
private _update;
}
export { Message, UploadedPhoto, VKError, VKExecuteResponse, VKResponse, UserEvent, MessageSendParams };

30

build/index.js

@@ -19,2 +19,3 @@ "use strict";

var fs = require("fs");
var stream = require("stream");
var poll_1 = require("./functions/poll");

@@ -92,4 +93,18 @@ var Bot = (function (_super) {

};
Bot.prototype.uploadPhoto = function (path) {
Bot.prototype.getPayload = function (jsonString, listener) {
this.on('payload', function (msg, reply) {
if (JSON.stringify(JSON.parse(msg.payload)) === JSON.stringify(JSON.parse(jsonString))) {
listener(msg, reply);
}
});
};
Bot.prototype.uploadPhoto = function (photo) {
var _this = this;
var photoStream;
if (typeof photo === 'string') {
photoStream = fs.createReadStream(photo);
}
else if (photo instanceof stream.Stream) {
photoStream = photo;
}
return this.api('photos.getMessagesUploadServer')

@@ -100,3 +115,3 @@ .then(function (server) { return rq({

formData: {
photo: fs.createReadStream(path)
photo: photoStream
},

@@ -113,2 +128,3 @@ json: true

Bot.prototype._update = function (update) {
var _this = this;
var msg = update.object;

@@ -127,2 +143,10 @@ var hasAttachments = msg.attachments.length;

};
var reply = function (text, params) {
if (params === void 0) { params = {}; }
return _this.send(text, message.peer_id, params);
};
if (msg.payload) {
message.payload = msg.payload;
this.emit('payload', msg, reply);
}
if (hasAttachments && msg.attachments[0].type === 'sticker')

@@ -142,3 +166,3 @@ return this.emit('sticker', message);

}
ev.listener(message, ev.pattern.exec(message.text));
ev.listener(message, ev.pattern.exec(message.text), reply);
};

@@ -145,0 +169,0 @@ return Bot;

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

export interface Message {
export default interface Message {
id: number;

@@ -11,2 +11,3 @@ peer_id: number;

fwd_messages: any;
payload?: string;
}

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

export interface MessageSendParams {
export default interface MessageSendParams {
message?: string;

@@ -13,3 +13,4 @@ peer_id?: number;

sticker_id?: number;
guid?: number;
keyboard?: string;
payload?: any;
}

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

export interface UploadedPhoto {
export default interface UploadedPhoto {
id: number;

@@ -3,0 +3,0 @@ album_id: number;

@@ -1,5 +0,6 @@

import { Message } from '..';
export interface UserEvent {
import Message from './Message';
import { replyFunc } from '..';
export default interface UserEvent {
pattern: RegExp;
listener(msg?: Message, exec?: RegExpExecArray): any;
listener(msg?: Message, exec?: RegExpExecArray, reply?: replyFunc): void;
}
const express = require('express');
const bodyParser = require('body-parser');
const { Bot } = require('node-vk-bot');
const { Bot } = require('..');
const bot = new Bot({

@@ -5,0 +5,0 @@ token: 'Community API token',

const express = require('express');
const bodyParser = require('body-parser');
const { Bot } = require('node-vk-bot');
const { Bot } = require('..');
const bot = new Bot({
token: 'Community API token',
group_id: 123456
token: 'Community API token',
group_id: 123456
});

@@ -15,35 +15,35 @@

app.post('/bot', (req, res) => {
if (req.body.type == 'confirmation') return res.send('CONFIRMATION CODE');
bot.processUpdate(req.body);
res.sendStatus(200);
if (req.body.type == 'confirmation') return res.send('CONFIRMATION CODE');
bot.processUpdate(req.body);
res.sendStatus(200);
});
app.listen(port, () => {
console.log(`Express server is listening on ${port}`);
console.log(`Express server is listening on ${port}`);
});
bot.get(/Hi|Hello|Hey/i, message => {
bot.send('Hello!', message.peer_id, {
keyboard: JSON.stringify({
one_time: true,
buttons: [
{
action: {
type: 'text',
label: 'Red'
},
color: 'negative'
},
{
action: {
type: 'text',
label: 'Green'
},
color: 'positive'
},
]
})
});
bot.send('Hello!', message.peer_id, {
keyboard: JSON.stringify({
one_time: true,
buttons: [
{
action: {
type: 'text',
label: 'Red'
},
color: 'negative'
},
{
action: {
type: 'text',
label: 'Green'
},
color: 'positive'
},
]
})
});
});
bot.get(/Red|Green/, msg => bot.send('You clicked a button - ' + msg.body, msg.peer_id))

@@ -9,8 +9,8 @@ import { Bot, Message } from '..'

.start()
.get(/cat|kitten/, async (msg: Message) => {
const photoPath = path.join(__dirname, '../test/kitten.jpg')
.get(/cat|kitten/, async (msg, exec, reply) => {
const photoPath = path.join(__dirname, 'kitten.jpg')
const photo = await bot.uploadPhoto(photoPath)
bot.send('Take this', msg.peer_id, {
reply('Take this', {
attachment: `photo${photo.owner_id}_${photo.id}`
})
})

@@ -8,9 +8,10 @@ // Отправляет картинку на любое входящее сообщение

token: 'TOKEN',
group_id: 123456
}).start()
bot.on('command-notfound', msg => {
bot.uploadPhoto(path.join(__dirname, './kitten.jpg'))
.then(photo => bot.send('', msg.peer_id, {
attachment: `photo${photo.owner_id}_${photo.id}`
}))
bot.uploadPhoto(path.join(__dirname, './kitten.jpg'))
.then(photo => bot.send('', msg.peer_id, {
attachment: `photo${photo.owner_id}_${photo.id}`
}))
})

@@ -15,4 +15,3 @@ module.exports = function (grunt) {

src: [
'src/**/*.ts',
'test/**/*.ts'
'src/**/*.ts'
]

@@ -22,5 +21,14 @@ }

ts: {
default : {
default: {
tsconfig: true
}
},
mochaTest: {
test: {
options: {
require: 'ts-node/register',
timeout: 5000
},
src: ['test/**/*.ts']
}
}

@@ -32,5 +40,6 @@ })

grunt.loadNpmTasks('grunt-ts')
grunt.loadNpmTasks('grunt-mocha-test')
grunt.registerTask('default', ['clean', 'ts'])
grunt.registerTask('test', ['tslint'])
grunt.registerTask('test', ['tslint', 'mochaTest'])
}
{
"name": "node-vk-bot",
"version": "1.0.2",
"version": "1.0.3",
"description": "Create and control VK bots easily.",

@@ -24,3 +24,4 @@ "main": "./build/index.js",

"devDependencies": {
"@types/node": "7.0.67",
"@types/mocha": "5.2.5",
"@types/node": "7.0.69",
"@types/request": "2.47.1",

@@ -30,4 +31,7 @@ "@types/request-promise-native": "1.0.15",

"grunt-contrib-clean": "1.1.0",
"grunt-mocha-test": "0.13.3",
"grunt-ts": "6.0.0-beta.21",
"grunt-tslint": "5.0.2",
"mocha": "5.2.0",
"ts-node": "7.0.1",
"tslint": "5.11.0",

@@ -34,0 +38,0 @@ "typescript": "3.0.1"

@@ -26,6 +26,6 @@ [![Build Status](https://travis-ci.org/vitalyavolyn/node-vk-bot.svg?branch=master)](https://travis-ci.org/vitalyavolyn/node-vk-bot)

bot.get(/Hi|Hello|Hey/i, message => {
bot.get(/Hi|Hello|Hey/i, (message, exec, reply) => {
const options = { forward_messages: message.id }
bot.send('Hello!', message.peer_id, options)
reply('Hello!', options)
})

@@ -47,2 +47,3 @@ ```

- [`get`](#get)
- [`getPayload`](#getPayload)
- [`send`](#send)

@@ -57,2 +58,3 @@ - [`uploadPhoto`](#uploadPhoto)

- [sticker](#sticker)
- [payload](#payload)
- [poll-error](#poll-error)

@@ -107,5 +109,11 @@ - [command-notfound](#command-notfound)

```javascript
bot.get(/Hello/i, (msg, exec) => {
bot.get(/Hello/i, (msg, exec, reply) => {
console.log(msg)
reply('Hi!')
})
Аргументы callback:
msg - [объект сообщения](#the-message-object)
exec - результат `pattern.exec(text)`
reply - Функция для ответа на сообщение, принимает текст сообщения и необязательные параметры message.send
```

@@ -117,2 +125,15 @@

#### getPayload <a name="getPayload"></a>
То же самое, что и get, но для payload клавиатур
Это синтаксический сахар для [события `payload`](#payload)
```
bot.getPayload('{"command": "start"}', (msg, reply) => console.log(msg))
```
Аргументы: строка json и callback
-------
#### send <a name="send"></a>

@@ -130,3 +151,3 @@ Отправляет сообщение.

Принимает абсолютный путь к изображению
Принимает абсолютный путь к изображению или `Stream`
Возвращает Promise с [объектом фотографии](https://vk.com/dev/photos.saveMessagesPhoto)

@@ -137,2 +158,7 @@ ```javascript

})
let stream = fs.createReadStream('./kittens.png')
bot.uploadPhoto(stream).then(photo => {
console.log(photo)
})
```

@@ -192,3 +218,8 @@

#### payload <a name="payload"></a>
Вызывается при получении сообщения с json payload (используется в клавиатурах)
Возвращает объект `Message` и функцию [reply](#get)
-------
#### poll-error <a name="poll-error"></a>

@@ -195,0 +226,0 @@ Вызывается при ошибке при использовании LongPoll

@@ -28,6 +28,6 @@ [![Build Status](https://travis-ci.org/vitalyavolyn/node-vk-bot.svg?branch=master)](https://travis-ci.org/vitalyavolyn/node-vk-bot)

bot.get(/Hi|Hello|Hey/i, message => {
bot.get(/Hi|Hello|Hey/i, (message, exec, reply) => {
const options = { forward_messages: message.id }
bot.send('Hello!', message.peer_id, options)
reply('Hello!', options)
})

@@ -49,2 +49,3 @@ ```

- [`get`](#get)
- [`getPayload`](#getPayload)
- [`send`](#send)

@@ -59,2 +60,3 @@ - [`uploadPhoto`](#uploadPhoto)

- [sticker](#sticker)
- [payload](#payload)
- [poll-error](#poll-error)

@@ -110,11 +112,26 @@ - [command-notfound](#command-notfound)

```javascript
bot.get(/Hello/i, (msg, exec) => {
bot.get(/Hello/i, (msg, exec, reply) => {
console.log(msg)
reply('Hi!')
})
```
The argument passed to callback is a [`Message`](#the-message-object) object and result of `pattern.exec(text)`.
The argument passed to callback is a [`Message`](#the-message-object) object, result of `pattern.exec(text)` and a `reply` function.
`reply` takes text as first argument and optional message.send parameters as second.
-------
#### getPayload <a name="getPayload"></a>
Listens for specific `payload` (used for keyboards)
This is a syntactic sugar for the [`payload` event](#payload)
```
bot.getPayload('{"command": "start"}', (msg, reply) => console.log(msg))
```
Arguments: json string and listener
-------
#### send <a name="send"></a>

@@ -132,3 +149,3 @@ Sends message.

The only parameter is an absolute path to picture.
The only parameter is an absolute path to picture or a stream object.
Returns a Promise that resolves with a [photo object](https://vk.com/dev/photos.saveMessagesPhoto)

@@ -139,2 +156,7 @@ ```javascript

})
let stream = fs.createReadStream('./kittens.png')
bot.uploadPhoto(stream).then(photo => {
console.log(photo)
})
```

@@ -194,3 +216,9 @@

#### payload <a name="payload"></a>
Emitted when bot recieves a message with json payload (used in keyboards)
Emits `Message` object and [reply function](#get)
-------
#### poll-error <a name="poll-error"></a>

@@ -197,0 +225,0 @@ The poll-error event is emitted whenever there is an error occurred in LongPoll.

@@ -8,3 +8,3 @@ import * as rq from 'request-promise-native'

export default function poll (bot, delay: number = DEFAULT_DELAY) {
export default function poll(bot, delay: number = DEFAULT_DELAY) {
return bot.api('groups.getLongPollServer', { group_id: bot.options.group_id })

@@ -18,7 +18,7 @@ .then(res => {

// перезапуск при ошибке
// restart on error
return poll(bot, delay)
})
function request (url, delay: number) {
function request(url, delay: number) {
return rq(url, { json: true })

@@ -33,3 +33,3 @@ .then(res => {

url = url.replace(/ts=.*/, `ts=${res.ts}`) // ставим новое время
url = url.replace(/ts=.*/, `ts=${res.ts}`) // set new timestamp

@@ -36,0 +36,0 @@ if (!res.failed && res.updates && res.updates.length > 0) {

import { EventEmitter } from 'events'
import * as rq from 'request-promise-native'
import * as fs from 'fs'
import * as stream from 'stream'

@@ -8,13 +9,15 @@ import poll from './functions/poll'

import { VKError, VKExecuteResponse, VKResponse } from './interfaces/APIResponses'
import { UploadedPhoto } from './interfaces/UploadedPhoto'
import { Message } from './interfaces/Message'
import { UserEvent } from './interfaces/UserEvent'
import { MessageSendParams } from './interfaces/MessageSendParams'
import UploadedPhoto from './interfaces/UploadedPhoto'
import Message from './interfaces/Message'
import UserEvent from './interfaces/UserEvent'
import MessageSendParams from './interfaces/MessageSendParams'
export interface Options {
token: string,
api?: { lang?: string, v?: string},
api?: { lang?: string, v?: string },
group_id: number
}
export type replyFunc = (text?: string, params?: MessageSendParams) => Promise<VKResponse>
export class Bot extends EventEmitter {

@@ -25,3 +28,3 @@ _events: Object = {}

constructor (public options: Options) {
constructor(public options: Options) {
super()

@@ -36,8 +39,4 @@

* Access VK API
* @param method
* @param params Optional request params
*
* @returns {Promise}
*/
api (method: string, params: any = {}) : Promise<VKResponse | VKExecuteResponse> {
api(method: string, params: any = {}): Promise<VKResponse | VKExecuteResponse> {
let o = this.options

@@ -70,8 +69,4 @@ if (o.api) {

* Send messages
* @param text Message text
* @param peer peer_id (https://vk.com/dev/messages.send)
*
* @returns {Promise}
*/
send (text: string, peer: number, params: MessageSendParams = {}) : Promise<VKResponse> {
send(text: string, peer: number, params: MessageSendParams = {}): Promise<VKResponse> {
params.message = params.message || text

@@ -84,5 +79,4 @@ params.peer_id = params.peer_id || peer

* Process Callback API response when using webhook
* @param res Callback API response
*/
processUpdate (res: any) {
processUpdate(res: any) {
if (res.type === 'message_new') return this._update(res)

@@ -93,6 +87,4 @@ }

* Start polling
* @param {number} poll_delay A delay before a restart of the Long Poll client
* @returns The bot object
*/
start (poll_delay?: number) {
start(poll_delay?: number) {
this.on('update', this._update)

@@ -103,3 +95,3 @@ poll(this, poll_delay)

stop () {
stop() {
this._stop = true

@@ -113,6 +105,4 @@ this.removeListener('update', this._update)

* Listens on specific message matching the RegExp pattern
* @param pattern
* @returns The bot object
*/
get (pattern: RegExp, listener: (msg?: Message, exec?: RegExpExecArray) => any) {
get(pattern: UserEvent['pattern'], listener: UserEvent['listener']) {
this._userEvents.push({

@@ -124,7 +114,21 @@ pattern, listener

getPayload(jsonString: string, listener: (msg?: Message, reply?: replyFunc) => void) {
this.on('payload', (msg, reply) => {
if (JSON.stringify(JSON.parse(msg.payload)) === JSON.stringify(JSON.parse(jsonString))) {
listener(msg, reply)
}
})
}
/**
* Upload photo
* @returns {Promise}
*/
uploadPhoto (path: string) : Promise<UploadedPhoto> {
uploadPhoto(photo: string | stream.Stream): Promise<UploadedPhoto> {
let photoStream: stream.Stream
if (typeof photo === 'string') {
photoStream = fs.createReadStream(photo)
} else if (photo instanceof stream.Stream) {
photoStream = photo
}
return this.api('photos.getMessagesUploadServer')

@@ -135,3 +139,3 @@ .then(server => rq({

formData: {
photo: fs.createReadStream(path)
photo: photoStream
},

@@ -152,11 +156,9 @@ json: true

* get events - YOU SHOULD NOT USE THIS
*
* @param {object} update
*/
private _update (update) {
private _update(update) {
let msg = update.object
const hasAttachments : boolean = msg.attachments.length
const hasAttachments: boolean = msg.attachments.length
const message : Message = {
const message: Message = {
id: msg.id,

@@ -173,2 +175,9 @@ peer_id: msg.peer_id,

const reply = (text: string, params: MessageSendParams = {}) => this.send(text, message.peer_id, params)
if (msg.payload) {
message.payload = msg.payload
this.emit('payload', msg, reply)
}
if (hasAttachments && msg.attachments[0].type === 'sticker') return this.emit('sticker', message)

@@ -186,3 +195,7 @@ if (hasAttachments && msg.attachments[0].type === 'doc' && msg.attachments[0].doc.preview.audio_msg) return this.emit('voice', message)

ev.listener(message, ev.pattern.exec(message.text))
ev.listener(
message,
ev.pattern.exec(message.text),
reply
)
}

@@ -189,0 +202,0 @@ }

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

export interface Message {
export default interface Message {
id: number,

@@ -10,3 +10,4 @@ peer_id: number,

conversation_message_id: number,
fwd_messages: any
fwd_messages: any,
payload?: string
}

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

export interface MessageSendParams {
export default interface MessageSendParams {
message?: string,

@@ -7,3 +7,3 @@ peer_id?: number,

chat_id?: string,
user_ids?: string, // list of comma-separated numbers
user_ids?: string, // list of comma-separated numbers, max 100
lat?: number,

@@ -14,5 +14,4 @@ long?: number,

sticker_id?: number,
// deprecated
guid?: number
keyboard?: string,
payload?: any
}

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

export interface UploadedPhoto {
export default interface UploadedPhoto {
id: number,

@@ -3,0 +3,0 @@ album_id: number,

@@ -1,6 +0,9 @@

import { Message } from '..'
import Message from './Message'
import MessageSendParams from './MessageSendParams'
import { VKResponse } from './APIResponses'
import { replyFunc } from '..'
export interface UserEvent {
export default interface UserEvent {
pattern: RegExp,
listener(msg?: Message, exec?: RegExpExecArray) : any
listener(msg?: Message, exec?: RegExpExecArray, reply?: replyFunc): void
}

@@ -18,4 +18,5 @@ {

"./examples",
"./node_modules"
"./node_modules",
"./test"
]
}

@@ -37,7 +37,7 @@ {

{
"call-signature": "space",
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "space"
"variable-declaration": "nospace"
}

@@ -58,4 +58,4 @@ ],

"array-type": [
true,
"array"
true,
"array"
],

@@ -62,0 +62,0 @@ "jsdoc-format": true

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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