-
Notifications
You must be signed in to change notification settings - Fork 0
/
vk.py
76 lines (69 loc) · 2.33 KB
/
vk.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
# -*- coding: utf-8 -*-
import requests,json,time,random,os,traceback,sys
from utils import *
main_funcs=['call', 'send', 'lp_loop']
class vkmain:
def __init__(self, token, id, is_group = False):
self.token = token
self.is_grp = is_group
self.lp = None
self.id = id
def call(self, method, d={}, **args):
param = {'v':'5.91','access_token':self.token}
param.update(d)
param.update(args)
ret = requests.post('https://api.vk.com/method/'+method, data=param)
return D(ret.json())
def send(self, text, snd, fwd=0, attach=None, is_group=1):
ln=len(text)
if ln > 4096:
mess=[]
for i in range(int(ln/4096)+1):
time.sleep(1)
self.call('messages.send',peer_id=snd,message=text[i*4096:(i+1)*4096],random_id=random.randint(0,2**10))
return True
else: return self.call('messages.send',peer_id=snd,message=text,attachment=attach,random_id=random.randint(0,2**10))
def GetLP( self ):
try:
if self.is_grp: return self.call('groups.getLongPollServer',v=5.84,lp_version=3,group_id=self.id).response
else: return self.call('messages.getLongPollServer',v=5.84,lp_version=3)['response']
except Exception as e:
print('longpoll error: '+str(e))
return self.GetLP()
def lp_loop(self, func):
self.lp = self.GetLP()
while True:
try:
if self.is_grp:
sv='%s?act=a_check&key=%s&ts=%s&wait=25&mode=2&version=3'%(self.lp.server, self.lp.key, self.lp.ts)
response = D(requests.post(sv).json())
self.lp.ts=response.ts
for result in response.updates:
func(result.object)
else:
sv='http://%s?act=a_check&key=%s&ts=%s&wait=25&mode=2&version=3'%(self.lp['server'],self.lp['key'],self.lp['ts'])
response = D(requests.post(sv).json())
self.lp.ts=response.ts
for result in response.updates:
func(result)
except KeyboardInterrupt:
exit('KeyboardInterrupt')
except:
traceback.print_exc()
self.lp = self.GetLP( )
class vk:
class _submethod:
def __init__(self, vk , name):
self._name = name
self._vk = vk
def __getattr__(self,name):
def call(d = {},**args):
d.update(args)
return self._vk.call(self._name+'.'+name, d)
return call
def __init__(self, token, id=0, is_group = False):
self._vk=vkmain( token, id, is_group )
def __getattr__(self, name):
if name in main_funcs:
return getattr( self._vk, name)
return self._submethod(self._vk, name)