Skip to content

Instantly share code, notes, and snippets.

@ulidtko
Created November 21, 2012 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulidtko/4123870 to your computer and use it in GitHub Desktop.
Save ulidtko/4123870 to your computer and use it in GitHub Desktop.
VK API Python client
#!/usr/bin/env python
from vk import VkAPI
my_id = "8281539"
app_id = "1846406"
secret = "xxxxxxxxxxx"
if __name__=='__main__':
import json
from sys import argv, stderr
from optparse import OptionParser
optparser = OptionParser("Usage: %prog [options] <song name>")
optparser.add_option("-x", "--exact",
action="store_true",
help="restrict output to exact matches")
optparser.add_option("-n", "--count", default=1,
help="limit count of results to COUNT")
optparser.add_option("-v", "--verbose", default=False,
action="store_true",
help="dump everything returned from the query")
options, args = optparser.parse_args()
if len(args) != 1:
optparser.print_help()
exit(1)
query = args[0].lower()
api = VkAPI(my_id, app_id, secret)
response = api.make_request("audio.search", q=query, count=options.count)
if options.verbose:
print json.dumps(response, indent=4)
exit(0)
if response.has_key("error"):
print >> stderr, argv[0], "error:", response["error"]["error_msg"]
exit(1)
#-- now response should be a list of dictionaries
#-- response[0] - string indicating total count
#-- of matching results in the DB
audios = response["response"][1:]
if options.exact:
def songs_match(songdata):
artisttitle = "%(artist)s - %(title)s" % songdata
return artisttitle.lower() == query.lower()
audios = filter(songs_match, audios)
print "\n".join(entry["url"] for entry in audios)
#!/usr/bin/env python
from urllib import urlopen, urlencode
import json
try:
from BeautifulSoup import BeautifulStoneSoup
except:
BeautifulStoneSoup = None
class VkAPI():
""" Vkontakte API, http://vkontakte.ru/apps.php?act=api
Various accessible methods can be found here:
http://vkontakte.ru/pages.php?id=2369282
"""
def __init__(self, my_id, app_id, secret):
self.my_id = my_id
self.app_id = app_id
self.secret = secret
def make_request(self, method, **kwargs):
""" performs request of method with specified parameters """
def makeSig(data):
from hashlib import md5
params="".join("%s=%s" % (k, data[k])
for k in sorted(data.keys()))
#print "returning hash of "+"self.my_id"+params+self.secret
return md5(self.my_id+params+self.secret).hexdigest()
base_path = "http://api.vkontakte.ru/api.php"
qdata = {
"test_mode": "1",
"v": "2.0",
"count": 50 #-- 200 is maximum allowed by the server
}
qdata.update(kwargs)
qdata["api_id"] = self.app_id
qdata["method"] = method
qdata["format"] = "json"
qdata["sig"] = makeSig(qdata)
url_query = urlencode(qdata)
#print "VkAPI: making GET of " + base_path + "?" + url_query + "...",
h = urlopen(base_path + "?" + url_query)
#print "got " + str(h.code)
decode_that_ugly_html_entities_in_json = True
if decode_that_ugly_html_entities_in_json and BeautifulStoneSoup:
return json.loads(BeautifulStoneSoup(h.read(), convertEntities="html").contents[0])
else:
return json.load(h)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment