-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] LongPoll

, 07 2017 . 19:12 +
!
API . , , VK API, , . , LongPoll , , , , . LongPoll-, - . , . , .

API (, , )
API ? :
Callback API .

, , , . VK API : , , . API vk_api, requests. . vk_api, :

import vk_api
session = vk_api.VkApi(token='{ACCESS_TOKEN}')
print(session.method('users.get', {'user_ids': 210700286, 'fields': 'photo_50, city, verified'}))

:

import vk_api
.

session = vk_api.VkApi(token='{ACCESS_TOKEN}')
access token ( , ). : . , , .

print(session.method('users.get', {'user_ids': 210700286, 'fields': 'photo_50, city'}))
. ? method, : API, . API. users.get : user_ids id , , fields: : . : [{'id': 210700286, 'first_name': 'Lindsey', 'last_name': 'Stirling', 'city': {'id': 5331, 'title': 'Los Angeles'}, 'photo_50': 'https://pp.userapi.com/c636821/v636821286/38a75/Ay-bEZoJZw8.jpg'}]

- , , , : vk_api.exceptions.ApiError: [5] User authorization failed: no access_token passed..
: , , .

requests, API, .
: https://api.vk.com/method/{METHOD_NAME}?{PARAMS}&v={API_VERSION}, {METHOD_NAME} , {PARAMS} , {API_VERSION} API, .
JSON . API requests:

import requests
data = requests.get('https://api.vk.com/method/{METHOD_NAME}'.format(METHOD_NAME='users.get'),
                    params={'user_ids': 210700286, 'fields': 'photo_50, city'}).json()
print(data)

, .

import requests
requests

data = requests.get('https://api.vk.com/method/{METHOD_NAME}'.format(METHOD_NAME='users.get'),
                    params={'user_ids': 210700286, 'fields': 'photo_50, city'}).json()
data . get : , ( ), . access token-, 'access_token'. v ( API) , , , , 'v'. json(), JSON-.

, {'response': [{'uid': 210700286, 'first_name': 'Lindsey', 'last_name': 'Stirling', 'city': 5331, 'photo_50': 'https://pp.userapi.com/c636821/v636821286/38a75/Ay-bEZoJZw8.jpg'}]}.

, : {'error': {'error_code': 5, 'error_msg': 'User authorization failed: no access_token passed.', 'request_params': [{'key': 'oauth', 'value': '1'}, {'key': 'method', 'value': 'user.get'}, {'key': 'user_ids', 'value': '210700286'}, {'key': 'fields', 'value': 'photo_50, city'}]}}.

LongPoll?
:
Long Polling , . , , , - (, ), .
, , , , , , , Long Poll , .
, , Long Poll . , , Long Poll-a: server, key ts.
key ;
server ;
ts , .

, Long Pooll, . , , messages.getLongPollServer. , Long Pooll.

import requests
token = ''  #      access_token
data = requests.get('https://api.vk.com/method/messages.getLongPollServer',
                    params={'access_token': token}).json()['response']  #    
print(data)

, : {'key': '###############################', 'server': 'imv4.vk.com/im####', 'ts': 0000000000}

Long Pooll
, , , , Long Poll ! , : https://{$server}?act=a_check&key={$key}&ts={$ts}&wait=25&mode=2&version=2, {$server}, {$key} {$ts}- 'server', 'key' 'ts' , wait , Long Poll , mode . , Long Poll

import requests
token = ''  #      access_token
params = requests.get('https://api.vk.com/method/messages.getLongPollServer',
                       params={'access_token': token}).json()['response']  #    
response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=90&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()  #    Long Poll     90     2
print(response)

90 - , Long Pooll , : {'ts': 0000000000, 'updates': [[9, -999999999, 0, 1501588841]]}. ?

-, , 'ts', . . , Long Poll , . , 1, 2 . Long Poll, , , . , Long Poll .

-, 'updates' . , , . . , . , , . 'ts' . , 'updates', , wait . : ?. , . , , Long Poll .

Long Pooll
, Long Pooll, , . , Long Pooll

import requests
token = ''  #      access_token
data = requests.get('https://api.vk.com/method/messages.getLongPollServer',
                    params={'access_token': token}).json()['response']  #    
while True:
    response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=20&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()  #    Long Poll     20    2
    updates = response['updates']
    if updates:  # ,   
        for element in updates:  #      
            print(element)
    data['ts'] = response['ts']  #    

Long Pooll-, , , . , , . :
[8, -999999999, 1, 1501592696]
[8, -999999999, 7, 1501592862]
[9, -999999999, 0, 1501592882]
[9, -999999999, 1, 1501592583]
[8, -999999999, 4, 1501592893]
[9, -999999999, 0, 1501592900]

. , , . ( ):
1 (FLAGS:=$flags);
2 (FLAGS|=$mask);
3 (FLAGS&=~$mask);
4 ;
6 $peer_id, $local_id.
7 $peer_id, $local_id.
8 $user_id . $extra 0, mode 64. ( 256) extra $timestamp $user_id ;
9 $user_id ($flags 0, (, ) 1, (, away)). $timestamp $user_id ;
10 $peer_id. (PEER_FLAGS &= ~$flags). ;
11 $peer_id. (PEER_FLAGS:= $flags). ;
12 $peer_id. (PEER_FLAGS|= $flags). ;
13 $peer_id $local_id;
14 ( 20 ) $peer_id $local_id;
51 (, ) $chat_id . $self 1 0 ( );
61 $user_id . ~5 . $flags = 1;
62 $user_id $chat_id;
70 $user_id $call_id;
80 $count;
112 . $peer_id /.

, 8, - , 9 . , , .

, . , , . 80 , . 80:
[80, 0, 0]
[80, 1, 0]

, , . 2 : 0 0 1 0 . 80 , ; . , . 0 ( ), . , 80. :

#         ,      
while True:
    response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=20&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()  #    Long Poll     20    2
    updates = response['updates']
    if updates:  # ,   
        for element in updates:  #      
            action_code = element[0]  #     
            if action_code == 80:  #   
                print('    ', element[1])  # 
    data['ts'] = response['ts']  #    

, . 8 9 . , . 9. , :

elif action_code == 9:

, 9:
[9, -000000000, 1, 1501744865]
0, , 9. id , ( id, -1, ). 3 2 : 0 1. 1 , - , 0 , , . Unix time. :

user_id = element[1] * -1  # id ,  
user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0]  # ,      id = user_id 
timeout = bool(element[2])  #        -
last_visit = element[3]  #        Unix time

, , . , - . timeout False, , True, -. :

#     "import time",    
if user['sex'] == 1:
    verb = ['', '']
else:
    verb = ['', '']
if timeout:
    print(user['first_name'], user['last_name'], verb[0], '   -.     :', time.ctime(last_visit).split()[3])
else:
    print(user['first_name'], user['last_name'], verb[1], ' .     :', time.ctime(last_visit).split()[3])

, :

time.ctime(last_visit).split()[3]
. ctime time Unix time 'Thu Jan 1 03:00:00 1970'
. , split , 0 , 1 , 2 , 3 , 4 . 3, .

8. : [8, -6892937, 4, 1501750273]. id , , , , Unix time. :

user_id = element[1] * -1  # id ,  
user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0]  # ,      id = user_id
platform = element[2]  #   
last_visit = element[3]  #     Unix time
if user['sex'] == 1:
    verb = ''
else:
    verb = ''

, . platform 1 7 . , . :

#     
if platform == 1:
    platform = '   web- VK'
elif platform == 2:
    platform = '  VK  iPhone'
elif platform == 3:
    platform = '  VK  iPad'
elif platform == 4:
    platform = '  VK  Android'
elif platform == 5:
    platform = '  VK  Windows Phone'
elif platform == 6:
    platform = '  VK  Windows'
elif platform == 7:
  platform = ' web- VK'

:

print(user['first_name'], user['last_name'], verb, ' ', platform, '', time.ctime(last_visit).split()[3])

61 62. , - . , 61 , 62 . 62 : [62, 000000000, 000]. id , , . 61 : [61, 000000000, 1]. id , . :

elif action_code == 61:
    user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': element[1]}).json()['response'][0]  #     
    print(user['first_name'], user['last_name'], ' ')
elif action_code == 62:
    user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': element[1]}).json()['response'][0]  #     ,  
    chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': element[2], 'access_token': token}).json()['response']['title']  #   
    print(user['first_name'], user['last_name'], '    "{}"'.format(chat))

.

, , . 4 . 4: [4, $ts, $flag, $id, $unixtime, $text, {'title': ' ... '}]. $ts , $flag , $id id 2000000000 + id ( ), $unixtime Unix time, , , . , : . , , , $id , 2000000000 chat_id ( ). , $id id , , 2000000000 + chat_id . , , $id 2000000000 > 0, , , . , id , , 'from'. :

elif action_code == 4:
    if element[3] - 2000000000 > 0:  # ,      
        user_id = element[6]['from']  # id 
        chat_id = element[3] - 2000000000  # id 
        chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
        user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
        time_ = element[4]  #   
        text = element[5]  #  
        if text:  # ,    
            print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'], '  "{}"'.format(chat) + ':', text)
    else:
        user_id = element[3]  # id 
        user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
        time_ = element[4]  #   
        text = element[5]  #  
        if text:  # ,    
            print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'] + ':', text)

, . :
  • ;
  • -;
  • , ;

, , 2. , , ( ):
+1:
+2:
+4:
+8:
+16:
+32: .
+64:
+128: ( )
+256:
+512:
+65536: . ( ). <2.

. , , . , :

summands = []  # ,     
flag = element[2]  #  
for number in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 65536]:  #     
    if flag & number:  # ,        
        summands.append(number)  #  ,    

, , ,

if 2 not in summands:

, , :

elif action_code == 4:
    summands = []  # ,     
    flag = element[2]  #  
    for number in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 65536]:  #     
        if flag & number:  # ,        
            summands.append(number)  #  ,    
    if 2 not in summands:
        if element[3] - 2000000000 > 0:  # ,      
            user_id = element[6]['from']  # id 
            chat_id = element[3] - 2000000000  # id 
            chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
            user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
            time_ = element[4]  #   
            text = element[5]  #  
            if text:  # ,    
                print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'], '  "{}"'.format(chat) + ':', text)
        else:
            user_id = element[3]  # id 
            user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
            time_ = element[4]  #   
            text = element[5]  #  
            if text:  # ,    
                print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'] + ':', text)

-. , , , , , -: [[4, $ts, $flag, $id, $unixtime, $text, {'attach1_type': 'photo', 'attach1': '$photoId', 'attach2_type': 'video', 'attach2': '$videoId', 'attach3_type': 'audio', 'attach3': '$audioId', 'attach4_type': 'doc', 'attach4': '$docId', 'geo': '2_SVK-le', 'geo_provider': '4', 'title': ' ... '}]. , API . (photos.getById docs.getById) ( , ). - , . , ( ) .

if 512 in summands:  # ,   -
    index = 1
    photos = []  #    id 
    docs = []  #    id 
    media_type = 'attach1_type'
    while media_type in element[6].keys():  # ,   -   
        media_type = element[6]['attach{}_type'.format(index)]  #  ,   
        if media_type == 'photo':  #    
            photos.append(element[6]['attach{}'.format(index)])  #  id   
        elif media_type == 'doc':  #    
            docs.append(element[6]['attach{}'.format(index)])  #  id   
        index += 1  #  
        media_type = 'attach{}_type'.format(index)
    change = lambda ids, type_: requests.get('https://api.vk.com/method/{}.getById'.format(type_), params={type_: ids, 'access_token': token}).json()  # ,    
    if photos:  # ,     
        photos = change(', '.join(photos), 'photos')  #  ,    photos  
        if 'response' in photos.keys():
            photos = [attachment['src_xbig'] for attachment in photos['response']]  #   
            print('   :', ', '.join(photos))
        else:
            pass  #  ,   
    if docs:  # ,     
        docs = change(', '.join(docs), 'docs')  #  ,    docs  
        if 'response' in docs.keys():
            docs = [attachment['url'] for attachment in docs['response']]  #   
            print('   :', ', '.join(docs))
        else:
            pass  #  ,   



if text:
, , - .

: , , , . , 6 4. :

  • : [4, $ts, $flag, $chat_id, $unixtime, '', {'source_act': 'chat_title_update', 'source_text': ' ', 'source_old_text': ' ', 'from': '$id'}]
  • : [4, $ts, $flag, $chat_id, $unixtime, '', {'attach1_type': 'photo', 'attach1': '247178624_456242629', 'source_act': 'chat_photo_update', 'from': '247178624'}]
  • : [4, $ts, $flag, $chat_id, $unixtime, '', {'source_act': 'chat_invite_user', 'source_mid': '$added_user_id', 'from': '$adder_id'}]
  • ( ): [4, $ts, $flag, $chat_id, $unixtime, '', {'source_act': 'chat_kick_user', 'source_mid': '&removed_user_id', 'from': '&remover_id'}]
  • : [4, $ts, $flag, $chat_id, $unixtime, '', {'source_act': 'chat_create', 'source_text': '', 'from': '$creator_id'}]

, :

elif action_code == 4:
    if 'source_act' not in element[6].keys():
        # <,  >
    else:
        source_act = element[6]
        if source_act['source_act'] == 'chat_title_update':  #       
            changer_id = source_act['from']  # id ,  
            source_text = source_act['source_text']  #   
            source_old_text = source_act['source_old_text']  #   
            changer = requests.get('https://api.vk.com/method/users.get', params={'user_ids': changer_id, 'fields': 'sex'}).json()['response'][0]  #     ,  
            if changer['sex']:
                verb = ''
            else:
                verb = ''
            print(changer['first_name'], changer['last_name'], verb, '   "{}"  "{}"'.format(source_old_text, source_text))
        elif source_act['source_act'] == 'chat_photo_update':
            chat_id = element[3] - 2000000000  # id 
            chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
            user_id = source_act['from']  # id ,  
            photo_id = source_act['attach1']  # id 
            photo = requests.get('https://api.vk.com/method/photos.getById', params={'photos': photo_id, 'access_token': token}).json()  #   
            user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0]  #    ,  
            if 'error' not in photo.keys():  #       
                if user['sex']:
                    verb = ''
                else:
                    verb = ''
                print(user['first_name'], user['last_name'], verb, '  "{}" '.format(chat), photo['response'][0]['src_xbig'])
            else:
                pass  #  ,     
        elif source_act['source_act'] == 'chat_invite_user':
            chat_id = element[3] - 2000000000  # id 
            chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
            invited_id = source_act['source_mid']  # id 
            inviter_id = source_act['from']  # id 
            if invited_id == inviter_id:  #         -  
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': inviter_id, 'fields': 'sex'}).json()['response'][0]  #    
                if user['sex']:
                    verb = ''
                else:
                    verb = ''
                print(user['first_name'], user['last_name'], verb, '  "{}"'.format(chat))
            else:
                inviter_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': inviter_id, 'fields': 'sex'}).json()['response'][0]  #    
                invited_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': invited_id, 'name_case': 'acc'}).json()['response'][0]  #    
                if inviter_user['sex']:
                    verb = ''
                else:
                    verb = ''
                print(inviter_user['first_name'], inviter_user['last_name'], verb, '  "{}"'.format(chat), invited_user['first_name'], invited_user['last_name'])
        elif source_act['source_act'] == 'chat_kick_user':
            chat_id = element[3] - 2000000000  # id 
            chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
            removed_id = source_act['source_mid']  # id 
            remover_id = source_act['from']  # id 
            if removed_id == remover_id:  #       
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': remover_id, 'fields': 'sex'}).json()['response'][0]  #    
                if user['sex']:
                    verb = ''
                else:
                    verb = ''
                print(user['first_name'], user['last_name'], verb, '  "{}"'.format(chat))
            else:
                remover_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': remover_id, 'fields': 'sex'}).json()['response'][0]  #    
                removed_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': removed_id, 'name_case': 'acc'}).json()['response'][0]  #    
                if remover_user['sex']:
                    verb = ''
                else:
                     verb = ''
                print(remover_user['first_name'], remover_user['last_name'], verb, '  "{}"'.format(chat), removed_user['first_name'], removed_user['last_name'])
        elif source_act['source_act'] == 'chat_create':
            chat = source_act['source_text']  #  
            creator_id = source_act['from']  # id 
            creator = requests.get('https://api.vk.com/method/users.get', params={'user_ids': creator_id, 'fields': 'sex'}).json()['response'][0]  # ,    
            if creator['sex']:
                verb = ''
            else:
                verb = ''
            print(creator['first_name'], creator['last_name'], verb, ' "{}"'.format(chat))


.
: Long Poll . .

: , , KeyError 8: response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=20&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()['response'] # Long Poll 20 2. , error 2, , &key . :

response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=20&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()  #    Long Poll     20    2
try:
    updates = response['updates']
except KeyError:  #       KeyError,   key ,    
    data = requests.get('https://api.vk.com/method/messages.getLongPollServer', params={'access_token': token}).json()['response']  #    
     break  #   ,    

! : . . , . , , , &_amp ( , ). . , sub re ( !).

import re
# <...>
symbols = {'
': '\n', '&': '&', '"': '"', '<': '<', '>': '>', '˜': '~', 'ˆ': '^', '–': '', '—': '', '€': '', '‰': ''} for code, value in symbols.items(): text = re.sub(code, value, text)


, , , , , . , :

import re
import time

import requests

token = ''  #      access_token
data = requests.get('https://api.vk.com/method/messages.getLongPollServer',
                    params={'access_token': token}).json()['response']  #    

while True:
    response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=20&mode=2&version=2'.format(server=data['server'], key=data['key'], ts=data['ts'])).json()  #    Long Poll     20    2
    try:
        updates = response['updates']
    except KeyError:  #       KeyError,   key ,    
        data = requests.get('https://api.vk.com/method/messages.getLongPollServer', params={'access_token': token}).json()['response']  #    
        break  #   ,    

    if updates:  # ,   
        for element in updates:  #      
            action_code = element[0]
            if action_code == 80:  #   
                print('    ', element[1])  # 
            elif action_code == 9:
                user_id = element[1] * -1  # id ,  
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0]  #      id = user_id
                timeout = bool(element[2])  #        -
                last_visit = element[3]  #      
                if user['sex'] == 1:
                    verb = ['', '']
                else:
                    verb = ['', '']
                if timeout:
                    print(user['first_name'], user['last_name'], verb[0], '   -.     :', time.ctime(last_visit).split()[3])
                else:
                    print(user['first_name'], user['last_name'], verb[1], ' .     :', time.ctime(last_visit).split()[3])
            elif action_code == 8:
                user_id = element[1] * -1  # id ,  
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0]  #      id = user_id
                platform = element[2]  #   
                last_visit = element[3]  #     Unix time
                if user['sex'] == 1:
                    verb = ''
                else:
                    verb = ''

                #     
                if platform == 1:
                    platform = '   web- VK'
                elif platform == 2:
                    platform = '  VK  iPhone'
                elif platform == 3:
                    platform = '  VK  iPad'
                elif platform == 4:
                    platform = '  VK  Android'
                elif platform == 5:
                    platform = '  VK  Windows Phone'
                elif platform == 6:
                    platform = '  VK  Windows'
                elif platform == 7:
                    platform = ' web- VK'
                print(user['first_name'], user['last_name'], verb, ' ', platform, '', time.ctime(last_visit).split()[3])

            elif action_code == 61:
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': element[1]}).json()['response'][0]  #     
                print(user['first_name'], user['last_name'], ' ')
            elif action_code == 62:
                user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': element[1]}).json()['response'][0]  #     ,  
                chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': element[2], 'access_token': token}).json()['response']['title']  #   
                print(user['first_name'], user['last_name'], '    "{}"'.format(chat))
            elif action_code == 4:
                if 'source_act' not in element[6].keys():
                    summands = []  # ,     
                    flag = element[2]  #  
                    for number in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 65536]:  #     
                        if flag & number:  # ,        
                            summands.append(number)  #  ,    
                    if 2 not in summands:
                        if element[3] - 2000000000 > 0:  # ,      
                            user_id = element[6]['from']  # id 
                            chat_id = element[3] - 2000000000  # id 
                            chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title']  #   
                            user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
                            time_ = element[4]  #   
                            text = element[5]  #  
                            symbols = {'&': '&', '"': '"', '<': '<', '>': '>', '&tilde': '~', '&circ': '^', '&ndash': '', '&mdash': '', '&euro': '', '&permil': ''}
                            for code, value in symbols.items():
                                text = re.sub(code, value, text)
                            print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'], '  "{}"'.format(chat) + ':', text)
                        else:
                            user_id = element[3]  # id 
                            user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'name_case': 'gen'}).json()['response'][0]  #     ,  
                            time_ = element[4]  #   
                            text = element[5]  #  
                            symbols = {'
': '\n', '&': '&', '"': '"', '<': '<', '>': '>', '˜': '~', 'ˆ': '^', '–': '', '—': '', '€': '', '‰': ''} for code, value in symbols.items(): text = re.sub(code, value, text) print(time.ctime(time_).split()[3] + ':', ' ', user['first_name'], user['last_name'] + ':', text) if 512 in summands: # , - index = 1 photos = [] # id docs = [] # id media_type = 'attach1_type' while media_type in element[6].keys(): # , - media_type = element[6]['attach{}_type'.format(index)] # , if media_type == 'photo': # photos.append(element[6]['attach{}'.format(index)]) # id elif media_type == 'doc': # docs.append(element[6]['attach{}'.format(index)]) # id index += 1 # media_type = 'attach{}_type'.format(index) change = lambda ids, type_: requests.get('https://api.vk.com/method/{}.getById'.format(type_), params={type_: ids, 'access_token': token}).json() # , if photos: # , photos = change(', '.join(photos), 'photos') # , photos if 'response' in photos.keys(): photos = [attachment['src_xbig'] for attachment in photos['response']] # print(' :', ', '.join(photos)) else: pass # , if docs: # , docs = change(', '.join(docs), 'docs') # , docs if 'response' in docs.keys(): docs = [attachment['url'] for attachment in docs['response']] # print(' :', ', '.join(docs)) else: pass # , else: source_act = element[6] if source_act['source_act'] == 'chat_title_update': # changer_id = source_act['from'] # id , source_text = source_act['source_text'] # source_old_text = source_act['source_old_text'] # changer = requests.get('https://api.vk.com/method/users.get', params={'user_ids': changer_id, 'fields': 'sex'}).json()['response'][0] # , if changer['sex']: verb = '' else: verb = '' print(changer['first_name'], changer['last_name'], verb, ' "{}" "{}"'.format(source_old_text, source_text)) elif source_act['source_act'] == 'chat_photo_update': chat_id = element[3] - 2000000000 # id chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title'] # user_id = source_act['from'] # id , photo_id = source_act['attach1'] # id photo = requests.get('https://api.vk.com/method/photos.getById', params={'photos': photo_id, 'access_token': token}).json() # user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': user_id, 'fields': 'sex'}).json()['response'][0] # , if 'error' not in photo.keys(): # if user['sex']: verb = '' else: verb = '' print(user['first_name'], user['last_name'], verb, ' "{}" '.format(chat), photo['response'][0]['src_xbig']) else: pass # , elif source_act['source_act'] == 'chat_invite_user': chat_id = element[3] - 2000000000 # id chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title'] # invited_id = source_act['source_mid'] # id inviter_id = source_act['from'] # id if invited_id == inviter_id: # - user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': inviter_id, 'fields': 'sex'}).json()['response'][0] # if user['sex']: verb = '' else: verb = '' print(user['first_name'], user['last_name'], verb, ' "{}"'.format(chat)) else: inviter_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': inviter_id, 'fields': 'sex'}).json()['response'][0] # invited_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': invited_id, 'name_case': 'acc'}).json()['response'][0] # if inviter_user['sex']: verb = '' else: verb = '' print(inviter_user['first_name'], inviter_user['last_name'], verb, ' "{}"'.format(chat), invited_user['first_name'], invited_user['last_name']) elif source_act['source_act'] == 'chat_kick_user': chat_id = element[3] - 2000000000 # id chat = requests.get('https://api.vk.com/method/messages.getChat', params={'chat_id': chat_id, 'access_token': token}).json()['response']['title'] # removed_id = source_act['source_mid'] # id remover_id = source_act['from'] # id if removed_id == remover_id: # user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': remover_id, 'fields': 'sex'}).json()['response'][0] # if user['sex']: verb = '' else: verb = '' print(user['first_name'], user['last_name'], verb, ' "{}"'.format(chat)) else: remover_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': remover_id, 'fields': 'sex'}).json()['response'][0] # removed_user = requests.get('https://api.vk.com/method/users.get', params={'user_ids': removed_id, 'name_case': 'acc'}).json()['response'][0] # if remover_user['sex']: verb = '' else: verb = '' print(remover_user['first_name'], remover_user['last_name'], verb, ' "{}"'.format(chat), removed_user['first_name'], removed_user['last_name']) elif source_act['source_act'] == 'chat_create': chat = source_act['source_text'] # creator_id = source_act['from'] # id creator = requests.get('https://api.vk.com/method/users.get', params={'user_ids': creator_id, 'fields': 'sex'}).json()['response'][0] # , if creator['sex']: verb = '' else: verb = '' print(creator['first_name'], creator['last_name'], verb, ' "{}"'.format(chat)) data['ts'] = response['ts'] #

Long Poll-a, , , .
, , - . !

:

Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/335106/

:  

: [1] []
 

:
: 

: ( )

:

  URL