Documentation ¶
Overview ¶
Package govkbot is a pure Go client library for https://vk.com messaging API.
It includes a API for receive and send messages, chats, users info and friending.
It works simply, but need to manually get user token.
This implementation don't use vk long pool API and proxies, and have limit 3 requests per second (VK API limit).
To get token you need:
1. You can use any app id from https://vk.com/apps?act=wingames, for example 4775211
(You can create own app and get app_id on page https://vk.com/editapp?act=create (standalone app))
2. Open in browser with logged in VK (you must use IP, where you want run bot)
https://oauth.vk.com/authorize?client_id={{app_id}}&scope=offline,group,messages,friends&display=page&response_type=token&redirect_uri=https://oauth.vk.com/blank.html
3. Copy token query parameter from URL string. Token valid only for IP from what you get it.
Index ¶
- Constants
- Variables
- func HandleAction(command string, handler func(*Message) string)
- func HandleAdvancedMessage(command string, handler func(*Message) Reply)
- func HandleError(handler func(*Message, error))
- func HandleMessage(command string, handler func(*Message) string)
- func HasPrefix(s, prefix string) bool
- func Listen(token string, url string, ver string, adminID int64) error
- func NotifyAdmin(msg string) error
- func SetAPI(token string, url string, ver string)
- func SetAutoFriend(af bool)
- func SetDebug(debug bool)
- func SetLang(lang string)
- func SetToken(token string)
- func TrimPrefix(s, prefix string) string
- type Attachment
- type Button
- type ChatInfo
- type ChatInfoResponse
- type ConversationInfo
- type ConversationsResponse
- type ErrorResponse
- type FailResponse
- type FriendDeleteResponse
- type FriendRequests
- type FriendRequestsResponse
- type Geo
- type GroupFailResponse
- type GroupLongPollEvent
- type GroupLongPollMessage
- type GroupLongPollResponse
- type GroupLongPollServer
- func (server *GroupLongPollServer) FilterReadMesages(messages []*Message) (result []*Message)
- func (server *GroupLongPollServer) GetLongPollMessages() ([]*Message, error)
- func (server *GroupLongPollServer) Init() (err error)
- func (server *GroupLongPollServer) ParseLongPollMessages(j string) (*GroupLongPollResponse, error)
- func (server *GroupLongPollServer) ParseMessage(obj map[string]interface{}) (Message, error)
- func (server *GroupLongPollServer) Request() ([]byte, error)
- type GroupLongPollServerResponse
- type GroupProfile
- type H
- type Keyboard
- type LongPollMessage
- type LongPollResponse
- type LongPollServer
- type LongPollUpdate
- type LongPollUpdateNum
- type MemberItem
- type MembersResponse
- type Mention
- type Message
- type Messages
- type MessagesResponse
- type Reply
- type ResponseError
- type SimpleResponse
- type User
- type UserLongPollServer
- func (server *UserLongPollServer) FilterReadMesages(messages []*Message) (result []*Message)
- func (server *UserLongPollServer) GetLongPollMessages() ([]*Message, error)
- func (server *UserLongPollServer) Init() (err error)
- func (server *UserLongPollServer) ParseLongPollMessages(j string) (*LongPollResponse, error)
- func (server *UserLongPollServer) Request() ([]byte, error)
- type UserLongPollServerResponse
- type UserProfile
- type UsersResponse
- type VKBot
- func (bot *VKBot) CheckFriends()
- func (bot *VKBot) GetMessages() ([]*Message, error)
- func (bot *VKBot) HandleAction(command string, handler func(*Message) string)
- func (bot *VKBot) HandleAdvancedMessage(command string, handler func(*Message) Reply)
- func (bot *VKBot) HandleError(handler func(*Message, error))
- func (bot *VKBot) HandleMessage(command string, handler func(*Message) string)
- func (bot *VKBot) ListenGroup(api *VkAPI) error
- func (bot *VKBot) ListenUser(api *VkAPI) error
- func (bot *VKBot) MainRoute(poller LongPollServer)
- func (bot *VKBot) Reply(m *Message, reply Reply) (id int64, err error)
- func (bot *VKBot) RouteAction(m *Message) (replies []string, err error)
- func (bot *VKBot) RouteMessage(m *Message) (replies []Reply, err error)
- func (bot *VKBot) RouteMessages(messages []*Message) (result map[*Message][]Reply)
- func (bot *VKBot) SetAutoFriend(af bool)
- func (bot *VKBot) SetIgnoreBots(ignore bool)
- type VKError
- type VKMembers
- type VKUsers
- type VkAPI
- func (api *VkAPI) AddFriend(uid int64) bool
- func (api *VkAPI) Call(method string, params map[string]string) ([]byte, error)
- func (api *VkAPI) CallMethod(method string, params map[string]string, result interface{}) error
- func (api *VkAPI) CurrentGroup() (*GroupProfile, error)
- func (api *VkAPI) DeleteFriend(uid int64) bool
- func (api *VkAPI) GetChatFullInfo(chatID int64) (*ChatInfo, error)
- func (api *VkAPI) GetChatInfo(chatID int64) (*ChatInfo, error)
- func (api *VkAPI) GetChatUsers(chatID int64) (users []*User, err error)
- func (api *VkAPI) GetConversation(chatID int64) (*ChatInfo, error)
- func (api *VkAPI) GetConversationMembers(chatID int64) (users []*User, err error)
- func (api *VkAPI) GetFriendRequests(out bool) (friends []int64, err error)
- func (api *VkAPI) GetMessages(count int, offset int) (*Messages, error)
- func (api *VkAPI) GetRandomID() string
- func (api *VkAPI) GetUserChatInfo(chatID int64) (*ChatInfo, error)
- func (api *VkAPI) GetUserChatUsers(chatID int64) (users []*User, err error)
- func (api *VkAPI) IsGroup() bool
- func (api *VkAPI) Me() (*User, error)
- func (api *VkAPI) NewBot() *VKBot
- func (api *VkAPI) NotifyAdmin(msg string) (err error)
- func (api *VkAPI) SendAdvancedPeerMessage(peerID int64, message Reply) (id int64, err error)
- func (api *VkAPI) SendChatMessage(chatID int64, msg string) (id int64, err error)
- func (api *VkAPI) SendMessage(userID int64, msg string) (id int64, err error)
- func (api *VkAPI) SendPeerMessage(peerID int64, msg string) (id int64, err error)
- func (api *VkAPI) User(uid int64) (*User, error)
Examples ¶
Constants ¶
const ( LongPollModeGetAttachments = 2 LongPollModeGetExtendedEvents = 8 LongPollModeGetPts = 32 LongPollModeGetExtraData = 64 LongPollModeGetRandomID = 128 )
const ChatPrefix = 2000000000
const DefaultMode = LongPollModeGetAttachments
const DefaultVersion = 2
const DefaultWait = 25
Variables ¶
var API = newAPI()
API - bot API
var Bot = API.NewBot()
Functions ¶
func HandleAction ¶
HandleAction - add action handler. Function must return string to reply or "" (if no reply)
func HandleAdvancedMessage ¶
HandleAdvancedMessage - add substr message handler. Function must return string to reply or "" (if no reply)
func HandleMessage ¶
HandleMessage - add substr message handler. Function must return string to reply or "" (if no reply)
func Listen ¶
Listen - start server
Example ¶
package main import ( "fmt" "log" "github.com/nikepan/govkbot/v2" ) func helpHandler(m *govkbot.Message) (reply string) { return "Available commands: /help, /me\nYou message" + m.Body } func errorHandler(msg *govkbot.Message, err error) { // Check gor VK Error code if _, ok := err.(*govkbot.VKError); !ok { log.Fatal( err.(govkbot.VKError).ErrorCode, err.Error(), msg.Body) } log.Fatal(err.Error(), msg.Body) } func addFriendHandler(m *govkbot.Message) (reply string) { log.Printf("friend %+v added\n", m.UserID) govkbot.NotifyAdmin(fmt.Sprintf("user vk.com/id%+v add me to friends", m.UserID)) return reply } func main() { //govkbot.HandleMessage("/", anyHandler) // any commands starts with "/" //govkbot.HandleMessage("/me", meHandler) govkbot.HandleMessage("/help", helpHandler) // any commands starts with "/help" //govkbot.HandleAction("chat_invite_user", inviteHandler) //govkbot.HandleAction("chat_kick_user", kickHandler) govkbot.HandleAction("friend_add", addFriendHandler) //govkbot.HandleAction("friend_delete", deleteFriendHandler) govkbot.HandleError(errorHandler) govkbot.SetAutoFriend(true) // enable auto accept/delete friends govkbot.SetDebug(true) // log debug messages // Optional Direct VK API access govkbot.SetAPI("!!!!VK_TOKEN!!!!", "", "") // Need only before Listen, if you use direct API me, _ := govkbot.API.Me() // call API method log.Printf("current user: %+v\n", me.FullName()) // Optional end govkbot.Listen("!!!!VK_TOKEN!!!!", "", "", 12345678) // start bot }
Output:
func SetLang ¶
func SetLang(lang string)
SetLang - sets VK response language. Default auto. Available: en, ru, ua, be, es, fi, de, it
func TrimPrefix ¶
TrimPrefix returns s without the provided leading case insensitive prefix string. If s doesn't start with prefix, s is returned unchanged.
Types ¶
type Attachment ¶
type Button ¶
type Button struct { Action struct { Type string `json:"type"` Payload string `json:"payload"` Label string `json:"label"` } `json:"action"` Color string `json:"color"` }
Button for keyboard, which sends to user
type ChatInfo ¶
type ChatInfo struct { ID int64 `json:"id"` Type string `json:"type"` Title string `json:"title"` Kicked int `json:"kicked"` AdminID int64 `json:"admin_id"` Users VKUsers `json:"users"` }
ChatInfo - chat info
type ChatInfoResponse ¶
ChatInfoResponse - chat info vk struct
type ConversationInfo ¶
type ConversationInfo struct { Peer struct { ID int64 Type string LocalID int `json:"local_id"` } InRead int `json:"in_read"` OutRead int `json:"out_read"` LastMessageID int `json:"last_message_id"` CanWrite struct { Allowed bool } `json:"can_write"` ChatSettings struct { Title string MembersCount int `json:"members_count"` State string ActiveIDs []int `json:"active_ids"` ACL struct { CanInvite bool `json:"can_invite"` CanChangeInfo bool `json:"can_change_info"` CanChangePin bool `json:"can_change_pin"` CanPromoteUsers bool `json:"can_promote_users"` CanSeeInviteLink bool `json:"can_see_invite_link"` CanChangeInviteLink bool `json:"can_change_invite_link"` } IsGroupChannel bool `json:"is_group_channel"` OwnerID int64 `json:"owner_id"` } `json:"chat_settings"` }
ConversationInfo - conversation info
type ConversationsResponse ¶
type ConversationsResponse struct { Response struct { Items []ConversationInfo Profiles []UserProfile } Error *VKError }
ConversationsResponse - resonse of confersations info
type ErrorResponse ¶
type ErrorResponse struct {
Error *VKError
}
ErrorResponse - need to parse VK error
type FailResponse ¶
type FriendDeleteResponse ¶
FriendDeleteResponse - VK friend delete response
type FriendRequests ¶
FriendRequests - VK friend requests
type FriendRequestsResponse ¶
type FriendRequestsResponse struct { Response FriendRequests Error *VKError }
FriendRequestsResponse - VK friend requests response
type GroupFailResponse ¶
type GroupFailResponse struct { Failed int Date int `json:"date,omitempty"` Ts interface{} `json:"ts,omitempty"` MinVersion int `json:"min_version"` MaxVersion int `json:"max_version"` }
func (*GroupFailResponse) TS ¶ added in v2.1.4
func (g *GroupFailResponse) TS() (string, error)
type GroupLongPollEvent ¶
type GroupLongPollMessage ¶
type GroupLongPollMessage struct { Type string Object struct { Date int `json:"date"` FromID int64 `json:"from_id"` ID int64 `json:"id"` Out int `json:"out"` PeerID int `json:"peer_id"` Text string `json:"text"` ConversationMessageID int `json:"conversation_message_id"` FwdMessages []GroupLongPollMessage `json:"fwd_messages"` Important bool `json:"important"` RandomID int64 `json:"random_id"` //Attachments [] `json:"attachments"` IsHidden bool `json:"is_hidden"` Action struct { Type string MemberID int64 `json:"member_id"` } } GroupID int64 }
type GroupLongPollResponse ¶
type GroupLongPollServer ¶
type GroupLongPollServer struct { Key string Server string Ts string Wait int Mode int Version int RequestInterval int NeedPts bool API *VkAPI LpVersion int ReadMessages map[int64]time.Time }
LongPollServer - longpoll server structure
func NewGroupLongPollServer ¶
func NewGroupLongPollServer(requestInterval int) (resp *GroupLongPollServer)
NewLongPollServer - get longpoll server
func (*GroupLongPollServer) FilterReadMesages ¶
func (server *GroupLongPollServer) FilterReadMesages(messages []*Message) (result []*Message)
FilterReadMesages - filter read messages
func (*GroupLongPollServer) GetLongPollMessages ¶
func (server *GroupLongPollServer) GetLongPollMessages() ([]*Message, error)
GetLongPollMessages - get messages via longpoll
func (*GroupLongPollServer) Init ¶
func (server *GroupLongPollServer) Init() (err error)
Init - init longpoll server
func (*GroupLongPollServer) ParseLongPollMessages ¶
func (server *GroupLongPollServer) ParseLongPollMessages(j string) (*GroupLongPollResponse, error)
ParseLongPollMessages - parse longpoll messages
func (*GroupLongPollServer) ParseMessage ¶
func (server *GroupLongPollServer) ParseMessage(obj map[string]interface{}) (Message, error)
func (*GroupLongPollServer) Request ¶
func (server *GroupLongPollServer) Request() ([]byte, error)
Request - make request to longpoll server
type GroupLongPollServerResponse ¶
type GroupLongPollServerResponse struct {
Response GroupLongPollServer
}
type GroupProfile ¶
type GroupProfile struct { ID int64 `json:"id"` Name string `json:"name"` ScreenName string `json:"screen_name"` IsClosed int `json:"is_closed"` Type string `json:"type"` Photo50 string `json:"photo50"` Photo100 string `json:"photo100"` Photo200 string `json:"photo200"` }
GroupProfile - conversation group profile
type LongPollMessage ¶
type LongPollResponse ¶
type LongPollServer ¶
type LongPollUpdate ¶
type LongPollUpdate []interface{}
type LongPollUpdateNum ¶
type LongPollUpdateNum []int64
type MemberItem ¶
type MemberItem struct { MemberID int64 `json:"member_id"` JoinDate int `json:"join_date"` IsOwner bool `json:"is_owner"` IsAdmin bool `json:"is_admin"` InvitedBy int64 `json:"invited_by"` }
MemberItem - conversation item
type MembersResponse ¶
MembersResponse - VK user response
type Message ¶
type Message struct { ID int64 Date int Out int UserID int64 `json:"user_id"` ChatID int64 `json:"chat_id"` PeerID int64 `json:"peer_id"` ReadState int `json:"read_state"` Title string Body string Action string ActionMID int64 `json:"action_mid"` Flags int Timestamp int64 Payload string FwdMessages []Message `json:"fwd_messages"` }
Message - VK message struct
func GetLongPollMessage ¶
func GetLongPollMessage(resp []interface{}) *Message
GetLongPollMessage - get message from longpoll json row
func (Message) GetMentions ¶
func (Message) MarkAsRead ¶
MarkAsRead - mark message as read
type MessagesResponse ¶
MessagesResponse - VK messages response
type ResponseError ¶
type ResponseError struct {
// contains filtered or unexported fields
}
VKError - error with response content
func (ResponseError) Error ¶
func (err ResponseError) Error() string
type SimpleResponse ¶
SimpleResponse - simple int response
type User ¶
type User struct { ID int64 `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` ScreenName string `json:"screen_name"` Photo string `json:"photo"` InvitedBy int64 `json:"invited_by"` City Geo `json:"city"` Country Geo `json:"country"` Sex int `json:"sex"` BDate string `json:"bdate"` Photo50 string `json:"photo_50"` Photo100 string `json:"photo_100"` Status string `json:"status"` About string `json:"about"` Relation int `json:"relation"` Hidden int `json:"hidden"` Closed bool `json:"is_closed"` CanAccessClosed bool `json:"can_access_closed"` Deactivated string `json:"deactivated"` IsAdmin bool `json:"is_admin"` IsOwner bool `json:"is_owner"` }
User - simple VK user struct
type UserLongPollServer ¶
type UserLongPollServer struct { Key string Server string Ts int Wait int Mode int Version int RequestInterval int NeedPts bool API *VkAPI LpVersion int ReadMessages map[int64]time.Time }
LongPollServer - longpoll server structure
func NewUserLongPollServer ¶
func NewUserLongPollServer(needPts bool, lpVersion int, requestInterval int) (resp *UserLongPollServer)
NewLongPollServer - get longpoll server
func (*UserLongPollServer) FilterReadMesages ¶
func (server *UserLongPollServer) FilterReadMesages(messages []*Message) (result []*Message)
FilterReadMesages - filter read messages
func (*UserLongPollServer) GetLongPollMessages ¶
func (server *UserLongPollServer) GetLongPollMessages() ([]*Message, error)
GetLongPollMessages - get messages via longpoll
func (*UserLongPollServer) Init ¶
func (server *UserLongPollServer) Init() (err error)
Init - init longpoll server
func (*UserLongPollServer) ParseLongPollMessages ¶
func (server *UserLongPollServer) ParseLongPollMessages(j string) (*LongPollResponse, error)
ParseLongPollMessages - parse longpoll messages
func (*UserLongPollServer) Request ¶
func (server *UserLongPollServer) Request() ([]byte, error)
Request - make request to longpoll server
type UserLongPollServerResponse ¶
type UserLongPollServerResponse struct {
Response UserLongPollServer
}
LongPollServerResponse - response format for longpoll info
type UserProfile ¶
type UserProfile struct { ID int64 FirstName string `json:"first_name"` LastName string `json:"last_name"` IsClosed bool `json:"is_closed"` CanAccessClosed bool `json:"can_access_closed"` Sex int ScreenName string `json:"screen_name"` BDate string `json:"bdate"` Photo string Online int City Geo Country Geo }
UserProfile - conversation user profile
type UsersResponse ¶
UsersResponse - VK user response
type VKBot ¶
type VKBot struct { LastMsg int64 IgnoreBots bool API *VkAPI // contains filtered or unexported fields }
VKBot - bot config
func (*VKBot) CheckFriends ¶
func (bot *VKBot) CheckFriends()
CheckFriends checking friend invites and matсhes and deletes mutual
func (*VKBot) GetMessages ¶
GetMessages - request unread messages from VK (more than 200)
func (*VKBot) HandleAction ¶
HandleAction - add action handler. Function must return string to reply or "" (if no reply)
func (*VKBot) HandleAdvancedMessage ¶
HandleAdvancedMessage - add substr message handler. Function must return string to reply or "" (if no reply)
func (*VKBot) HandleError ¶
HandleError - add error handler
func (*VKBot) HandleMessage ¶
HandleMessage - add substr message handler. Function must return string to reply or "" (if no reply)
func (*VKBot) ListenGroup ¶
ListenGroup - listen group VK API
func (*VKBot) ListenUser ¶
ListenUser - listen User VK API (deprecated)
func (*VKBot) MainRoute ¶
func (bot *VKBot) MainRoute(poller LongPollServer)
MainRoute - main router func. Working cycle Listen.
func (*VKBot) RouteAction ¶
RouteAction routes an action
func (*VKBot) RouteMessage ¶
RouteMessage routes single message
func (*VKBot) RouteMessages ¶
RouteMessages routes inbound messages
func (*VKBot) SetAutoFriend ¶
SetAutoFriend - auto add friends
func (*VKBot) SetIgnoreBots ¶ added in v2.0.12
SetIgnoreBots - ignore bots messages
type VKMembers ¶
type VKMembers struct { Items []MemberItem `json:"items"` Profiles []UserProfile `json:"profiles"` Groups []GroupProfile `json:"groups"` }
VKMembers - conversation members info
type VkAPI ¶
type VkAPI struct { Token string URL string Ver string UID int64 GroupID int64 Lang string HTTPS bool AdminID int64 MessagesCount int RequestInterval int DEBUG bool }
VkAPI - api config
func (*VkAPI) CallMethod ¶
CallMethod - call VK API method by name to interfce
func (*VkAPI) CurrentGroup ¶
func (api *VkAPI) CurrentGroup() (*GroupProfile, error)
CurrentGroup - get current group info
func (*VkAPI) DeleteFriend ¶
DeleteFriend - delete friend
func (*VkAPI) GetChatInfo ¶
GetChatInfo - returns Chat info by id
func (*VkAPI) GetChatUsers ¶
func (*VkAPI) GetConversation ¶
GetChatInfo - returns Chat info by id
func (*VkAPI) GetConversationMembers ¶
GetChatUsers - get chat users
func (*VkAPI) GetFriendRequests ¶
GetFriendRequests - get friend requests
func (*VkAPI) GetMessages ¶
GetMessages - get user messages (up to 200)
func (*VkAPI) GetRandomID ¶
func (*VkAPI) GetUserChatInfo ¶
GetChatInfo - returns Chat info by id
func (*VkAPI) GetUserChatUsers ¶
GetChatUsers - get chat users
func (*VkAPI) NotifyAdmin ¶
NotifyAdmin - send notify to admin
func (*VkAPI) SendAdvancedPeerMessage ¶
SendAdvancedPeerMessage sending a message to chat
func (*VkAPI) SendChatMessage ¶
SendChatMessage sending a message to chat
func (*VkAPI) SendMessage ¶
SendMessage sending a message to user
func (*VkAPI) SendPeerMessage ¶
SendPeerMessage sending a message to chat