-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
76 lines (60 loc) · 2.55 KB
/
app.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
from chalice import Chalice, BadRequestError
import asyncio
from src.services import receive_and_respond_message, webhook_verify
app = Chalice(app_name='whats-bot-api')
# @app.route('/login', methods=['POST'])
# def login():
# request = app.current_request.json_body
# user_phone_id = request.get('user_phone_id')
# password = request.get('password')
# result = asyncio.run(validate_user(user_phone_id, password))
# if result:
# return {'message': 'Login successful'}
# else:
# raise BadRequestError("Invalid credentials")
@app.route('/message', methods=['POST', 'GET'])
def message_handler():
if app.current_request.method == 'GET':
query_params = app.current_request.query_params
hub_verify_token = query_params.get('hub_verify_token')
hub_mode = query_params.get('hub_mode')
hub_challenge = query_params.get('hub_challenge')
return webhook_verify(
hub_verify_token = hub_verify_token,
hub_mode = hub_mode,
hub_challenge = hub_challenge
)
if app.current_request.method == 'POST':
body = app.current_request.json_body
client_message = body \
.get('entry', [{}])[0] \
.get('changes', [{}])[0] \
.get('value', {}) \
.get('messages', [{}])[0] \
.get('text', {}) \
.get('body')
if not client_message:
raise BadRequestError("Did not receive a client_message from Whatsapp API")
client_phone_number = body \
.get('entry', [{}])[0] \
.get('changes', [{}])[0] \
.get('value', {}) \
.get('contacts', [{}])[0] \
.get('wa_id')
if not client_phone_number:
raise BadRequestError("Did not receive a client_phone_number from Whatsapp API")
user_phone_id = body \
.get('entry', [{}])[0] \
.get('changes', [{}])[0] \
.get('value', {}) \
.get('metadata', {}) \
.get('phone_number_id')
if not user_phone_id:
raise BadRequestError("Did not receive a user_phone_id from Whatsapp API")
asyncio.run(
receive_and_respond_message(
user_phone_id = user_phone_id,
client_phone_number = client_phone_number,
client_message = client_message
)
)