Giter Club home page Giter Club logo

easyvk's Introduction

EasyVK logo

EasyVK (VKontakte API Manager) v2.0 (DEPRECATED)

This package has been deprecated and will no longer be supported.

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);

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

easyvk's People

Contributors

ciricc 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  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

easyvk's Issues

Не ставится

`npm i easyvk --save

added 50 packages, removed 2 packages, changed 2 packages, and audited 170 packages in 3s

2 packages are looking for funding
run npm fund for details

5 vulnerabilities (3 high, 2 critical)

To address all issues (including breaking changes), run:
npm audit fix --force

Run npm audit for details.
(base) MacBook-Pro:libs хххх$ npm fund
ххх@1.0.0
├── https://github.com/sponsors/feross
│ └── [email protected]
└── https://github.com/sponsors/epoberezkin
└── [email protected]`

Fatal Error

Everyday i get the same error:
[VK ERROR] FetchError: network timeout at: https://lp.vk.com/wh179713434...

Can you explain me, how to implement auto reconnect for bot longpoll?

UnhandledPromiseRejectionWarning

(node:220) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'json' of undefined at self.lpConnection.fetch__default.default.catch.then (/root/node_modules/easyvk/lib/bundle.js:2304:18) at process._tickCallback (internal/process/next_tick.js:68:7) (node:220) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 8)

Crash

При использовании нескольких групп, крашится из-за данной строки

	groups: [
		{
			groupId: 1,
			secret: '1',
			confirmCode: '1'
		},
		{
			groupId: 2,
			secret: '2',
			confirmCode: '2'
		}
	]

if (self._vk.session.group_id) {

UnhandledPromiseRejectionWarning в audio.get при заданном offset

При попытке задать offset > 0 выдаёт ошибку UnhandledPromiseRejectionWarning.

(node:132) UnhandledPromiseRejectionWarning: Error
at Request.request.post [as _callback] (.......\node_modules\easyvk\src\utils\AudioAPI.js:397:23)
at Request.self.callback (.......\node_modules\request\request.js:185:22)
at Request.emit (events.js:189:13)
at Request. (.......\node_modules\request\request.js:1161:10)
at Request.emit (events.js:189:13)
at IncomingMessage. (.......\node_modules\request\request.js:1083:12)
at Object.onceWrapper (events.js:277:13)
at IncomingMessage.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1103:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:132) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:132) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Сам код:

vk.http.loginByForm({
        cookies: __dirname + "/mycookies.json"
    }).then(({client: Client}) => {
        Client.audio.get({
            owner_id: -45703770,
            offset: 100, // Здесь
            playlist_id: -1
        }).then(({vkr}) => {
            for(song in vkr)
                songs.push(`[${song}] ${vkr[song].performer} - ${vkr[song].title}`);
        }).catch(err => console.log(err));
    }).catch(err => console.log(err));

UnhandledPromiseRejectionWarning: Error при частом запуске client.audio.search

easyvk 2.2.0

Если запустить пару раз скрипт, который ищет аудио и проходит до конца - приложение падает с
UnhandledPromiseRejectionWarning: Error. При этом, исключение не ловиться через конструкцию then().catch().

(node:8420) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabli
ng certificate verification.
loop: 0
0 50
(node:8420) UnhandledPromiseRejectionWarning: Error
    at Request.request.post [as _callback] (d:\dev\vk_music\node_modules\easyvk\src\utils\http.js:263:23)
    at Request.self.callback (d:\dev\vk_music\node_modules\request\request.js:185:22)
    at Request.emit (events.js:197:13)
    at Request.<anonymous> (d:\dev\vk_music\node_modules\request\request.js:1161:10)
    at Request.emit (events.js:197:13)
    at IncomingMessage.<anonymous> (d:\dev\vk_music\node_modules\request\request.js:1083:12)
    at Object.onceWrapper (events.js:285:13)
    at IncomingMessage.emit (events.js:202:15)
    at endReadableNT (_stream_readable.js:1129:12)
    at processTicksAndRejections (internal/process/next_tick.js:76:17)
(node:8420) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function withou
t a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8420) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will ter
minate the Node.js process with a non-zero exit code.
const easyvk = require('easyvk')({
    username: "",
    password: "",
    reauth: true,
})

var vkr_output = [];
var loop = 0;
function read_audio(client, q, offset) {
	client.audio.search({q:q, offset:offset}).then(({vkr}) => {
		console.log('loop:', loop++)
		console.log(offset, vkr.length);
		if (vkr.length == 0 && offset == 0)
		{
			console.log("Nothing found");
			return;
		}
		vkr_output = vkr_output.concat(vkr);
		if (vkr.length < 50){
			console.log(vkr_output.length, vkr_output[vkr_output.length-1])
			return;
		}
		read_audio(client, q, offset+50);
	}).catch((error) => {
      console.log(error,'Promise error');
  });
};

easyvk.then(vk => {
	vk.http.loginByForm().then(({client}) => {
		read_audio(client, 'Jesus and mary chain', 0);
	}).catch((error) => {
      console.log(error,'Promise error');
  });
});

И ещё пара важных багов

Снова привет. Пытаюсь исправить пару очень важных багов, но никак не получается. Первый баг связан с капчей. Сама капча ловится, но вот captchaHandler ни в какую не хочет вызываться.
Код дефолтный из документации

const captchaHandler = ({captcha_sid, captcha_img, resolve:solve, vk}) => {
    console.log(true);
}

easyvk({
    username: settings.username,
    password: settings.password,
    captchaHandler: captchaHandler
}).then((vk) => { }).catch(console.error)

Второй баг связан с audio.get(), аудиозаписи не получаются, если у пользователя есть хотя бы один плейлист (то есть, у владельца аккаунта всё нормально получается, даже если у него есть плейлисты. У другого пользователя треки нормально получаются, если у него нет плейлистов).
UPD: Не знаю как, но оно починилось... Но getById() по-прежнему не работает

Cannot read property 'uploader' of undefined

Не могу разобраться. У меня есть проект, используется easyvk версия 2.5.11 . Я его обновляю до 2.6.1 и метод uploader исчезает, возвращаю 2.5.11 все работает. В документации увидел что нужно добавить utils:

async function vkAuth(username, password, sessionPath, captchaHandler) {
  return await easyvk({
    username: username,
    password: password,
    session_file: sessionPath,
    captchaHandlder: captchaHandler,
    utils: {
      uploader: true
    }
  }).then(async (vk) => {
    console.log(vk); // тут uploader не доступен
    return vk;
  });
}

Добавляю, но ничего не происходит. Что я делаю не так?

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.