Git Product home page Git Product logo

node-vk-call's Introduction

vk-call Build Status

Simple API wrapper for VK.com social network. Inspired by node-vk-sdk.

Installation

npm install vk-call

Usage

VK object

const VK = require('vk-call').VK;

constructor(config: Object)

config options:

  • token — OAuth token for authorized requests
  • timeout — request timeout in milliseconds
  • version — API version
  • api_url — base url for api calls
  • groupId — group id for Long Poll API bots

vk.call(method: String, params: Object) : Promise

Single api call, returns promise.

  • method — method name, i.e. 'users.get'
  • params — method parameters, i.e. { id: 1 }

Example:

const VK = require('vk-call').VK;
const vk = new VK({
  token: "YOUR TOKEN HERE",
  version: "5.124",
  timeout: 10000
});

api.call("users.get", { user_ids: 1 })
  .then(users => console.log(users));

vk.persistentLongpoll() : { sink: EventEmitter, abort: Function }

Start Long Poll API for group bots.

Example:

const VK = require('vk-call').VK;
const vk = new VK({
  token: "YOUR TOKEN HERE",
  version: "5.124",
  timeout: 10000,
  groupId: 1,
});

const longpoll = vk.persistentLongpoll();
longpoll.sink.on("data", (events) => {
  events.forEach((event) => {
    const message = event.object.message;
    if (/^hello/i.test(msg.text)) {
      vk.call('messages.send', {
        user_id: message.from_id,
        message: "Hi!",
        random_id: 0,
      }).catch((error) => console.error(error));
    }
  })
});

vk.chain() : Chain

Intitializes and returns Chain object

Chain object

This object is responsible for chaining api calls and batching them with the help of execute method. It allows you to legally get around some of request rate limits. However, remember that you can't chain more than 25 api calls.

It's better to create Chain object via vk.chain method.

constructor(api: vk)

  • api — initialized instance of vk

append(method: String, params: Object) : Promise

This method is very similar to vk.call, but used for chaining. Returned promise will be resolved after successfull execute call. Promise will return value as if it is a single api call. It means, that only data returned single for this request will be supplied.

You can't call Chain.append after you called Chain.done, you have to create new Chain.

done() : Promise

You must call this method, when you appended enough requests.

This method will return an array of results for chained methods in the same order in which you appended calls.

Empty chain will return Promise([]).

Exmaple:

const VK = require('vk-call').VK;
const vk = new vk({
  token: "YOUR TOKEN",
  version: "5.124"
});

var chain = vk.chain();

chain.append("users.get", { user_ids: 1 })
  .then((users) => console.log(users));
  
chain.append("groups.getById", { group_ids: 1 })
  .then(groups => console.log(groups));
  
chain.done()
  .then((result) => {
    var users = result[0];
    var groups = result[1];
    console.log(users, groups);
  });
  
chain.append("users.get", { user_ids: 2 });

// Throws error, because chain ended after done

Errors

All errors are wrapped with VKError object wich you can request as:

var VKError = require('vk-call').errors.VKError;

There are two type of errors:

  • domain errors — all errors, that returned by VK API
  • failures (not domain errors) — all other errors (timeouts, no internet, code issues etc.)

Most of error codes that can be returned by VK API are represented by constants:

var errors = require('vk-call').errors;
assert(errors.NOT_DOMAIN_ERROR === -1);
assert(errors.UKNOWN_ERROR === 1);
assert(errors.UNKNOWN_METHOD === 3);

This codes are stored in type property of VKError instance. You can find the whole list of constants here.

There is also name property, it can have two values:

var errors = require('vk-call').errors;
errors.NOT_DOMAIN_NAME
errors.DOMAIN_NAME

This property is handy for distinguishing API errors from any other failures.

Also there is an originalError property were you can get the original error (json or Error object).

Tests

This library is mostly covered with tests. To run test, use npm test command. For developing, use npm test-watch command.

We use mocha for testing. All test files are stored in test/**/*.

License

Distributed under MIT LICENSE

node-vk-call's People

Contributors

flyink13 avatar maxkoryukov avatar mhamlet avatar termina1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-vk-call's Issues

API Error: Access denied when trying to post to the wall

I got the token by authorizing the user with this URL:

const VK_CLIENT_ID = '1231231';

const photos = 4;
const wall = 8192;
const offline = 65536;
const scope = offline + wall + photos;

const URL = `https://oauth.vk.com/authorize?client_id=${VK_CLIENT_ID}&display=popup&redirect_uri=http://example.com/auth/vk&scope=${scope}&response_type=token&v=5.78`;

I followed these instructions:
https://vk.com/dev.php?method=implicit_flow_user

const vkCall = require('vk-call');

const vk = new vkCall.VK({
  token: accessToken,
  version: '5.78',
  timeout: 10000,
});

vk
  .call('wall.post', {
    message: 'testing a wall post text message',
  })
  .then(res => console.log(res))
  .catch(err => console.log(err));
{ [domain_name: Domain error: Access denied: no access to call this method]
  type: 15,
  name: 'domain_name',
  message: 'Domain error: Access denied: no access to call this method',
  originalError:
   { error_code: 15,
     error_msg: 'Access denied: no access to call this method',
     ... } }

What could be the issue?

Thanks a lot

service token

при некоторых запросах получаю ошибку

Application authorization failed: method is unavailable with service token.

как и куда надо передавать service token?
в коде я про него не нашел упоминаний

await chain.done(); не работает

Я попытался использовать конструкцию вида : var result = await chain.done(); с включенным флагом --harmony в node 8.5.0. И это не сработало, переменная result undef, сам объект chain https://yadi.sk/i/WeiNizc13NCiAx. Что я делаю не так ? Ф-ция в которой вызываю done имеет сигнатуру async function. В документации написано, что done() возвращает Promise

chain.append(...) возвращает одни и те же наборы сообщений с разными offcet

Имеем следующий код
async function getMessageFromDialog(userId, count, offcet, api) { if (count == -1) return new Array(); var chain = api.chain(); chain.append("messages.getHistory", { count: 200, user_id: userId, offcet: 200 }); chain.append("messages.getHistory", { count: 200, user_id: userId, offcet: 400 }); .... chain.append("messages.getHistory", { count: offcet, user_id: userId, offcet: offcet * 24 }); chain.done().then((result) => { var anser = new Array(); for (var i = 0; i < result.length; i++) { anser.push(result[i]); } if(count >= 0) return anser.push(getMessageFromDialog(userId, count - 1, offcet * 26, api)); });
который должен рекурсивно получать историю из диалога.
То, что возвращает код - на двух скриншотах ниже, показываю 0 и 1 элементы массива.
https://yadi.sk/i/FqLMXo8d3NJeYG
https://yadi.sk/i/qOtpAIiF3NJeZJ
Как видно, id сообщений одинаковый, и код работает не правильно. При этом, если повторить в браузере запрос с такими же параметрами - https://yadi.sk/i/19NagvZi3NJf2M все работает.
node v8.5.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.