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: 11 Imported by: 20

README

Bots Long Poll API

PkgGoDev VK

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

Long Poll настраивается автоматически. Вам не требуется заходить в настройки сообщества.

Версия API

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

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

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

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

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

А потом сам longpoll

lp, err := longpoll.NewLongPoll(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
Обработчик событий

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

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

lp.MessageNew(func(ctx context.Context, obj events.MessageNewObject) {
	...
})

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

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

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

Контекст

Поля groupID, ts и eventID передаются в ctx. Чтобы получить их, можно воспользоваться следующими функциями:

groupID := events.GroupIDFromContext(ctx)
eventID := events.EventIDFromContext(ctx)
ts := longpoll.TsFromContext(ctx)
Запуск и остановка
// Запуск
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-bot"
	"github.com/SevereCloud/vksdk/v2/events"
)

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

	lp.MessageNew(func(ctx context.Context, obj events.MessageNewObject) {
		log.Print(obj.Message.Text)
	})

	lp.Run()
}

Documentation

Overview

Package longpoll implements Bots Long Poll API.

See more https://vk.com/dev/bots_longpoll

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TsFromContext

func TsFromContext(ctx context.Context) int

TsFromContext returns the ts from context.

Types

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 LongPoll

type LongPoll struct {
	GroupID int
	Server  string
	Key     string
	Ts      string
	Wait    int
	VK      *api.VK
	Client  *http.Client

	events.FuncList
	// contains filtered or unexported fields
}

LongPoll struct.

func NewLongPoll

func NewLongPoll(vk *api.VK, groupID int) (*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 NewLongPollCommunity

func NewLongPollCommunity(vk *api.VK) (*LongPoll, error)

NewLongPollCommunity returns a new LongPoll for community token.

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) FullResponse

func (lp *LongPoll) FullResponse(f func(Response))

FullResponse handler.

func (*LongPoll) Run

func (lp *LongPoll) Run() error

Run handler.

func (*LongPoll) RunWithContext added in v2.8.0

func (lp *LongPoll) RunWithContext(ctx context.Context) error

RunWithContext handler.

func (*LongPoll) Shutdown

func (lp *LongPoll) Shutdown()

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

type Response

type Response struct {
	Ts      string              `json:"ts"`
	Updates []events.GroupEvent `json:"updates"`
	Failed  int                 `json:"failed"`
}

Response struct.

Jump to

Keyboard shortcuts

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