-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
76 lines (61 loc) · 2.11 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
import os
import json
import requests
from flask import Flask, request
from langchainBot import ask
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
# Access token for your app
# (copy token from DevX getting started page
# and save it as an environment variable)
token = os.getenv("WHATSAPP_TOKEN")
@app.route("/", methods=["GET"])
def index():
return "Webhook is listening"
@app.route("/webhook", methods=["POST"])
def webhook():
# Parse the request body from the POST
body = request.get_json()
# Check the Incoming webhook message
print(json.dumps(body, indent=2))
if body.get("object"):
if (body.get("entry") and body["entry"][0].get("changes")
and body["entry"][0]["changes"][0].get("value")
and body["entry"][0]["changes"][0]["value"].get("messages")
and body["entry"][0]["changes"][0]["value"]["messages"][0]):
phone_number_id = body["entry"][0]["changes"][0]["value"]["metadata"][
"phone_number_id"]
from_number = body["entry"][0]["changes"][0]["value"]["messages"][0][
"from"]
msg_body = body["entry"][0]["changes"][0]["value"]["messages"][0][
"text"]["body"]
respuesta = ask(msg_body)
payload = {
"messaging_product": "whatsapp",
"to": from_number,
"text": {
"body": respuesta
}
}
print(payload)
print(token)
print(phone_number_id)
url = f"https://graph.facebook.com/v17.0/184262751430193/messages?access_token={token}"
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response)
return "OK", 200
@app.route('/webhook', methods=['GET'])
def verificar_token():
try:
verifyToken = request.args.get('hub.verify_token')
challenge = request.args.get('hub.challenge')
if verifyToken == os.getenv("VERIFY_TOKEN") and challenge != None:
return challenge
else:
return f'token incorrecto {os.getenv("VERIFY_TOKEN")}', 403
except Exception as e:
return e, 403
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)