-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
85 lines (66 loc) · 3.02 KB
/
main.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 ujson as json
from http import HTTPStatus
import aiohttp
import vk
from aiohttp import web
def find_audio_messages(obj):
doc_previews = map(
lambda att: att['doc']['preview'],
filter(lambda att: att['type'] == 'doc', obj.get('attachments', {}))
)
audio_msgs = map(
lambda doc: doc['audio_msg'],
filter(lambda doc: 'audio_msg' in doc, doc_previews)
)
urls = list(map(lambda audio: (audio['link_mp3'], audio['link_ogg']), audio_msgs))
if 'fwd_messages' in obj:
for msg in obj['fwd_messages']:
urls += find_audio_messages(msg)
return urls
async def process_message(request):
body = await request.json()
request_type = body['type']
if request_type == 'confirmation':
return web.Response(text=confirmation_key)
elif request_type != 'message_new':
return web.Response(text='ok')
else:
audio_messages = find_audio_messages(body['object'])
user_id = body['object']['user_id']
message_id = body['object']['id']
session = vk.Session()
api = vk.API(session, v='5.68')
if not audio_messages:
api.messages.send(access_token=access_token, user_id=user_id, message='Не вижу аудиосообщений 🙈')
return web.Response(text='ok')
async with aiohttp.ClientSession() as session:
messages = []
api.messages.send(access_token=access_token,
user_id=user_id,
message='Обрабатываю сообщение, это может занять некоторое время...💤')
for (mp3, ogg) in audio_messages:
async with session.post(server_host, json={'url': mp3, 'user_id': str(user_id)}) as response:
response_text = await response.text()
if response.status != HTTPStatus.OK:
api.messages.send(access_token=access_token,
user_id=user_id,
message='Ошибка при анализировании сообщения 🙊\nПопробуйте позже!',
forward_messages=[message_id])
return web.Response(text='ok')
else:
messages.append(response_text)
api.messages.send(access_token=access_token,
user_id=user_id,
message='\n'.join(messages),
forward_messages=[message_id])
return web.Response(text='ok')
with open('config/config.json', 'r') as f:
config = json.load(f)
app_host = config['app_host']
app_port = config['app_port']
server_host = config['server_host']
confirmation_key = config['confirmation_key']
access_token = config['access_token']
app = web.Application()
app.router.add_post('/', process_message)
web.run_app(app, host=app_host, port=app_port)