longpoll

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2020 License: MIT Imports: 6 Imported by: 0

README

User Long Poll API

Documentation 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{}) {
	...
})

Если вы хотите получать полный ответ от 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/api"

	longpoll "github.com/SevereCloud/vksdk/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/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

This section is empty.

Functions

This section is empty.

Types

type EventNewFunc

type EventNewFunc func([]interface{}) error

EventNewFunc struct.

type FuncList

type FuncList map[int][]EventNewFunc

FuncList struct.

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
	// contains filtered or unexported fields
}

Longpoll struct.

func Init deprecated

func Init(vk *api.VK, mode Mode) (lp Longpoll, err error)

Init Longpoll.

Deprecated: use NewLongpoll.

func NewLongpoll added in v1.5.0

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) 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 added in v1.3.0

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