Socket
Socket
Sign inDemoInstall

easyvk

Package Overview
Dependencies
9
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

easyvk

Functional library for support VKontake API (ВКонтакте API) on node.js


Version published
Maintainers
1
Weekly downloads
47
decreased by-12.96%

Weekly downloads

Readme

Source

EasyVK logo

EasyVK (VKontakte API Manager) v2.0

This library helps you easily create a javascript application with VKontakte API! Official VK API: vk.com/dev/

Codacy Badge Build Status Downloads Issues Node version support Npm version released

CommunityДокументация на русском

Для русскоязычных

Данная библиотека создана для того, чтобы VKontakte API имел удобную поддержу на node.js. С помощью этой библиотеки вы можете делать все, что позволяет официально ВКонтакте API, и не только. Так как я предполагаю, что большинство людей, кто скачивает - владеют русским с рождения, то я написал документацию для этого модуля на этом языке. Если вы хотите помочь в развитии этой библиотеки, вступайте в наше сообщество и предлагайте, что можно улучшить и добавить. Если вы хотите помочь нам кодом - делайте это на github. Ниже написано, что можно делать при помощи EasyVK.

Installing

Download and install Node.js. Create a project and install easyvk with npm:

npm i easyvk --save

Yarn installation

If you are using a yarn package manager, you can add easyvk to project so

yarn add easyvk

Example usage

You can test the library without installing on npm runkit. Copy this code and paste it in the code area, don't forget to change username and password.


const easyvk = require("easyvk")

//Authenticating user
easyvk({
   username: 'your_login',
   password: 'your_password',
   save: false,

   // By default are vk android credentials 
   clientId: 'YOUR_CLIENT_ID',
   clientSecret: 'YOUR_CLIENT_SECRET'
}).then(vk => {
  
   //Getting user id from authenticated session
   let me = vk.session.user_id || 356607530 //Or your account id
   
   //Sending a message using messages.send method
   vk.call('messages.send', {
      message: 'Hi',
      user_id: me,
      random_id: easyvk.randomId()
   }).then((vkr) => console.log(vkr))
   
}).catch(console.error)


EasyVK can help you

  • Create Bots
  • Manage groups
  • Use LongPoll: Bots LongPoll (groups) and User LongPoll
  • Create high loading projects with highload mode
  • Use Callback API (like creating your server to listen to group events)
  • Manage your stream based on official Streaming API, listen to events and collect data to create statistic and metrics
  • Upload your files to the server
  • Call official VKontakte API methods
  • Use my widgets - non-official instruments for everyday tasks
  • Use helpers - utility for creating something that you need everyday
  • Use saved session, cache data to saved session
  • Catch errors like Captcha error and others
  • Configure all that you want or not (utils can bee disabled or enabled by you)

EasyVK provide

  • Promises and async / await based library
  • Authentication support: groups, users, applications, password + username
  • Informative documentation
  • Regular updates and support for newest features
  • Two factor authentication support
  • Easy working with captcha errors and captcha handlers
  • Easy customize your requests and easy control them

You can read documentation here

Что дает EasyVK

Узнайте, зачем Вам может понадобиться Easy VK, и что именно он может вам дать!

Режим параллельных запросов

В Easy VK есть режим highload, включая который, вы сможете использовать все возможности API ВКонтакте даже при большом количестве запросов. Этот режим дает знать библиотеке, что все запросы необходимо выполнять через метод execute, который выполняет до 25 запросов в секунду.

Может пригодиться чат-ботам, в которых сообщений в тысячи раз больше, чем пользователей.

easyvk({
  token: "{GROUP_TOKEN}",
  reauth: true,
  mode: 'highload' || {
    timeout: 10,
    name: 'highload'
  }
}).then(async (vk) => {
  
  let connection = await vk.bots.longpoll.connect();

  connection.on('message_new', console.log);

});

Плагины

Теперь в Easy VK будет поддерживаться разработка новых плагинов. Функционал API для плагинов будет дополняться по мере просьб и нужд разработчиков, я всегда буду рад обновлениям.

  
  // Разработка простейшего плагина для отправки сообщений
  vk.use(async ({thread, next}) => {
    if (thread.method == "messages.send") {
      // Автоматически меняем типа запроса на POST
      thread.methodType = "post";

      if (Number(thread.query.v) >= 5.90) {

        /* Для новых версий API ВКонтакте для сообщений 
           требует поля random_id (уникальный id сообщения) */
        thread.query.random_id = easyvk.randomId(); 
      }

    }

    // Запускаем следующий плагин
    await next();
  });

Client Credentials Flow и авторизация по приложению


  easyvk({
    clientId: '{APP_SECRET_CODE}',
    clientSecret: '{CLIENT_SECRET_CODE}',
    utils: {
      streamingAPI: true
    }
  }).then((vk) => {

    const StreamingAPI = vk.streamingAPI

    return StreamingAPI.connect().then((connection) => {

      connection.getRules().then((vkr) => {
        console.log(vkr.rules);
      });
      
      connection.on("post", console.log);

    });
  });

LongPoll API

Создавайте своих чат-ботов с помощью Easy VK и его возможностей LongPoll API

  
  //bots
  vk.bots.longpoll.connect({
    forGetLongPollServer: {
      grop_id: vk.session.group_id
    }
  }).then((connection) => {
    
    connection.on("message_new", (msg) => {
      
      //On message event
      vk.call("messages.send", {
        peer_id: msg.from_id,
        message: "Reply it!",
        random_id: easyvk.randomId()
      }).catch(console.error);

    });

  });

  //user longpoll
  vk.longpoll.connect({}).then((connection) => {
    connection.on("message", (event) => {
      console.log(event);
    });
  
    //changed state of message
    connection.addEventCodeListener(3, (eventChangeState) => {
      console.log(eventChangeState);
    });
  });


Streaming API

Собирайте статистические данные о популярности тех или инных продуктов, проектов - чего угодно! Это позволит Вам знать, о чем пишут пользователи ВКонтакте, и кто из них - ваши клиенты!

    
  easyvk({
    clientId: '{APP_SECRET_CODE}',
    clientSecret: '{CLIENT_SECRET_CODE}',
    utils: {
      streamingAPI: true
    }
  }).then(vk => {
    vk.streamingAPI.connect((stream) => {
        
      stream.initRules({
        key1: 'кошка',
        key2: 'собака -кот'
      }).then((changes) => {
        
        console.log(changes.changedRules, changes.deletedRules, changes.addedRules);

        stream.on("post", (postEvent) => {
          console.log("Post info: ", postEvent);
        });
        
        //.on(...)
        //.on("share")
        //.on("comment") etc...
      });

    });
  })

Callback API

Создавайте чат-ботов (и не только) с помощью Callback API, имея собственный сервер с открытым доступом в интернете.


  easyvk.callbackAPI.listen({
    port: process.env.PORT || 8080,
    groups: [
      {
        groupId: 11,
        confirmCode: 'TestConfirmationCode',
        secret: 'GroupPassword'
      },
      {
        /*....*/
      }
    ]
  }).then((connection) => {
    
    connection.on('message_new', (msg) => {
        console.log(msg.group_id);
    });

  }).catch(console.error);

Все остальное находится на сайте-документации проекта.

Keywords

FAQs

Last updated on 17 Sep 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

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