-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
main.py
109 lines (82 loc) · 3.1 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
106
107
108
109
# Copyright 2018 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START functions_slack_setup]
import os
from flask import jsonify
import functions_framework
import googleapiclient.discovery
from slack.signature import SignatureVerifier
kgsearch = googleapiclient.discovery.build(
"kgsearch", "v1", developerKey=os.environ["KG_API_KEY"], cache_discovery=False
)
# [END functions_slack_setup]
# [START functions_verify_webhook]
def verify_signature(request):
request.get_data() # Decodes received requests into request.data
verifier = SignatureVerifier(os.environ["SLACK_SECRET"])
if not verifier.is_valid_request(request.data, request.headers):
raise ValueError("Invalid request/credentials.")
# [END functions_verify_webhook]
# [START functions_slack_format]
def format_slack_message(query, response):
entity = None
if (
response
and response.get("itemListElement") is not None
and len(response["itemListElement"]) > 0
):
entity = response["itemListElement"][0]["result"]
message = {
"response_type": "in_channel",
"text": f"Query: {query}",
"attachments": [],
}
attachment = {}
if entity:
name = entity.get("name", "")
description = entity.get("description", "")
detailed_desc = entity.get("detailedDescription", {})
url = detailed_desc.get("url")
article = detailed_desc.get("articleBody")
image_url = entity.get("image", {}).get("contentUrl")
attachment["color"] = "#3367d6"
if name and description:
attachment["title"] = "{}: {}".format(entity["name"], entity["description"])
elif name:
attachment["title"] = name
if url:
attachment["title_link"] = url
if article:
attachment["text"] = article
if image_url:
attachment["image_url"] = image_url
else:
attachment["text"] = "No results match your query."
message["attachments"].append(attachment)
return message
# [END functions_slack_format]
# [START functions_slack_request]
def make_search_request(query):
req = kgsearch.entities().search(query=query, limit=1)
res = req.execute()
return format_slack_message(query, res)
# [END functions_slack_request]
# [START functions_slack_search]
@functions_framework.http
def kg_search(request):
if request.method != "POST":
return "Only POST requests are accepted", 405
verify_signature(request)
kg_search_response = make_search_request(request.form["text"])
return jsonify(kg_search_response)
# [END functions_slack_search]