Skip to content

Class library covering all vkontakte API methods. Generated using vkontakte API JSON schema, compiled under .NET Standard 1.1. Pull requests are welcome!

License

Notifications You must be signed in to change notification settings

pixorama/VkLibrary

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

95 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Targets Nuget Downloads Issues License

VkLibrary is an unofficial vkontakte library implemented in C# and covering almost all existing API methods and types.

Quick Start

The library is delivered via NuGet Package Manager:

Install-Package VkLibrary.Core

If you are targeting .NET Core, use the following command:

dotnet add package VkLibrary.Core

Getting Started

To run most API methods you need to pass an access_token, a special access key. Token is a string of digits and latin characters and may refer to a user, community or application itself. There are several ways to get an access_token, VkLibrary supports DirectAuth and OAuth.

Getting Application ID

The first thing you need to do in order to get application id and access token is to register a VK application. Go to my apps section and select "Create an application". After you'r done with it, you will find app id and client secret code in application's settings section. More detailed instructions can be found here.

Initializing the Library

var vk = new Vkontakte(1234567, string.Empty);

Use your app's secret code instead of string.Empty if you are going to work with secure API section.

Authentication using OAuth

As we already know, most methods require a valid access token. To get that token using OAuth, show a WebView-like control to a user, navigate him to authentication page and handle future redirects. More info can be found in official docs.

Here is a small instruction on how to get things done using UWP. Imagine we have a XAML-declared WebView control named BrowserView. Firstly we build an OAuth url and launch it using preffered ScopeSettings. Secondly we navigate our WebView control to url we've just built:

var url = vk.OAuth.GetAuthUrl(ScopeSettings.CanAccessMessages, AuthDisplayType.Mobile);
BrowserView.Navigate(new Uri(url));

Then we subscribe to WebView's navigation starting event and try to parse WebView's url when user is being redirected.

void OnNavigationStarting(WebView sender, EventArgs args)
{
    var result = vk.OAuth.ParseResponseUrl(args.Uri);
    if (result?.IsSuccess == true)
    {
        // We are authenticated! Let's save the token.
        vk.AccessToken = result.AccessToken;
    }
}

So VkLibrary will sign all future requests using AccessToken stored in AccessToken property.

Authentication using existing access token

If you'd like to use an existing access token to authenticate a user, just use AccessToken.FromString method:

vk.AccessToken = AccessToken.FromString(accessTokenString, authenticatedUserId);

Authentication using Direct Auth

If you are developing an application that was approved by vk administration, you can use Direct Auth extensions. Note that in this case you need to set your application's secret code (also known as client_secret). Do the following to authorize a user and to get an AccessToken:

vk.AccessToken = await vk.DirectAuth.Login("login", "pass", ScopeSettings.CanAccessWhatever);

Calling API Methods

All API methods are listed here.

Returns a list of current user's friends by invoking friends.get API method:

var friends = await vk.Friends.Get();

Returns a sequence of vk users containing only one user, whose id is 210700286, using Nom. name case:

var users = await vk.Users.Get(
  userIds: new[] { "210700286" },    
  fields: new[] { "photo_50", "city", "verified" },
  nameCase: "Nom"
);

Returns last 10 messages from a conversation with user, whose id is 12345.

var messages = await vk.Messages.GetHistory(userId: "12345", count: 10);

Sends a message to a user. Returns 1 if OK, 0 if not OK.

var ok = await vk.Messages.Send(userId: "12345", message: "Hey! What's up?");

Invoking RequestAsync

If you find an API method that VkLibrary does not support (this is unlikely, but may happen), use GetAsync method.

var friends = await vk.RequestAsync<ApiItemsResponse<UserFull>>(
  "friends.get", new Dictionary<string, string> {
    { "userId", "1234567" },
    { "count", "10" }
  }
);

The code above is equivalent to:

var friends = await vk.Friends.Get(userId: 1234567, count: 10);

Executing Scripts

API provides an ability to execute code on vk servers. Such code should be written in VkScript, a language similar to ActionScript or JavaScript, and end with a return %expression% statement.

If we send this kind of execute request:

var script = "return [API.users.isAppUser(), API.friends.get()];";
var result = await vk.Execute<JToken>(script);

The server will answer with a similar response:

[1, { 
"count": 5,
"items": [12345678, 87654321, 12345679, 97654321, 01012345]
}]

Uploading Files

VkLibrary has a helpers section containing methods for photos, videos, audios and documents uploading. This section is called UploadHelper. Here are some examples on how to use these helpers.

Document Uploading Example

var server = await vk.Docs.GetUploadServer();
var response = await vk.UploadHelper.UploadDocument(
    server.UploadUrl, // Server url received using GetUploadServer
    "Document.docx",  // Document name 
    bytes             // Bytes representing the document
);
var document = await vk.Docs.Save(
    response.File,   // File received on previous step
    "My document!",  // Document name
    "usefull, stuff" // Tags separated by comas
);

Photo for Messages Uploading Example

var uploadServer = await App.vk.Photos.GetMessagesUploadServer();
var uploadResponse = await App.vk.UploadHelper.UploadMessagesPhoto(
    uploadServer.UploadUrl, file.Name, bytes
);
var uploadResult = await App.vk.Photos.Save(
    uploadResponse.Photo,
    uploadResponse.Server,
    uploadResponse.Hash,
    -3
);

Generic PostAsync

If there are no POST methods in UploadHelper that can suite you, use generic ones: PostAsync or PostMultipleAsync.

Uploads multiple photos to vk servers using PostMultipleAsync method.

var response = await vk.UploadHelper.PostMultipleAsync<PhotoUploadResponse>(new Uri(url), files);  

Uploads a document to vk servers using PostAsync method.

var response = await vk.UploadHelper.PostAsync<DocUploadResponse>(new Uri(url), bytes, "file", fileName);

Processing Captcha

If any action (e.g. sending a message) is performed too frequently, an API request may return "Captcha needed" error. After that a user needs to enter a code from the image and resend a request with a Captcha code input in the request parameters.

Error code: 14

Error text: Captcha needed

See official docs for more detailed info

Understanding Exception Handling

VkLibrary provides an ability to process API captcha errors. When VK servers return a captcha error, VkLibrary throws an ApiException. ApiException holds an ApiError object that contains such fields as Code and ErrorMessage. So, when this type of exception is thrown, we should catch it and check ApiError code. If it equals 14, than we will need to process the captcha.

try {
  // Invoke any library method
} catch (ApiException apiException) {
  var apiError = apiException.GetApiError();
  if (apiError.Code == 14) {
    // Hey! Captcha needed!
    var captchaSid = apiError.CaptchaSid;
    var captchaUrl = apiError.CaptchaImg;
  }
}

Processing Captcha

To handle this kind of exception we should invoke SetCaptchaForNextRequest library method and pass CaptchaSid and user's answer CaptchaKey to it. So you we need to write something like this:

// Show captcha to a user and store results in 'captchaKey' 
vk.SetCaptchaForNextRequest(captchaSid, captchaKey);
vk.SomeRequest.PerformAgain();

Working with LongPoll Server

Long polling is a technology that allows the receiving of information about new events with the help of "long requests". The server receives the request but it doesn't immediately send the answer but rather when some event will happen (for example, receiving a new incoming message), or waiting period is over. Learn more about how VK's LongPoll server works on it's documentation page.

VkLibrary provides a simple event-based wrapper to work with the LongPoll server in an easy way. This wrapper is named LongPollClient and is located in VkLibrary.Core.LongPolling namespace. Let's learn how it works.

Starting a Long Poll Client

Firstly we need to get new long poll server parameters from API. Then we need to start a long poll client to work with.

var longPollParams = await vk.Messages.GetLongPollServer();
var longPollClient = vk.StartLongPollClient(
  longPollParams.Server, // Server received on previous step
  longPollParams.Key,    // Secret session key
  longPollParams.Ts,     // Event number
);

Working with Events

Our long poll client is now ready to notify us when new vk events take place. A list of all available events can be found here. Subscribing to events is easy and familiar. Let's subscribe to FriendOnlineEvent to be notified when friends launch vk applications:

longPollClient.FriendOnlineEvent += (sender, args) => Console.WriteLine(
  $"Friend with id {args.Item1} is now online! He uses {args.Item2} platform."
);

Info about all available events with description can be found here.

Stopping and Disposing

If we don't need our long poll client anymore, we should stop it.

longPollClient.Stop();

Extended Scenarios

VkLibrary also contains additional extended constructors, using them you can customize almost everything.

var api = new Vkontakte(
  appId: 1234567, 
  appSecret: "fb4f44tbuyh5k",
  apiVersion: "5.63",
  requestMethod: RequestMethod.Get,
  parseJson: ParseJson.FromString
);

ParseJson option determines how the library should parse JSONs received from VK servers.

  • ParseJson.FromString: loads JSON into a string, logs it using default logger and only after that deserializes. Use this for testing purposes only due to potential high memory usage and performance issues;
  • ParseJson.FromStream: to minimize memory usage and the number of strings allocated in memory, JSON.NET supports deserializing objects directly from a stream. Use this option in production for better performance.

RequestMethod determines which request method should be used when sending queries to Vkontakte API. GET option is generally a good choice for testing and debugging as GET queries are easy to read and understand. But when sending large objects to VK API servers consider using POST option, otherwise you'll receive "414 URI Too Long" error.

There may be some cases when you would like to customize default HttpService implementation. To do this, simply implement IHttpService interface and pass your new class instance to VkLibrary.Core via an extended constructor. The same thing you can do with a default logger, you'll need an ILogger interface. Default implementations of ILogger and IHttpService are DefaultLogger and DefaultHttpService respectively.

class CustomLogger : ILogger { /* implementation */ }
class CustomHttpService : IHttpService { /* implementation */ }
var api = new Vkontakte(1234567, string.Empty, new CustomHttpService(), new CustomLogger());

Other .NET languages

For F# Developers

VkLibrary can also be used with F# programming language!

use lib = new Vkontakte(1234567, "your_secret_code")
lib.Friends.Get(userId = Nullable 1234567, count = Nullable 1)
|> Async.AwaitTask
|> Async.RunSynchronously

F# gives us an ability to create annonymous interface implementations! Using this feature you can write code like this and inject a custom logger into VkLibrary.Core:

let logger = { new ILogger with member __.Log o = printfn "%A" o }
use api = new Vkontakte(1234567, "your_secret_code", logger = logger)

For Visual Basic Developers

Using VkLibrary with Visual Basic is pretty much the same as using it with C#.

Dim vk = new Vkontakte(12345, String.Empty)
Dim response = Await vk.Friends.Get(userId := 12345, count := 10)

About

Class library covering all vkontakte API methods. Generated using vkontakte API JSON schema, compiled under .NET Standard 1.1. Pull requests are welcome!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 97.6%
  • Python 2.4%