Advertisement
stuppid_bot

Untitled

Nov 18th, 2013
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # @author: noname <tz4678@gmail.com>
  3. # @description: модуль для работы с API Вконтакте
  4. # Полный список методов API можно увидеть здесь https://vk.com/dev/methods
  5. import sys
  6. import urllib
  7. import json
  8. import urllib2
  9. import uuid
  10. import os
  11. import mimetypes
  12.  
  13. class NeedCaptchaError(Exception):
  14.     def __init__(self, captcha_img, captcha_sid):
  15.         super(NeedCaptchaError, self).__init__('need captcha')
  16.         self.captcha_img = captcha_img
  17.         self.captcha_sid = captcha_sid
  18.  
  19. class VkAuthError(Exception):
  20.     pass
  21.  
  22. class VkApiError(Exception):
  23.     pass
  24.  
  25. class VkUploadError(Exception):
  26.     pass
  27.  
  28. class VkClient(object):
  29.     def __init__(self, client_id, client_secret, permissions, api_version):
  30.         self.client_id = client_id
  31.         self.client_secret = client_secret
  32.         self.permissions = permissions
  33.         self.api_version = api_version
  34.         self.user_agent = 'VkClient (Python %s.%s.%s)' % sys.version_info[:3]
  35.         self.user_id = None
  36.         self.access_token = None
  37.  
  38.     def fetch_json(self, url, data = None, headers = {}):
  39.         headers.setdefault('User-Agent', self.user_agent)
  40.         request = urllib2.Request(url, data, headers)
  41.         response = urllib2.urlopen(request);
  42.         content = response.read().decode('utf-8')
  43.         return json.loads(content)
  44.  
  45.     def auth(self, username, password, **params):
  46.         defaults = {
  47.             'username': username,
  48.             'password': password,
  49.             'client_id': self.client_id,
  50.             'client_secret': self.client_secret,
  51.             'scope': self.permissions,
  52.             'v': self.api_version,
  53.             'grant_type': 'password'
  54.         }
  55.         params.update(defaults)
  56.         result = self.fetch_json('https://oauth.vk.com/token?' + urllib.urlencode(params))
  57.         if 'error' in result:
  58.             if result['error'] == 'need_captcha':
  59.                 # raise NeedCaptchaError(result['captcha_img'], result['captcha_sid'])
  60.             raise VkAuthError('%s. Error Description: %s' % (result['error'], result.get('error_description', '')))
  61.         self.user_id = result['user_id']
  62.         self.access_token = result['access_token']
  63.  
  64.     def raw_api(self, uri, params = {}):
  65.         headers = {}
  66.         if len(params):
  67.             for k, v in params.items():
  68.                 if type(v) == unicode:
  69.                     params[k] = v.encode('utf-8')
  70.             headers['Content-Type'] = 'application/x-www-form-urlencoded'
  71.         data = urllib.urlencode(params) if len(params) else None
  72.         result = self.load_json('https://api.vk.com/method/' + uri, data, headers)
  73.         if 'error' in result:
  74.             error = result['error']
  75.             if error['error_code'] == 14:
  76.                 # raise NeedCaptchaError(error['captcha_img'], error['captcha_sid'])
  77.             raise VkApiError(error['error_msg'])
  78.         return result['response']
  79.  
  80.     def api(self, uri, params = {}):
  81.         params.update({
  82.             'access_token': self.access_token,
  83.             'v': self.api_version
  84.         })
  85.         return self.raw_api(uri, params)
  86.  
  87.     def escape_quote(self, s):
  88.         return s.replace('"', '\\"')
  89.  
  90.     # VkClient().upload(server_url, {'photo': filename})
  91.     def upload(self, server_url, files):
  92.         boundary = uuid.uuid4().hex
  93.         L = []
  94.         for fieldname, filename in files.items():
  95.             extension = os.path.splitext(filename)[1]
  96.             L.extend([
  97.                 '--' + boundary,
  98.                 'Content-Disposition: form-data; name="%s"; filename="%s"' % (self.escape_quote(fieldname), os.path.basename(filename)),
  99.                 'Content-Type: ' + (mimetypes.types_map[extension] if extension in mimetypes.types_map else 'application/octet-stream'),
  100.                 '',
  101.                 open(filename, 'rb').read()
  102.             ])
  103.         L.extend([
  104.             '--' + boundary + '--',
  105.             ''
  106.         ])
  107.         headers = {
  108.             'Content-Type': 'multipart/form-data; boundary="%s"' % boundary,
  109.         }
  110.         result = self.fetch_json(server_url, '\r\n'.join(L), headers)
  111.         if 'error' in result:
  112.             raise VkUploadError(result['error'])
  113.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement