-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudFunctionsP2.py
64 lines (53 loc) · 2.44 KB
/
CloudFunctionsP2.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
#####################################################################
# #
# SkillsFuture IBM Cloud Function Example 2 #
# This example is used to show how to get data from Discovery #
# and return it to Watson Assistant. #
# #
# input JSON: { "text": "What is Barn Town?"} #
# #
# WL IBM - 17 July 2019 #
# #
#####################################################################
import os
import sys
try:
from ibm_cloud import DiscoveryV1
except ImportError:
from watson_developer_cloud import DiscoveryV1
def MakeReturnMessage(results):
messageback = "Here are some answers from search:<br>\n"
counter = 0
for aresult in results:
counter = counter + 1
messageback = messageback + "<b>" + str(counter) + "</b> " + aresult["text"] + "<br>\n"
return messageback
def main(dict):
#create defaults for our variable
text = ""
#first, lets deconstruct the input variable
if "text" in dict:
text = dict["text"]
#then create the discovery object, please choose the right version.
discovery = ""
if 'username' in dict:
discovery = DiscoveryV1(version=dict['version'], url=dict['url'],
username=dict['username'], password=dict['password'])
elif 'iam_apikey' in os.environ:
discovery = DiscoveryV1(version=dict['version'], url=dict['url'],
iam_apikey=dict['iam_apikey'] )
else:
return { 'text': 'Error: Disc. Creds not specified!' }
#query discovery
get_disc = discovery.query(dict['envid'], dict['colid'], natural_language_query=text, count=3)
#get results
get_results = get_disc.get_result()['results']
#make the output message
messageback = ""
if len(get_results) > 0:
messageback = MakeReturnMessage(get_results)
else:
messageback = "I am sorry, there are no results from search. Please try another question"
#craft the output
result = {"text":messageback}
return result