· 6 years ago · Nov 10, 2019, 08:26 AM
1# -*- coding: utf-8 -*-
2import os
3from random import randint
4from requests import *
5import vk
6import random
7
8# Указываем ключи доступа, id группы и версию API
9VK_API_ACCESS_TOKEN = 'токен'
10VK_API_VERSION = '5.92'
11GROUP_ID = ид
12
13
14session = vk.Session(access_token = VK_API_ACCESS_TOKEN)
15api = vk.API(session, v = VK_API_VERSION)
16
17# Первый запрос к LongPoll: получаем server и key
18longPoll = api.groups.getLongPollServer(group_id = GROUP_ID)
19server, key, ts = longPoll['server'], longPoll['key'], longPoll['ts']
20
21while True:
22 # Последующие запросы: меняется только ts
23 longPoll = post('%s'%server, data = {'act': 'a_check',
24 'key': key,
25 'ts': ts,
26 'wait': 25}).json()
27 if longPoll['updates'] and len(longPoll['updates']) != 0:
28 for update in longPoll['updates']:
29 if update['type'] == "message_new":
30 print(update)
31 api.messages.markAsRead(peer_id = update['object']['from_id'])
32 name = api.users.get(user_ids = update['object']['from_id'])[0]['first_name']
33 a10 = "12.jpg", "13.jpg"
34 a9= random.choice(a10)
35 pfile = post(api.photos.getMessagesUploadServer(peer_id = update['object']['from_id'])['upload_url'], files = {'photo': open(a9, 'rb')}).json()
36 photo = api.photos.saveMessagesPhoto(server = pfile['server'], photo = pfile['photo'], hash = pfile['hash'])[0]
37 api.messages.send(user_id = update['object']['from_id'], random_id = randint(-2147483648, 2147483647), message = '%s, держи свою фоточку!:)'%name, attachment = 'photo%s_%s'%(photo['owner_id'], photo['id']))