stuppid_bot

VkClient класс для работы с API Вконтакте

Mar 30th, 2014
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.58 KB | None | 0 0
  1. # -*- coding: utf8 -*-
  2. # Модуль для работы с API Вконтакте. Список методов API можно увидеть здесь https://vk.com/dev/methods.
  3. #
  4. import os, re, sys, json, time, uuid, urllib, urllib2, mimetypes, webbrowser
  5.  
  6. class VKClientError(Exception):
  7.     pass
  8.  
  9. class VKClient(object):
  10.     def __init__(self, api_version, access_token='', user_id=None, expires=None):
  11.         self.user_agent = 'VKClient (Python %s.%s.%s)' % sys.version_info[:3]
  12.         self.auth_url = 'https://oauth.vk.com/{0}?{1}'
  13.         self.api_url = 'https://api.vk.com/method/'
  14.         self.api_version = api_version
  15.         self.access_token = access_token
  16.         self.user_id = user_id
  17.         self.expires = expires
  18.  
  19.     def fetch_json(self, url, data=None, headers={}):
  20.         headers.setdefault('User-Agent', self.user_agent)
  21.         request = urllib2.Request(url, data, headers)
  22.         try:
  23.             response = urllib2.urlopen(request)
  24.             content = response.read()
  25.         except urllib2.HTTPError, error:
  26.             content = error.read()
  27.         return json.loads(content.decode('utf8'))
  28.  
  29.     def captcha_handler(self, url):
  30.         raise VKClientError('Captcha is needed')
  31.  
  32.     def captcha_params(self, params, response):
  33.         params['captcha_key'] = self.captcha_handler(response['captcha_img'])
  34.         params['captcha_sid'] = response['captcha_sid']
  35.  
  36.     def encode_params(self, params):
  37.         for k, v in params.items():
  38.             if type(v) == unicode:
  39.                 params[k] = v.encode('utf8')
  40.  
  41.     def auth(self, params, auth_type='authorize'):
  42.         params['v'] = self.api_version
  43.         self.encode_params(params)
  44.         response = self.fetch_json(self.auth_url.format(auth_type, urllib.urlencode(params)))
  45.         if 'error' in response:
  46.             if response['error'] == 'need_captcha':
  47.                 self.captcha_params(params, response)
  48.                 return self.auth(params)
  49.             if response['error'] == 'need_validation' and 'redirect_uri' in response:
  50.                 webbrowser.open(response['redirect_uri'])
  51.             raise VKClientError(response['error'] + ': ' + response['error_description'])
  52.         self.access_token = response['access_token']
  53.         if 'user_id' in response:
  54.             self.user_id = response['user_id']
  55.         if 'expires_in' in response and response['expires_in'] > 0:
  56.             self.expires = time.time() + response['expires_in']
  57.  
  58.     def api(self, method, params={}):      
  59.         params['v'] = self.api_version
  60.         if self.access_token:
  61.             params['access_token'] = self.access_token
  62.         self.encode_params(params)
  63.         data = urllib.urlencode(params)
  64.         headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  65.         response = self.fetch_json(self.api_url + method, data, headers)
  66.         if 'error' in response:
  67.             response = response['error']
  68.             if response['error_code'] == 14:
  69.                 self.captcha_params(params, response)
  70.                 return self.api(method, params)
  71.             raise VKClientError('API error code: %s - %s' % (response['error_code'], response['error_msg']))
  72.         return response['response']
  73.  
  74.     def upload(self, upload_url, files):
  75.         boundary = '--VKClientBoundary_' + uuid.uuid4().hex
  76.         data = []
  77.         for q, w in files.items():
  78.             if re.match('https?://', w, re.I):
  79.                 u = urllib.urlopen(w)
  80.                 content_type = u.info()['content-type']
  81.                 content = u.read()
  82.             else:
  83.                 w = w.encode(sys.getfilesystemencoding())
  84.                 extension = os.path.splitext(w)[1]
  85.                 content_type = mimetypes.types_map[extension] if extension in mimetypes.types_map else 'application/octet-stream'
  86.                 f = open(w, 'rb')
  87.                 content = f.read()
  88.                 f.close()
  89.             data.extend([
  90.                 '--' + boundary,
  91.                 'Content-Disposition: form-data; name="' + q + '"; filename="' + os.path.basename(w) + '"',
  92.                 'Content-Type: ' + content_type,
  93.                 '',
  94.                 content
  95.             ])
  96.         data.extend([
  97.             '--' + boundary + '--',
  98.             ''
  99.         ])
  100.         headers = {'Content-Type': 'multipart/form-data; boundary="' + boundary + '"'}
  101.         data = '\r\n'.join(data)
  102.         response = self.fetch_json(upload_url, data, headers)
  103.         if 'error' in response:
  104.             raise VKClientError('Upload error: ' + response['error'])
  105.         return response
Advertisement
Add Comment
Please, Sign In to add comment