Code Monkey home page Code Monkey logo

node-vk-sdk's Introduction

node-vk-sdk

VK API SDK for Node.js

Installation

To install the stable version:

npm install --save node-vk-sdk

This assumes you are using npm as your package manager. If you don’t, you can access these files on unpkg, download them, or point your package manager to them.

Importing

You can import SDK using ES6 modules:

import {VKApi, ConsoleLogger} from 'node-vk-sdk'

Or using require:

const {VKApi, ConsoleLogger} = require('node-vk-sdk')

Usage

import {VKApi, ConsoleLogger} from 'node-vk-sdk'

let api = new VKApi({
    logger: new ConsoleLogger()
})

api.usersGet({ userIds: ['1'] })
    .then(response => {
        console.log(response)
    })

VKApi constructor options

interface VKApiOptions {
    lang?: string|number,
    testMode?: number,
    logger?: BaseLogger,
    token?: string,
    timeout?: number,
    requestsPerSecond?: number,
    useQueue?: boolean
}
  • lang? - Determines the language for the data to be displayed on. For example country and city names. If you use a non-cyrillic language, cyrillic symbols will be transtiterated automatically
    en – English, ru – Russian, ua – Ukrainian, be – Belorussian, es – Spanish, fi – finnish, de – German, it – Italian.
    Numeric format from account.getInfo is supported as well.

  • test_mode? - 1 – allows to send requests from a native app without switching it on for all users.

  • logger? - Logger class that implements BaseLogger No logging will be used logger is not passed

  • token? - Access token

  • timeout? - Network timeout in ms

  • requestsPerSecond - Maximum requests per second, default is 3

  • useQueue - If useQueue is true, then SDK will limit number of requests per second at requestsPerSecond

Calling methods

All api methods returning Promise, so you can use them as Promise or as async functions. Methods arguments are described in interfaces, so you need to pass object implementing that interface, for example users.get props interface:

export interface UsersGetParams {
    /**
     * User IDs or screen names ('screen_name'). By default, current user ID.
     */
    user_ids?: string[],
    /**
     * Profile fields to return. Sample values: 'nickname', 'screen_name', 'sex', 'bdate' (birthdate), 'city', 'country', 'timezone', 'photo', 'photo_medium', 'photo_big', 'has_mobile', 'contacts', 'education', 'online', 'counters', 'relation', 'last_seen', 'activity', 'can_write_private_message', 'can_see_all_posts', 'can_post', 'universities',
     */
    fields?: string[],
    /**
     * Case for declension of user name and surname: 'nom' — nominative (default), 'gen' — genitive , 'dat' — dative, 'acc' — accusative , 'ins' — instrumental , 'abl' — prepositional
     */
    name_case?: string,
    /**
     * access token
     */
    access_token?: string
}

All props interfaces have accessToken property, that token will be used instead of token passed to VKApi

Calling example:

api.usersGet({ user_ids: ['1'] })
    .then(response => {
        console.log(response)
    })


// or we can call it as async function

let response = await api.usersGet({ user_ids: ['1'] })

Direct call methods:

// makes plain call & returns contents of "response" property of server response
public async call(method: string, params: Object): Promise<any>

// Makes api call and if there was
// server-side error or requests limit was reached
// repeats the call after some timeout
public async callWithRetry(method: string, params: Object): Promise<any>

Bots Long Poll API

To receive group updates using Bots Long Poll API use BotsLongPollUpdatesProvider class:

import {VKApi, ConsoleLogger, BotsLongPollUpdatesProvider} from 'node-vk-sdk'

let api = new VKApi({
    token: 'GROUP_TOKEN_HERE',
    logger: new ConsoleLogger()
})

let updatesProvider = new BotsLongPollUpdatesProvider(api, GROUP_ID_HERE)

updatesProvider.getUpdates(updates => {
    console.log('got updates: ', updates)
})

node-vk-sdk's People

Contributors

alatushkin avatar arnidan avatar grebenschikov avatar naltox avatar tonyspb 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  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

node-vk-sdk's Issues

photosGetWallUploadServer возвращает undefined

При вызове метода api.photosGetWallUploadServer возвращает undefined
из-за ошибки в логике работы либо в VKApi.handleResponse либо в PhotosGetWallUploadServerResponse.deserialize

При выполнении wall.get ответ false

по какой-то причине не выходит сделать запрос.

Group.api('wall.get', {owner_id: '-183816027', domain: 'starcheebots'}, (data, error) => {
   console.log(data)
   if (error) {
      console.log('Ошибка выполнения метода', error)
   } else {
      console.log(data)
   }
 })

и выводит постоянно false. Почему?

Upload Image to VK Servers.

Hi, guys! I have been trying to upload a photo to the VK server for a long time, but all the time I get an empty photo.

I get the upload link using api.photosGetMessagesUploadServer, but I can't send working POST request.

Can you help me?

после 1-2 часа работы прилетает undefined и бот падает

Короче, не знаю, что я делаю не так, (уже всё перевробовал) но бот работает ровно 1-2 часа и потом спамит тем, что у него приходит пустота:
image

Я уже и return пихал везде и пытался функцию стопать, когда прилетает undefined. Но увы, ничего не получилось, как он присылал undefined так и присылает. Может есть вариант, как можно перезапускать функцию после ошибки?

Not working.

Скопировал example из доки и вставил в index.js. В итоге мне приходит пустой ответ [].

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.