Skip to content

Instantly share code, notes, and snippets.

@imring
Last active January 26, 2021 17:39
Show Gist options
  • Save imring/e873a88ad3a915bbc3a408f1997bb423 to your computer and use it in GitHub Desktop.
Save imring/e873a88ad3a915bbc3a408f1997bb423 to your computer and use it in GitHub Desktop.
local requests = require 'requests'
local json = require 'cjson'
local url = 'https://api.vk.com/method/%s'
local mt = {}
-- http://lua-users.org/wiki/CopyTable
local function shallowcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
local function send(self, method, data, full_info)
local params = shallowcopy(data)
params.access_token = self.token
params.v = self.v
local res = requests.get{url:format(method), params = params}
return full_info and res or json.decode(res.text)
end
function mt.__index(self, index)
local v = rawget(self, index)
if v ~= nil then return v end
local t = shallowcopy(self)
if not t.method then t.method = {} end
table.insert(t.method, tostring(index))
return setmetatable(t, getmetatable(self))
end
function mt.__call(self, data, full_info)
return send(self, table.concat(self.method, '.'), data, full_info)
end
local function new(token, version)
return setmetatable({ token = token, v = version, send = send }, mt)
end
return { new = new }
@imring
Copy link
Author

imring commented Jan 18, 2021

Example:

local vkapi = require 'vkapi'
local me = vkapi.new(require('config'), '5.126')

local info = me.friends.areFriends{ user_ids = { 93787870, 103509140 } }
-- equivalent: local info = me:send('friends.areFriends', { user_ids = { 93787870, 103509140 } })

assert(info and info.response)
for i, k in pairs(info.response) do
  print(k.user_id, k.friend_status)
end

-- 93787870        3
-- 103509140       3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment