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 int) 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
- 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()
- func (bot *VKBot) Reply(m *Message, reply Reply) (id int, 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)
- type VKError
- type VKMembers
- type VKUsers
- type VkAPI
- func (api *VkAPI) AddFriend(uid int) 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() (*User, error)
- func (api *VkAPI) DeleteFriend(uid int) bool
- func (api *VkAPI) GetChatFullInfo(chatID int) (*ChatInfo, error)
- func (api *VkAPI) GetChatInfo(chatID int) (*ChatInfo, error)
- func (api *VkAPI) GetChatUsers(chatID int) (users []*User, err error)
- func (api *VkAPI) GetConversation(chatID int) (*ChatInfo, error)
- func (api *VkAPI) GetConversationMembers(chatID int) (users []*User, err error)
- func (api *VkAPI) GetFriendRequests(out bool) (friends []int, err error)
- func (api *VkAPI) GetMessages(count int, offset int) (*Messages, error)
- func (api *VkAPI) GetRandomID() string
- func (api *VkAPI) GetUserChatInfo(chatID int) (*ChatInfo, error)
- func (api *VkAPI) GetUserChatUsers(chatID int) (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 int, err error)
- func (api *VkAPI) SendChatMessage(chatID int, msg string) (id int, err error)
- func (api *VkAPI) SendMessage(userID int, msg string) (id int, err error)
- func (api *VkAPI) SendPeerMessage(peerID int64, msg string) (id int, err error)
- func (api *VkAPI) User(uid int) (*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" "github.com/nikepan/govkbot" "log" ) 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 int `json:"id"` Type string `json:"type"` Title string `json:"title"` Kicked int `json:"kicked"` AdminID int `json:"admin_id"` Users VKUsers }
ChatInfo - chat info
type ChatInfoResponse ¶
ChatInfoResponse - chat info vk struct
type ConversationInfo ¶
type ConversationInfo struct { Peer struct { ID int 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 int `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 GroupLongPollEvent ¶
type GroupLongPollMessage ¶
type GroupLongPollMessage struct { Type string Object struct { Date int `json:"date"` FromID int `json:"from_id"` ID int `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 int `json:"random_id"` //Attachments [] `json:"attachments"` IsHidden bool `json:"is_hidden"` Action struct { Type string MemberID int `json:"member_id"` } } GroupID int }
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[int]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
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 int Name string IsClosed int `json:"is_closed"` Type string Photo50 string Photo100 string Photo200 string }
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 int `json:"member_id"` JoinDate int `json:"join_date"` IsOwner bool `json:"is_owner"` IsAdmin bool `json:"is_admin"` InvitedBy int `json:"invited_by"` }
MemberItem - conversation item
type MembersResponse ¶
MembersResponse - VK user response
type Message ¶
type Message struct { ID int Date int Out int UserID int `json:"user_id"` ChatID int `json:"chat_id"` PeerID int64 `json:"peer_id"` ReadState int `json:"read_state"` Title string Body string Action string ActionMID int `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 int `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` ScreenName string `json:"screen_name"` Photo string `json:"photo"` InvitedBy int `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"` 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[int]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 int 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 int LongPoll LongPollServer 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 ¶
func (*VKBot) ListenUser ¶
func (*VKBot) MainRoute ¶
func (bot *VKBot) MainRoute()
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 ¶
type VKMembers ¶
type VKMembers struct { Items []MemberItem Profiles []UserProfile Groups []GroupProfile }
VKMembers - conversation members info
type VkAPI ¶
type VkAPI struct { Token string URL string Ver string UID int GroupID int Lang string HTTPS bool AdminID int MessagesCount int RequestInterval int DEBUG bool }
VkAPI - api config
func (*VkAPI) CallMethod ¶
CallMethod - call VK API method by name to interfce
func (*VkAPI) CurrentGroup ¶
CurrentGroup - get current group info
func (*VkAPI) DeleteFriend ¶
DeleteFriend - delete friend
func (*VkAPI) GetChatInfo ¶
GetChatInfo - returns Chat info by id
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