class VK { /** * Конструктор * * @param {MainOptions} options */ constructor (options = {}) { this.options = Object.assign({}, defaultMainOptions); this.request = request.defaults({ method: 'POST', json: true }); this.api = new Api(this); this.auth = new Auth(this); this.upload = new Upload(this); this.collect = new Collect(this); this.longpoll = new Longpoll(this); this._captchaHandler = null; this.setOptions(options); } /** * Возвращает текущую версию API * * @return {string} */ get API_VERSION () { return API_VERSION; } /** * Устанавливает токен * * @param {string} token * * @return {this} */ setToken (token) { this.options.token = token; return this; } /** * Устанавливает опции * * @param {Object} options * * @return {this} */ setOptions (options) { Object.assign( this.options, this._transformOptions(options) ); return this; } /** * Устанавливает обработчик капчи * * @param {?function} handler * * @return {this} */ setCaptchaHandler (handler) { this._captchaHandler = handler; return this; } /** * Возвращает класс для работы с цепочками методов * * @return {Chain} */ chain () { return new Chain(this); } /** * Вызов хранимой процедуры * * @param {string} name * @param {Object} params * * @return {Promise} */ procedure (name, params) { return this.api.call(`execute.${name}`, params); } /** * Упрощённый вызов целой цепочки метода * * @param {string} method * @param {Array} queues * * @return {Promise} */ executes (method, queues) { return Chain.executes(this, method, queues); } /** * Разбирает ссылку ВКонтакте * * @param {string} uri * * @return {Promise} */ parseLink (uri) { return parseLink(this.api, uri); } /** * Возвращает токен * * @return {?string} */ getToken () { return this.options.token; } /** * Собирает прикрипление из переданных значений * * @param {string} type * @param {mixed} attachments * * @return {mixed} */ getAttachment (type, attachments) { type = type.toLowerCase(); if (!Array.isArray(attachments)) { return getAttachment(type, attachments); } return attachments.map((attachment) => getAttachment(type, attachment)); } /** * Возвращает ссылку на маленькую фотографию * * @param {Object} photo * * @return {string} */ getSmallPhoto (photo) { return getSmallPhoto(photo); } /** * Возвращает ссылку на среднюю фотографию * * @param {Object} photo * * @return {string} */ getMediumPhoto (photo) { return getMediumPhoto(photo); } /** * Возвращает ссылку на большую фотографию * * @param {Object} photo * * @return {string} */ getLargePhoto (photo) { return getLargePhoto(photo); } /** * Разбирает опции * * @param {Object} options * * @return {Object} */ _transformOptions (options) { options = Object.assign({}, options); if ('id' in options) { options.id = +options.id; } if ('scope' in options) { if (Array.isArray(options.scope)) { options.scope = options.scope.join(','); } else if (options.scope === 'all') { options.scope = MAX_SCOPE.join(','); } } if ('proxy' in options) { let proxy = options.proxy; delete options.proxy; /* На случай лайфхака :/ */ if (!proxy.startsWith('http')) { proxy = 'http://' + proxy; } const { protocol, auth, host, path } = url.parse(proxy); const params = {}; if (auth !== null) { params.headers = { 'Proxy-Authorization': 'Basic ' + Buffer.from(auth).toString('base64') }; } params.proxy = `${protocol}//${host}${path || ''}`; this.request = this.request.defaults(params); } return options; } /** Дальше устаревшее */ setting (settings) { debug('vk.setting depre ...
n/a
(type, attachment) => ( type + attachment.owner_id + '_' + attachment.id )
...
console.log('Url small compare:', photo.photo_130 === urlSmall); // => true
});
```
### getAttachment
Позволяет получить прикрепления с [объектов](https://vk.com/dev/objects)
```javascript
vk.getAttachment(type, attachment); // => array / string
```
| Параметр | Тип | Описание |
|------------|----------------|---------------------|
| type | string | Тип прикрепления |
| attachment | array / object | Объект прикрепления |
...
(photo) => ( photo.photo_2560 || photo.photo_1280 || getMediumPhoto(photo) )
...
Если метод не находит ссылку на фотографию он будет искать меньшего размера пока не найдёт существующие разрешение
#### getLargePhoto
Возвращает фотографии разрешения `2560` или `1280`
```javascript
vk.getLargePhoto(photo); // => string
```
| Параметр | Тип | Описание |
|----------|--------|-------------------|
| photo | object | Объект фотографии |
#### getMediumPhoto
...
(photo) => ( photo.photo_807 || photo.photo_604 || getSmallPhoto(photo) )
...
|----------|--------|-------------------|
| photo | object | Объект фотографии |
#### getMediumPhoto
Возвращает фотографии разрешения `807` или `604`
```javascript
vk.getMediumPhoto(photo); // => string
```
| Параметр | Тип | Описание |
|----------|--------|-------------------|
| photo | object | Объект фотографии |
#### getSmallPhoto
...
(photo) => ( photo.photo_130 || photo.photo_75 )
...
|----------|--------|-------------------|
| photo | object | Объект фотографии |
#### getSmallPhoto
Возвращает фотографии разрешения `130` или `75`
```javascript
vk.getSmallPhoto(photo); // => string
```
| Параметр | Тип | Описание |
|----------|--------|-------------------|
| photo | object | Объект фотографии |
#### Пример работы с методами
...
function parseForm($) { const $form = $('form[action][method]'); const fields = {}; for (const { name, value } of $form.serializeArray()) { fields[name] = value; } return { action: $form.attr('action'), fields }; }
n/a
function parseSecurityForm(response, { login, phone }, $ = cheerio(response.body)) { let number; if (phone !== null) { number = phone; } else if (login !== null && !login.includes('@')) { number = login; } else { throw new AuthError({ message: 'Missing phone number in the phone or login field' }); } if (typeof number === 'string') { number = number.trim().replace(/^(\+|00)/, ''); } const $field = $('.field_prefix'); const prefix = $field.first().text().trim().replace('+', '').length; const postfix = $field.last().text().trim().length; number = number.toString(); let { action, fields } = parseForm($); fields.code = number.slice(prefix, number.length - postfix); if (!action.startsWith('https://')) { action = 'https://' + response.request.uri.host + action; } return { action, fields }; }
n/a
class Message extends BaseMessage { /** * Конструктор * * @param {VK} vk * @param {Object} message */ constructor (vk, message) { super(vk, message); this.chat = null; const attachments = message[7]; if (this.peer > SHEAR_CHAT_PEER) { this.user = +attachments.from; this.title = unescape(message[5]); this.chat = this.peer - SHEAR_CHAT_PEER; this.from = 'chat'; } else if (this.peer < 0) { this.user = null; this.title = null; this.admin = +attachments.from_admin; this.from = 'group'; } else { this.user = this.peer; this.title = null; this.from = 'dialog'; } if (message[6].length !== 0) { this.text = unescape(message[6]).replace(brReplace, '\n'); } else { this.text = null; } this.flags = parseFlags(message[2], this.isGroup()); this.attachments = parseAttachments(attachments); this.hasEmoji = 'emoji' in attachments; if ('geo' in attachments) { this.attachments.geo = { id: attachments.geo, provider: +attachments.geo_provider }; } this._fwd = attachments.fwd || null; } /** * Отвечает на сообщение * * @param {mixed} text * @param {Object} params * * @return {Promise} */ reply (text, params = {}) { if (typeof text === 'object') { params = text; } else { params.message = text; } params.forward_messages = this.id; return this.send(params); } /** * Проверяет наличие флага * * @param {string} name * * @return {boolean} */ hasFlag (name) { return this.flags.includes(name); } /** * Проверяет наличие прикриплений * * @return {boolean} */ hasAttachments () { return Object.keys(this.attachments).length > 0; } /** * Проверяет наличие прикрипления * * @param {string} name * * @return {boolean} */ hasAttachment (name) { return name in this.attachments; } /** * Проверяет наличие пересылаемых сообщений * * @return {boolean} */ hasFwd () { return this._fwd !== null; } /** * Сообщение из диалога * * @return {boolean} */ isDialog () { return this.from === 'dialog'; } /** * Сообщение из беседы * * @return {boolean} */ isChat () { return this.from === 'chat'; } /** * Сообщения из сообщества * * @return {boolean} */ isGroup () { return this.from === 'group'; } /** * Возвращает пересылаемые сообщения * * @return {Array} */ getFwd () { if (!this.hasFwd()) { return []; } if (Array.isArray(this._fwd)) { return this._fwd; } this._fwd = parseFwds(this._fwd); return this._fwd; } /** * Возвращает свойства которые нужно вывести * * @return object */ inspect (depth, options) { const print = Object.assign(super.inspect(depth, options), { user: this.user, chat: this.chat, title: this.title, text: this.text, from: this.from, hasEmoji: this.hasEmoji, flags: this.flags, attachments: this.attachments }); return this.constructor.name + ' ' + inspect(print, options); } }
n/a