-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
105 lines (90 loc) · 2.63 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from flask import Flask
import ddg3
import os
import requests
app = Flask('app')
TOKEN = os.environ.get("TOKEN")
def search(text):
result = ddg3.query(text)
search_results = []
if result.abstract.text:
search_results.append(
{
"type": "TEXT",
"body": result.abstract.text,
"title": "Main Abstract",
"confidence": 1.0,
}
)
if result.results:
search_results.extend(
[
{
"type": "TEXT",
"body": "%s - %s" % (r.text, r.url),
"title": "Search Result %s" % (index,),
"confidence": ((len(result.results) - index) / 10),
}
for index, r in enumerate(result.results)
]
)
return search_results
@app.route('/')
def index():
return 'The Turn Webhook API endpoint is at /webhook'
@app.route('/webhook', methods=["POST"])
def webhook():
from flask import request
json = request.json
if "statuses" in json:
return ""
wa_id = json["contacts"][0]["wa_id"]
[message] = json["messages"]
if message["type"] != "text":
return ""
message_id = message["id"]
text = message["text"]["body"]
results = search(text)
if results:
response = requests.post(
url="https://whatsapp.turn.io/v1/messages",
headers={
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
},
json={
"to": wa_id,
"text": {
"body": "\n\n".join(
["*%(title)s*\n\n%(body)s" % result for result in results]
)
},
},
).json()
else:
response = requests.post(
url="https://whatsapp.turn.io/v1/messages",
headers={
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
},
json={
"to": wa_id,
"text": {
"body": "Apologies, DuckDuckGo did not return an abstract for %s" % (text,)
},
},
).json()
print(response)
response = requests.post(
url=f"https://whatsapp.turn.io/v1/messages/{message_id}/labels",
headers={
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/vnd.v1+json",
"Content-Type": "application/json",
},
json={"labels": ["question"]},
)
print(response)
return ""
app.run(host='0.0.0.0', port=8080)