Help us shape the future of Go! Take the 2026 Go Developer Survey

vkbot

package module
v0.0.0-...-4324148 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2019 License: MIT Imports: 9 Imported by: 0

README

vkbot

Установка и обновление

go get -u github.com/azzzak/vkbot

Запуск

Для работы бота потребуется указать адрес для отправки callback-запросов на вкладке Управление сообщестом > Работа с API > Callback API. Для подтверждения нового сервера надо скопировать строку подтверждения и передать ее боту. После запуска бота нажмите кнопку Подтвердить, в случае успеха можно будет выбрать какие типы событий станут инициировать callback-запрос.

Поддерживаются следующие типы событий:

  • Входящие сообщения
  • Исходящие сообщения
  • Вступление в сообщество
  • Выход из сообщества

Для отправки сообщений необходимо создать ключи доступа на вкладке Управление сообщестом > Работа с API > Ключи доступа. Ключ указывается при запуске бота вместе с числовым идентификатором группы.

На вкладке Управление сообщестом > Работа с API > Callback API можно задать секретный ключ, который будет удостоверять подлинность данных. Если секретный ключ задан, его так же требуется указать при запуске бота.

Работа за Nginx

Для работы за Nginx надо настроить обратный прокси. Функцию ListenForWebhook в этом случае следует запускать с параметром "/".

server {
...
	location = /callback/path {
		proxy_pass	http://localhost:8101;
	}
...	
}

Пример

Простой бот, который повторяет присланные сообщения.

package main

import (
	"fmt"
	"net/http"

	"github.com/azzzak/vkbot"
)

func main() {
	bot, err := vkbot.NewBotAPI("key", GroupID)
	if err != nil {
		fmt.Println(err)
	}
	bot.Confirmation = "123"
	bot.Secret = "123"
	updates := bot.ListenForWebhook("/callback/path")

	go http.ListenAndServe(":8101", nil)

	for update := range updates {
		switch update.Type {
		case vkbot.IncomingMessage:
      			bot.Send(update.Payload.UserID, update.Payload.Body)
		}
	}
}

Documentation

Index

Constants

View Source
const (
	IncomingMessage  = "message_new"
	OutcomingMessage = "message_reply"
	JoinGroup        = "group_join"
	LeaveGroup       = "group_leave"
)

Constant values for type of message.

Variables

This section is empty.

Functions

This section is empty.

Types

type BotAPI

type BotAPI struct {
	Token  string `json:"token"`
	Buffer int    `json:"buffer"`

	GroupID      int    `json:"-"`
	Secret       string `json:"-"`
	Confirmation string `json:"-"`

	Client *http.Client `json:"-"`
}

BotAPI contains information for using API.

func NewBot

func NewBot(token string, group int) (*BotAPI, error)

NewBot creates a new BotAPI instance.

func (*BotAPI) ListenForWebhook

func (bot *BotAPI) ListenForWebhook(pattern string) <-chan Packet

ListenForWebhook registers a http handler for a webhook.

func (*BotAPI) Send

func (bot *BotAPI) Send(id int, text ...string) (Response, error)

Send will send message to user through VK.

type Error

type Error struct {
	ErrorCode     int           `json:"error_code"`
	ErrorMsg      string        `json:"error_msg"`
	RequestParams []interface{} `json:"request_params"`
}

Error is type for possibly error.

type Packet

type Packet struct {
	Type    string  `json:"type"`
	Payload Payload `json:"object"`
	GroupID int     `json:"group_id"`
	Secret  string  `json:"secret"`
}

Packet is type for incoming message.

type Payload

type Payload struct {
	ID        int    `json:"id"`
	Date      int64  `json:"date"`
	Out       int    `json:"out"`
	UserID    int    `json:"user_id"`
	ReadState int    `json:"read_state"`
	Title     string `json:"title"`
	Body      string `json:"body"`
	JoinType  int    `json:"join_type"`
	Self      int    `json:"self"`
}

Payload is type for payload of incoming message.

type Response

type Response struct {
	Error    Error `json:"error"`
	Response int   `json:"response"`
}

Response is type for response in Send function.

Jump to

Keyboard shortcuts

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