Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
vildan-valeev committed Dec 8, 2023
1 parent 301eb2b commit a305e88
Show file tree
Hide file tree
Showing 12 changed files with 355 additions and 223 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# GVK - golang vk api

Library with states, goroutines

## Example
```go
Expand Down
43 changes: 25 additions & 18 deletions api.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package gvk

import "net/url"
import (
"net/url"
"strconv"
)

const (
APIVersion = "5.131"
)

// https://dev.vk.com/ru/api/community-messages/getting-started#Доступные инструменты и методы
type API struct {
token string
base string
Expand All @@ -19,35 +23,38 @@ func NewAPI(token string) API {
}
}

// GetUpdates is used to receive incoming updates using long polling.
func (a API) GetUpdates(opts *UpdateOptions) (res APIResponseUpdate, err error) {
return get[APIResponseUpdate](a.base, "getUpdates", urlValues(opts))
}

// GetUpdates is used to receive incoming updates using long polling.
func (a API) MessagesSend(text string, chatID int64, opts *MessagesSendOptions) (res APIResponseUpdate, err error) {
// GetUpdates https://dev.vk.com/ru/api/bots-long-poll/getting-started
func (a API) GetUpdates(opts *UpdateOptions) (res ResponseUpdate, err error) {
var vals = make(url.Values)
vals.Set("access_token", a.token)
vals.Set("v", APIVersion)

return getUpdates(a.base, "", urlValues(opts))
}

func (a API) MessagesSend(text string, chatID int64, opts *MessagesSendOptions) (res ResponseMessagesSend, err error) {
var vals = make(url.Values)
vals.Set("message", text)
vals.Set("chat_id", strconv.FormatInt(chatID, 10))

return get[APIResponseUpdate](a.base, "messages.send", addValues(vals, opts))
return get[ResponseMessagesSend](a.base, "messages.send", addValues(vals, opts))
}

//// GetUpdates is used to receive incoming updates using long polling.
//func (a API) MessagesSend(opts *UpdateOptions) (res APIResponseUpdate, err error) {
// return get[APIResponseUpdate](a.base, "getUpdates", urlValues(opts))
//}
// MessagesGetLongPollServer https://dev.vk.com/ru/method/groups.getLongPollServer
func (a API) GroupsGetLongPollServer(opts *GetLongPollServerOptions) (res ResponseGetLongPollServer, err error) {
var vals = make(url.Values)
vals.Set("access_token", a.token)
vals.Set("v", APIVersion)
return get[ResponseGetLongPollServer](a.base, "groups.getLongPollServer", addValues(vals, opts))

}

// MessagesGetLongPollServer returns data required for connection to a Long Poll server.
//
// https://vk.com/dev/messages.getLongPollServer
func (a API) MessagesGetLongPollServer(opts *GetLongPollServerOptions) (res APIResponseGetLongPollServer, err error) {
// GroupsSetLongPollSettings https://dev.vk.com/ru/method/groups.setLongPollSettings
func (a API) GroupsSetLongPollSettings(opts *SetLongPollSettingsOptions) (res ResponseSetLongPollSettings, err error) {
var vals = make(url.Values)

vals.Set("access_token", a.token)
vals.Set("v", APIVersion)
return get[APIResponseGetLongPollServer](a.base, "groups.getLongPollServer", addValues(vals, opts))
return get[ResponseSetLongPollSettings](a.base, "groups.setLongPollSettings", addValues(vals, opts))

}
25 changes: 11 additions & 14 deletions apierror.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,20 @@ package gvk

import "fmt"

// APIError represents an error returned by the Telegram API.
type APIError struct {
desc string
code int
Code int64 `json:"error_code"` // todo const type
Subcode int64 `json:"error_subcode"` // todo const type
Message string `json:"error_msg"`
Text string `json:"error_text"`
CaptchaSID string `json:"captcha_sid"`
CaptchaImg string `json:"captcha_img"`
}

// ErrorCode returns the error code received from the Telegram API.
func (a *APIError) ErrorCode() int {
return a.code
}

// Description returns the error description received from the Telegram API.
func (a *APIError) Description() string {
return a.desc
// Error returns the error string.
func (a APIError) Error() string {
return fmt.Sprintf("API error: %d %s", a.Code, a.Message)
}

// Error returns the error string.
func (a *APIError) Error() string {
return fmt.Sprintf("API error: %d %s", a.code, a.desc)
func (a APIError) Base() APIError {
return a
}
50 changes: 48 additions & 2 deletions dispatcher.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package gvk

import (
"context"
"log"
"net/http"
"sync"
)
Expand Down Expand Up @@ -42,13 +44,23 @@ func NewDispatcher(token string, groupID int64, newBotFn NewBotFn) (*Dispatcher,
if err != nil {
return nil, err
}

go d.listen()

return d, nil
}

// Poll is a wrapper function for PollOptions.
func (d *Dispatcher) Poll() error {
return d.PollOptions(true, UpdateOptions{Timeout: 120})
opts := UpdateOptions{
Server: d.Server,
Act: "a_check",
Key: d.Key,
Ts: d.Ts,
Wait: d.Wait,
}

return d.PollOptions(true, opts)
}

func (d *Dispatcher) PollOptions(dropPendingUpdates bool, opts UpdateOptions) error {
Expand All @@ -72,6 +84,11 @@ func (d *Dispatcher) PollOptions(dropPendingUpdates bool, opts UpdateOptions) er
if err != nil {
return err
}

err = d.check(response)
if err != nil {
return err
}
//
//if !dropPendingUpdates || !isFirstRun {
// for _, u := range response.Result {
Expand Down Expand Up @@ -111,7 +128,7 @@ func (d *Dispatcher) listen() {
}

func (d *Dispatcher) updateServer(updateTs bool) error {
serverSetting, err := d.api.MessagesGetLongPollServer(&GetLongPollServerOptions{GroupID: d.GroupID})
serverSetting, err := d.api.GroupsGetLongPollServer(&GetLongPollServerOptions{GroupID: d.GroupID})
if err != nil {
return err
}
Expand All @@ -125,3 +142,32 @@ func (d *Dispatcher) updateServer(updateTs bool) error {

return nil
}

func (d *Dispatcher) autoSetting(ctx context.Context) error {
// Updating LongPoll settings
opts := SetLongPollSettingsOptions{
GroupID: d.GroupID,
Enable: 1,
APIVersion: APIVersion,
}
_, err := d.api.GroupsSetLongPollSettings(&opts)

return err
}

func (d *Dispatcher) check(r ResponseUpdate) (err error) {
switch r.Failed {
case 0:
d.Ts = r.Ts
case 1:
d.Ts = r.Ts
case 2:
err = d.updateServer(false)
case 3:
err = d.updateServer(true)
default:
log.Println(err)
//err = &APIError{failed: r.failed}
}
return nil
}
1 change: 1 addition & 0 deletions error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package gvk
142 changes: 142 additions & 0 deletions event_message_new.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package gvk

// ClientInfo struct.
type ClientInfo struct {
ButtonActions []string `json:"button_actions"`
Keyboard bool `json:"keyboard"`
InlineKeyboard bool `json:"inline_keyboard"`
Carousel bool `json:"carousel"`
LangID int `json:"lang_id"`
}

// Messages struct.
type Message struct {
ID int `json:"id"` // Message ID
Date int `json:"date"`
PeerID int `json:"peer_id"` // Peer ID
FromID int64 `json:"from_id"`
Text string `json:"text"` // Message text
RandomID int `json:"random_id"`
Ref string `json:"ref"`
RefSource string `json:"ref_source"`
Attachments []Attachment `json:"attachments"`
Important bool `json:"important"` // Is it an important message
Geo BaseMessageGeo `json:"geo"`
Payload string `json:"payload"`
Keyboard Keyboard `json:"keyboard"`
FwdMessages []Message `json:"fwd_Messages"`
ReplyMessage *Message `json:"reply_message"`
Action MessageAction `json:"action"`
AdminAuthorID int `json:"admin_author_id"`
ConversationMessageID int `json:"conversation_message_id"`
IsCropped bool `json:"is_cropped"`
MembersCount int `json:"members_count"` // Members number
UpdateTime int `json:"update_time"` // Date when the message has been updated in Unixtime
WasListened bool `json:"was_listened,omitempty"`
PinnedAt int `json:"pinned_at,omitempty"`
MessageTag string `json:"message_tag"` // for https://notify.mail.ru/
IsMentionedUser bool `json:"is_mentioned_user,omitempty"`
}

type MessageAction struct {
ConversationMessageID int `json:"conversation_message_id"` // Message ID
Email string `json:"email"`
MemberID int `json:"member_id"` // User or email peer ID
Message string `json:"message"` // Message body of related message
Photo MessageActionPhoto `json:"photo"`
Text string `json:"text"`
Type string `json:"type"`
}

type MessageActionPhoto struct {
Photo100 string `json:"photo_100"` // URL of the preview image with 100px in width
Photo200 string `json:"photo_200"` // URL of the preview image with 200px in width
Photo50 string `json:"photo_50"` // URL of the preview image with 50px in width
}

type Attachment struct {
//Audio AudioAudio `json:"audio"`
//Doc DocsDoc `json:"doc"`
//Gift GiftsLayout `json:"gift"`
//Link BaseLink `json:"link"`
//Market MarketMarketItem `json:"market"`
//MarketMarketAlbum MarketMarketAlbum `json:"market_market_album"`
//Photo PhotosPhoto `json:"photo"`
//Sticker BaseSticker `json:"sticker"`
Type string `json:"type"`
//Video VideoVideo `json:"video"`
//Wall WallWallpost `json:"wall"`
//WallReply WallWallComment `json:"wall_reply"`
//AudioMessage DocsDoc `json:"audio_message"`
//Graffiti DocsDoc `json:"graffiti"`
//Poll PollsPoll `json:"poll"`
//Call MessageCall `json:"call"`
//Story StoriesStory `json:"story"`
//Podcast PodcastsEpisode `json:"podcast"`
}
type Keyboard struct {
AuthorID int `json:"author_id,omitempty"` // Community or bot, which set this keyboard
Buttons [][]Button `json:"buttons"`
OneTime bool `json:"one_time,omitempty"` // Should this keyboard disappear on first use
Inline bool `json:"inline,omitempty"`
}

type Button struct {
Action ButtonAction `json:"action"`
Color string `json:"color,omitempty"` // Button color
}
type ButtonAction struct {
AppID int `json:"app_id,omitempty"` // Fragment value in app link like vk.com/app{app_id}_-654321#hash
Hash string `json:"hash,omitempty"` // Fragment value in app link like vk.com/app123456_-654321#{hash}
Label string `json:"label,omitempty"` // Label for button
OwnerID int `json:"owner_id,omitempty"` // Fragment value in app link like vk.com/app123456_{owner_id}#hash
Payload string `json:"payload,omitempty"` // Additional data sent along with message for developer convenience
Type string `json:"type"` // Button type
Link string `json:"link,omitempty"` // Link URL
}

// BaseMessageGeo struct.
type BaseMessageGeo struct {
Coordinates BaseGeoCoordinates `json:"coordinates"`
Place BasePlace `json:"place"`
Showmap int `json:"showmap"`
Type string `json:"type"`
}

// BaseGeoCoordinates struct.
type BaseGeoCoordinates struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}

// BasePlace struct.
type BasePlace struct {
Address string `json:"address"`
Checkins int `json:"checkins"`
City interface{} `json:"city"` // BUG(VK): https://github.com/VKCOM/vk-api-schema/issues/143
Country interface{} `json:"country"`
Created int `json:"created"`
ID int `json:"id"`
Icon string `json:"icon"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Title string `json:"title"`
Type string `json:"type"`
IsDeleted bool `json:"is_deleted"`
TotalCheckins int `json:"total_checkins"`
Updated int `json:"updated"`
CategoryObject BaseCategoryObject `json:"category_object"`
}
type BaseCategoryObject struct {
ID int `json:"id"`
Title string `json:"title"`
Icons []BaseImage `json:"icons"`
}

// BaseImage struct.
type BaseImage struct {
Height float64 `json:"height"`
URL string `json:"url"`
Width float64 `json:"width"`
Type string `json:"type"`
}
8 changes: 4 additions & 4 deletions events.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package gvk

// MessageNewObject struct.
type MessageNewObject struct {
Message MessagesMessage `json:"message"`
ClientInfo ClientInfo `json:"client_info"`
// MessageNew https://dev.vk.com/ru/api/community-events/json-schema#Сообщения
type MessageNew struct {
Message Message `json:"message"`
ClientInfo ClientInfo `json:"client_info"`
}

//// MessageReplyObject struct.
Expand Down
Loading

0 comments on commit a305e88

Please sign in to comment.