-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplevk.py
87 lines (67 loc) · 2.83 KB
/
simplevk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import logging
import json
import time
from html.parser import HTMLParser
try:
import requests
except ImportError:
print('установите библиотеку requests')
class vk:
app_id = ''
user_id = ''
access_token = ''
v = '5.64'
def authorize(self, app_id, login, password, scope, v):
self.app_id = app_id
self.v = v
with requests.Session() as vk_session:
r = vk_session.get('https://oauth.vk.com/authorize?client_id='+app_id+'&display=page&redirect_uri=https://vk.com&scope='+scope+'&response_type=token&v='+v)
p = vkParser()
p.feed(r.text)
p.close()
p.login_data['email'] = login
p.login_data['pass'] = password
if p.method == 'get':
r = vk_session.get(p.url, params=p.login_data)
elif p.method == 'post':
r = vk_session.post(p.url, data=p.login_data)
if r.url.find('access_token=') >= 0:
self.access_token = r.url.partition('access_token=')[2].split('&')[0]
self.user_id = r.url.partition('user_id=')[2]
else:
p = vkParser()
p.feed(r.text)
p.close()
if p.method == 'get':
r = vk_session.get(p.url)
if p.method == 'post':
r = vk_session.post(p.url)
self.access_token = r.url.partition('access_token=')[2].split('&')[0]
self.user_id = r.url.partition('user_id=')[2]
if not self.user_id:
raise AuthorizationError('Неправильный логин или пароль')
def request(self, method, params=''):
access_param = '&access_token='+str(self.access_token) if self.access_token else ''
api_request = requests.get('https://api.vk.com/method/'+method+'?'+params+access_param+'&v='+str(self.v))
return api_request.json()
def encode_cyrilic(self, text):
return str(text.encode("utf-8")).replace("\\x", "%")[2:-1]
class vkParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.login_data = {}
self.method = "GET"
self.url = ""
def handle_starttag(self, tag, atribs):
attrs = {}
for attr in atribs:
attrs[attr[0]] = attr[1]
if tag == 'form':
self.url = attrs['action']
if 'method' in attrs:
self.method = attrs['method']
elif tag == 'input' and 'name' in attrs:
self.login_data[attrs['name']] = attrs['value'] if 'value' in attrs else ""
class AuthorizationError(Exception):
def __init__(self, value):
self.value = value