vksdk: Golang SDK for VK API

repository·master·Indexed 42 days ago

https://github.com/severecloud/vksdk

A comprehensive Golang SDK for interacting with the VK (VKontakte) API, supporting over 500 methods, real-time event handling via Long Poll, and specialized integrations for Bots, Mini Apps, and Payments. It supports VK API version 5.199 and provides implementations for OAuth 2.0 flows (Implicit, Authorization Code, and Direct Authorization), batching via the Execute method, and performance optimizations using MessagePack and zstd compression.

Tokens
11.2K
Snippets
45
Records
52
Agent score
52%

What's inside vksdk

  1. Overview of VK SDK features

    master

    The VK SDK provides a comprehensive implementation of the VK API (version 5.199) for Go developers. Key capabilities include:

    • Core API: Over 500 methods, support for zstd and MessagePack, request limiting, token pools, and OAuth.
    • Real-time Events:
      • Bots Long Poll API: Real-time community event handling.
      • User Long Poll API: Real-time user event handling.
      • Callback API: Tracking user activity in communities with auto-callback setting.
    • Specialized APIs:
      • Streaming API: Receiving public data via keywords.
      • FOAF: Machine-readable ontology for users and groups (includes page creation dates).
      • Games & VK Mini Apps: Launch parameter checking via intermediate HTTP handlers.
      • Payments API: Processing payment notifications.
      • Marusia Skills: Creating Marusia Skills with SSML support.
  2. Use a Service Access Token

    master

    A Service Access Token is used for requests that do not require user or community authorization, such as secure.sendNotification, secure.addAppEvent, or public methods like users.get.

    • Where to get it: In your application settings in VK.
    • Security: It identifies your application. It should only be used on the server-side and must never be shared with or stored on a client device.
    • Lifecycle: For public methods, it is not tied to an IP address and does not expire. If compromised, you must generate a new one to invalidate the old one.
  3. Understand VK OAuth 2.0 access token flows

    master

    To interact with the VK API, you must provide an access_token. VK supports three primary OAuth 2.0 flows depending on your application type and security requirements:

    1. Implicit flow: Used for client-side applications (like mobile or browser-based apps) where the token is returned directly to the user's device via a URL parameter. This token is typically restricted to requests from the user's device.
    2. Authorization code flow: A two-step process suitable for server-side applications. The server receives an authorization code, which it then exchanges for an access token. This token is not tied to a specific IP address and is ideal for automated server-side requests.
    3. Direct Authorization: A specialized flow for trusted applications (requires prior approval from VK administration) that allows obtaining a long-lived token using a user's login and password. This is intended for platforms that do not support standard browser-based authorization.
  4. Get a list of managed communities

    master

    To obtain access tokens for multiple communities at once, you can first retrieve a list of all communities the user administers.

    1. Obtain a user access token with the scope=groups permission.
    2. Call the VK method groups.get with the parameter filter=admin.
    3. Use the resulting list of community IDs as the GroupIDs parameter when initializing your OAuth flow (Authorization Code or Implicit).
  5. Manage application access rights (scopes)

    master

    Access rights (scopes) determine what data a token can access. For example, to send private messages, you need oauth.ScopeUserMessage.

    Important Note: Certain user scopes (like messages) can only be requested via Implicit Flow (Standalone applications).

    To combine multiple scopes, use bitwise OR operations. To check if a token has specific permissions, use the oauth.CheckScope function.

    Example of combining scopes and checking permissions:

    // Combining scopes
    scope := oauth.ScopeUserFriends + oauth.ScopeUserStatus
    
    // Checking permissions
    // Assuming 'scope' is retrieved via vk.AccountGetAppPermissions(nil)
    if oauth.CheckScope(scope, oauth.ScopeUserFriends, oauth.ScopeUserStatus) {
        log.Println("Has access to friends and status")
    }
  6. Get a person or group using FOAF

    master

    The FOAF package (Friend of a Friend) provides a machine-readable way to describe people, groups, and their relationships within VK. You can retrieve person or group data using foaf.GetPerson or foaf.GetGroup by providing a context and the corresponding ID.

    Note: VK uses a modified version of FOAF based on Yandex's implementation with additional custom tags.

    ctx := context.Background()
    
    // Get a person by ID
    person, err := foaf.GetPerson(ctx, 1)
    if err != nil {
      log.Fatal(err)
    }
    log.Println(person)
    
    // Get a group by ID
    group, err := foaf.GetGroup(ctx, 1)
    if err != nil {
      log.Fatal(err)
    }
    log.Println(group)
  7. Enable MessagePack and zstd for performance

    master

    To reduce data size and increase speed, you can enable MessagePack (binary serialization) and zstd compression.

    Warning: Some methods might return broken encoding when using MessagePack. Use with caution.

    vk := api.NewVK(os.Getenv("USER_TOKEN"))
    
    // Enable optimizations
    vk.EnableMessagePack()
    vk.EnableZstd()
    
    // Now requests will use msgpack/zstd
    r, err := vk.Request(method, params)
  8. Initialize the VK API client

    master

    To use the SDK, initialize a new VK client using an access token. The library supports VK API version 5.199.

    import "github.com/SevereCloud/vksdk/v3/api"
    
    // Initialize with your access token
    vk := api.NewVK("<TOKEN>")
  9. Implement Implicit Flow for client-side apps

    master

    Use this flow for applications where the API calls are made directly from the user's device.

    Step 1: Generate the URL Use oauth.ImplicitFlowUser with ClientID and Scope. The default RedirectURI is https://oauth.vk.ru/blank.html.

    Step 2: Retrieve the Token After authorization, the token is passed in the URL fragment. Use oauth.NewUserTokenFromURL(u) to parse the token from the resulting URL.

    // 1. Generate URL
    u := oauth.ImplicitFlowUser(oauth.UserParams{
        ClientID: 123456,
        Scope:    oauth.ScopeUserPhotos + oauth.ScopeUserDocs,
    })
    
    // 2. Parse token from the resulting URL
    t, err := oauth.NewUserTokenFromURL(u)
    if err != nil {
        fmt.Printf("%#v\n", err)
    }
    
    fmt.Printf("Token %s for id%d expires in %d seconds", t.AccessToken, t.UserID, t.ExpiresIn)
  10. Initialize the Bots Long Poll API

    master

    To use the Long Poll API, you must first initialize the VK API client and then create a Long Poll instance.

    Authentication Requirements:

    • User Access Token: Obtained via a Standalone application using Implicit Flow (requires groups permission).
    • Community Access Token: Requires manage permission.

    Configuration Options: When calling longpoll.NewLongPoll(vk, groupID), you can manually configure:

    • lp.Wait: The wait time (defaults to 25).
    • lp.Ts: The server time (timestamp).
    // 1. Initialize VK API
    vk := api.NewVK("<TOKEN>")
    
    // 2. Initialize Long Poll
    lp, err := longpoll.NewLongPoll(vk, 12345678)
    // lp.Wait = 90
    // lp.Ts = "123"
  11. Use the User Long Poll API v3 wrapper

    master

    The longpoll-user/v3 module provides a wrapper for the VK User Long Poll API version 3. It allows you to handle incoming events (such as new messages) using a callback-based approach instead of manually parsing the raw long poll response.

    To use it, create a new wrapper instance by passing your existing long poll instance to wrapper.NewWrapper(lp). You can then register event handlers, such as OnNewMessage, which triggers whenever a new message event (event code 4) is received.

    // import "github.com/SevereCloud/vksdk/v3/longpoll-user/v3"
    
    w := wrapper.NewWrapper(lp)
    
    // event with code 4
    w.OnNewMessage(func(m wrapper.NewMessage) {
      fmt.Printf("4 wrapper.NewMessage: %v\n", m)
    })
  12. Implement Authorization Code Flow for server-side apps

    master

    Use this flow when your application has a backend server. It is more secure and allows for automated requests.

    Step 1: Generate the Authorization URL Use NewAuthCodeFlowUser with your ClientID, RedirectURI, and desired Scope. Redirect the user's browser to this URL.

    Step 2: Handle the Callback After the user authorizes the app, VK redirects them to your RedirectURI with a code parameter in the URL. Use the Token(req.URL) method on your flow instance to exchange this code for a UserToken.

    // 1. Generate URL
    acf := NewAuthCodeFlowUser(oauth.UserParams{
        ClientID:    123456,
        RedirectURI: "https://example.com/callback",
        Scope:       oauth.ScopeUserPhotos + oauth.ScopeUserDocs,
    }, clientSecret)
    u := acf.URL().String()
    
    // 2. In your HTTP callback handler
    func callback(w http.ResponseWriter, req *http.Request) {
        t, err := acf.Token(req.URL)
        if err != nil {
            fmt.Printf("%#v\n", err)
            return
        }
    
        fmt.Printf("Token %s for id%d expires in %d seconds", t.AccessToken, t.UserID, t.ExpiresIn)
    }