longpoll

package
v2.16.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2023 License: MIT Imports: 10 Imported by: 3

README

User Long Poll API

PkgGoDev VK

Подключение User Long Poll API

Данный модуль по умолчанию поддерживает 3 версию

Инициализация

Модуль можно использовать с ключом доступа пользователя, полученным в Standalone-приложении через Implicit Flow(требуются права доступа: messages) или с ключом доступа сообщества(требуются права доступа: messages).

В начале необходимо инициализировать api:

vk := api.NewVK("<TOKEN>")

А потом сам longpoll

mode := longpoll.ReceiveAttachments + longpoll.ExtendedEvents
lp, err := longpoll.NewLongPoll(vk, mode)
// По умолчанию Wait = 25
// lp.Wait = 90
// lp.Ts = 123
HTTP client

В модуле реализована возможность изменять HTTP клиент - lp.Client

Пример прокси

dialer, _ := proxy.SOCKS5("tcp", "127.0.0.1:9050", nil, proxy.Direct)
httpTransport := &http.Transport{
	Dial:              dialer.Dial,
	// DisableKeepAlives: true,
}

client := &http.Client{
	Transport: httpTransport,
}

lp.Client = client
Обработчик событий

Обработчики, которые возвращают полноценные структуры:

Для каждого события существует отдельный обработчик, который передает функции []interface{}.

Пример для 4 события

lp.EventNew(4, func(event []interface{}) error {
	...
})

Если вы хотите получать полный ответ от Long Poll(например для сохранения ts или специальной обработки failed), можно воспользоваться следующим обработчиком.

lp.FullResponse(func(resp object.LongPollResponse) {
	...
})

Полный список событий и их структуру Вы найдёте в документации

Запуск и остановка
// Запуск
if err := lp.Run(); err != nil {
	log.Fatal(err)
}

// Безопасное завершение
// Ждет пока соединение закроется и события обработаются
lp.Shutdown()

// Закрыть соединение
// Требует lp.Client.Transport = &http.Transport{DisableKeepAlives: true}
lp.Client.CloseIdleConnections()

Пример

package main

import (
	"log"

	"github.com/SevereCloud/vksdk/v2/api"

	longpoll "github.com/SevereCloud/vksdk/v2/longpoll-user"
)

func main() {
	vk := api.NewVK("<TOKEN>")
	lp, err := longpoll.NewLongPoll(vk, 2)
	if err != nil {
		log.Fatal(err)
	}

	lp.EventNew(4, func(event []interface{}) error {
		log.Print(event[5].(string))

		return nil
	})

	if err := lp.Run(); err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package longpoll implements User Long Poll API.

Long polling – this 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.

By using this approach, you can instantly display in your app the most important events. Be aware that with the help of Long Poll, you won't be able to send messages. For this, you’ll need to use the messages.send method.

Initialization

The module can be used with the user access key obtained in the Standalone application via Implicit Flow(access rights required: messages) or with the community access key(access rights required: messages).

vk := api.NewVK("<TOKEN>")

And then longpoll

mode := longpoll.ReceiveAttachments + longpoll.ExtendedEvents
lp, err := longpoll.NewLongPoll(vk, mode)

Setting

TODO: write about lp.Ts lp.Wait

The module has the ability to modify the HTTP client

dialer, _ := proxy.SOCKS5("tcp", "127.0.0.1:9050", nil, proxy.Direct)
httpTransport := &http.Transport{
	Dial:              dialer.Dial,
	// DisableKeepAlives: true,
}
httpTransport.Dial = dialer.Dial
lp.Client.Transport = httpTransport

Wrapper

Wrapper allows you to get ready-made structures

Wrapper for v3 https://pkg.go.dev/github.com/SevereCloud/vksdk/v2/longpoll-user/v3

Run and shutdown

TODO: write about lp.Run() and lp.Shutdown()

VK documentation https://vk.com/dev/using_longpoll

Index

Constants

This section is empty.

Variables

View Source
var ErrNotValidVersion = errors.New("longpoll: not valid version")

ErrNotValidVersion not valid version.

Functions

This section is empty.

Types

type EventNewFunc

type EventNewFunc func([]interface{}) error

EventNewFunc struct.

type Failed

type Failed struct {
	Code int
}

Failed struct.

func (Failed) Error

func (e Failed) Error() string

Error returns the message of a Failed.

type FuncList deprecated

type FuncList map[int][]EventNewFunc

FuncList struct.

Deprecated: FuncList built into LongPoll.

func (FuncList) Handler

func (funcList FuncList) Handler(event []interface{}) error

Handler func.

type LongPoll

type LongPoll struct {
	Key     string
	Server  string
	Ts      int
	Mode    Mode
	Version int
	Wait    int
	VK      *api.VK

	Client    *http.Client
	UserAgent string
	// contains filtered or unexported fields
}

LongPoll struct.

func NewLongPoll

func NewLongPoll(vk *api.VK, mode Mode) (*LongPoll, error)

NewLongPoll returns a new LongPoll.

The LongPoll will use the http.DefaultClient. This means that if the http.DefaultClient is modified by other components of your application the modifications will be picked up by the SDK as well.

func (*LongPoll) EventNew

func (lp *LongPoll) EventNew(key int, f EventNewFunc)

EventNew handler.

func (*LongPoll) FullResponse

func (lp *LongPoll) FullResponse(f func(object.LongPollResponse))

FullResponse handler.

func (*LongPoll) Goroutine added in v2.4.0

func (lp *LongPoll) Goroutine(v bool)

Goroutine invoke functions in a goroutine.

func (*LongPoll) Run

func (lp *LongPoll) Run() error

Run handler.

func (*LongPoll) Shutdown

func (lp *LongPoll) Shutdown()

Shutdown gracefully shuts down the longpoll without interrupting any active connections.

type Mode

type Mode = int

Mode additional answer options.

const (
	// receive attachments.
	ReceiveAttachments Mode = 1 << 1
	// receive more events.
	ExtendedEvents Mode = 1 << 3
	// receive pts (used in messages.getLongPollHistory).
	ReturnPts Mode = 1 << 5
	// extra fields in event type 8(friend become online).
	Code8ExtraFields Mode = 1 << 6
	// return random_id field.
	ReturnRandomID Mode = 1 << 7
)

A list of necessary option codes.

Directories

Path Synopsis
Package wrapper implement User Long Poll API wrapper v3.
Package wrapper implement User Long Poll API wrapper v3.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL