· 6 years ago · Sep 07, 2019, 05:08 PM
1import urllib.request as req
2import json
3import re
4import os.path
5
6access_token="e2db779d403493b554be533d4fafaf0d3c3ac6c2e5487421af2ea28ea2d0073fc725c4f8e3e7cbb8b7699"
7
8def getContents( url ): #просто urlopen использовать неудобно
9 #возвращает содержимое страницы по адресу url
10 res = req.urlopen( url )
11 if not type( res ) == 'str':
12 res = res.read().decode( 'utf-8' )
13 return res
14
15
16def API( method, params ): #обращение к API
17 query = 'https://api.vk.com/method/' + method + '?v=5.101'
18
19 for key in params:
20 query += '&' + key + '=' + params[ key ]
21
22 return json.loads( getContents( query ) )
23
24longPoll = API( 'messages.getLongPollServer', {
25 'access_token': access_token,
26 'v': '5.65',
27 'lp_version': '3'} )
28
29key = longPoll["response"]["key"]
30server = longPoll["response"]["server"]
31ts = longPoll["response"]["ts"]
32
33while True:
34 query = 'https://' + str( server ) +'?act=a_check&key=' + str( key ) + '&ts=' + str( ts ) + '&wait=25&mode=2&version=3'
35
36 resp = json.loads( getContents( query ) )
37
38 ts = str(resp["ts"])
39 updates = resp["updates"]
40
41 for upd in updates:
42 if upd[0] == 4: #новое сообщение
43 print( upd[5] )