Advertisement
stuppid_bot

Untitled

Dec 9th, 2014
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.42 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import requests
  3. import datetime
  4. import re
  5. import os
  6.  
  7. USER_AGENT='VkClient'
  8. API_VERSION=5.27
  9. AUTH_TOKEN_URL='https://oauth.vk.com/token'
  10. API_URL='https://api.vk.com/method/{method}'
  11.  
  12. class VkClient(object):
  13.     user_id=0
  14.     expires_at=None
  15.     session=requests.Session()
  16.     session.headers['User-Agent']=USER_AGENT
  17.  
  18.     def __init__(self, client_id=0,  client_secret='', permissions='',\
  19.                  access_token='', api_version=API_VERSION):
  20.         self.client_id=client_id
  21.         self.client_secret=client_secret
  22.         self.permissions=permissions
  23.         self.access_token=access_token
  24.         self.api_version=api_version
  25.  
  26.     def authRequest(self, url, params):
  27.         params=dict(params)
  28.         r=self.session.post(url, data=params).json()
  29.         if 'error' in r:        
  30.             if r['error'] == 'need_captcha':
  31.                 self.addCaptchaParams(params, r)
  32.                 return self.authRequest(url, params)
  33.             if r['error'] == 'need_validation':
  34.                 return self.validate(r['redirect_uri'])
  35.             raise VkAuthorizationError(r['error'], r['error_description'])
  36.         self.access_token=r['access_token']
  37.         if 'user_id' in r:
  38.             self.user_id=r['user_id']
  39.         if r.get('expires_in') > 0:
  40.             self.expires_at=datetime.datetime.now() +\
  41.                             datetime.timedelta(seconds=r['expires_in'])
  42.  
  43.     def authDirect(self, username, password):
  44.         params={}
  45.         params['username']=username
  46.         params['password']=password
  47.         params['client_id']=self.client_id
  48.         params['client_secret']=self.client_secret
  49.         params['scope']=self.permissions
  50.         params['grant_type']='password'
  51.         self.authRequest(AUTH_TOKEN_URL, params)
  52.  
  53.     def authSite(self):
  54.         """Not implemented yet."""
  55.         pass
  56.  
  57.     def authMobile(self):
  58.         """Not implemented yet."""
  59.         pass
  60.  
  61.     def authServer(self):
  62.         """Not implemented yet."""
  63.         pass
  64.  
  65.     def api(self, method, params={}):
  66.         params=dict(params)
  67.         params['access_token']=self.access_token
  68.         params['v']=self.api_version
  69.         url=API_URL.format(method=method)
  70.         r=self.session.post(url, data=params).json()
  71.         if 'error' in r:
  72.             error=r['error']
  73.             if error['error_code'] == 14:
  74.                 self.addCaptchaParams(params, error)
  75.             elif error['error_code'] == 17:
  76.                 # Получаем новый access_token.
  77.                 self.validate(error['redirect_uri'])
  78.             else:
  79.                 raise VkApiError(error['error_code'], error['error_msg'])
  80.             # Отправляем запрос повторно.
  81.             return self.api(method, params)
  82.         return r['response']
  83.  
  84.     # <VkClient>.<МЕТОД_API_ВКОНТАКТЕ>(<СЛОВАРЬ_ИЛИ_ИМЕНОВАННЫЕ_АРГУМЕНТЫ>)
  85.     # <VkClient>.users.get(user_id=1)
  86.     # <VkClient>.users.get({'user_id': 1})
  87.     # <VkClient>.api('users.get', {'user_id': 1})
  88.     def __getattr__(self, name):
  89.         return VkApiMethod(self, name)
  90.  
  91.     def upload(self, url, files):
  92.         _files={}
  93.         for field, src in files.items():
  94.             if re.match('(?i)https?://', src):
  95.                 r=self.session.get(src)
  96.                 content=r.content
  97.             else:
  98.                 f=open(src, 'rb')
  99.                 content=f.read()
  100.                 f.close()
  101.             # Баг с non-ascii символами в имени файла.
  102.             filename=os.path.basename(src).encode('ascii', 'replace')
  103.             _files[field]=(filename, content)
  104.         r=self.session.post(url, files=_files).json()
  105.         if 'error' in r:
  106.             raise VkUploadError(r['error'])
  107.         return r
  108.  
  109.     def solveCaptcha(self, image_url):
  110.         raise VkCaptchaError("Captcha needed.")
  111.  
  112.     def validate(self, redirect_uri):
  113.         raise VkValidationError("Validation needed.")
  114.  
  115.     def checkAccessToken(self):
  116.         try:
  117.             if self.users.isAppUser():
  118.                 return True
  119.         except VkApiError, e:
  120.             pass
  121.         return False
  122.  
  123.     def addCaptchaParams(self, request_params, captcha_params):
  124.         request_params['captcha_sid']=captcha_params['captcha_sid']
  125.         captcha_key=self.solveCaptcha(captcha_params['captcha_img'])
  126.         request_params['captcha_key']=captcha_key
  127.  
  128. class VkApiMethod(object):
  129.     def __init__(self, client, name):
  130.         self.client=client
  131.         self.name=name
  132.  
  133.     def __call__(self, *args, **kwargs):
  134.         if len(args):
  135.             kwargs.update(args[0])
  136.         return self.client.api(self.name, kwargs)
  137.  
  138.     def __getattr__(self, name):
  139.         return self.__class__(self.client, self.name + '.' + name)
  140.  
  141. class VkClientError(Exception):
  142.     pass
  143.  
  144. class VkCaptchaError(VkClientError):
  145.     pass
  146.  
  147. class VkValidationError(VkClientError):
  148.     pass
  149.  
  150. class VkAuthorizationError(VkClientError):
  151.      def __init__(self, error_type, error_description):
  152.         super(VkAuthorizationError, self)\
  153.             .__init__("{}: {}".format(error_type, error_description))
  154.         self.type=error_type
  155.  
  156. class VkApiError(VkClientError):
  157.     def __init__(self, error_code, error_msg):
  158.         super(VkApiError, self)\
  159.             .__init__("[{}] {}".format(error_code,error_msg))
  160.         self.code=error_code
  161.  
  162. class VkUploadError(VkClientError):
  163.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement