longpoll

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2019 License: MIT Imports: 8 Imported by: 0

README

User Long Poll API

Документация User Long Poll API

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

Данная библиотека поддерживает версию 3.

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

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

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

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

А потом сам longpoll

lp, err := longpoll.Init(vk api.VK, groupID int)
// По умолчанию 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,
}
httpTransport.Dial = dialer.Dial
lp.Client.Transport = httpTransport
Обработчик событий

Для каждого события существует отдельный обработчик, который передает функции []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/5.92/api"

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

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

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EventNewFunc

type EventNewFunc func([]interface{})

EventNewFunc struct

type FuncList

type FuncList map[int][]EventNewFunc

FuncList struct

func (FuncList) Handler

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

Handler func

type Longpoll

type Longpoll struct {
	Key     string
	Server  string
	Ts      int
	Mode    int
	Version int
	Wait    int
	VK      *api.VK
	Client  *http.Client
	// contains filtered or unexported fields
}

Longpoll struct

func Init

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

Init Longpoll

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.

Jump to

Keyboard shortcuts

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