Alexa Flask Ask Yes / No response handling - python

I am trying to create a simple Alexa skill using Flask Ask in python.
I have an intent called "SearchIntent" with a "searchterm" slot and the python code looks something like this:
#ask.intent("SearchIntent")
def SearchIntent(searchterm):
resList = []
searchterm = searchterm.lower()
for item in somelist:
if item.find(searchterm) != -1:
resList.append(item)
return question("I Found " + str(len(resList)) + ", Do you want me to list them all?")
I want to check if the response from the user, if he says "Yes" than read all the results:
return statement('\n'.join(resList))
and if the user says no, to perform some other action
something like:
...
return question("I Found " + str(len(resList)) + ", Do you want me to list them all?")
if "return question" == "yes":
do something
else:
do something else
I don't want to create the search function again in a YesIntent, Is it possible to do something like this within the same function?

This is not possible in the suggested way using flask ask. After you call return, you leave your SearchIntent() function and have no way to check the answer or run additional code.
However, you can still make it work: after the user answers your question a new intent is sent and flask-ask calls the according function. By using session attributes, as suggested by #user3872094, you can process your searchterm in this new function. Session attributes are used to preserve user input during a session between different intent requests.
Check this minimal example:
#ask.intent("SearchIntent")
def SearchIntent(searchterm):
session.attributes['term'] = searchterm
return question("I understood {}. Is that correct?".format(searchterm))
#ask.intent('AMAZON.YesIntent')
def yes_intent():
term = session.attributes['term']
return statement("Ok. So your word really was {}.".format(term))
#ask.intent('AMAZON.NoIntent')
def no_intent():
return statement("I am sorry I got it wrong.")
Add the Amazon Yes and No intents to your intent_schema:
{
"intents": [
{
"intent": "SearchIntent",
"slots": [{
"name": "searchterm",
"type": "AMAZON.LITERAL"
}]
},{
"intent": "AMAZON.NoIntent"
}, {
"intent": "AMAZON.YesIntent"
}
]
}

Related

How to find on Daml-dazl app a transaction by key?

For example in a smart contract like this:
daml 1.2
module Example where
template Account with
owner : Party
number : Text
money : Int
where
signatory owner
key (owner, number) : (Party, Text)
maintainer key._1
It is possible to query a transaction based on a specific value of the template
import dazl
network = dazl.Network()
def main():
with dazl.simple_client('http://localhost:6865', 'Alice') as client:
# wait for the ACS to be fully read
client.ready()
allContracts = client.find(template = "Example.Account")
for contract in allContracts:
if contract.cdata ["money"] == 10000:
print("The query is" )
print(contract.cdata)
if __name__ == '__main__':
main()
However, how is possible to query based on key?
The only way to do this at the moment is to query on exactly the same condition you have in your key (which unfortunately duplicates code with the model):
all_contracts = clients.find("Example.Account", {"owner": "blah", "number": "blah"})
if all_contracts:
# something exists
...
else:
# nothing found
...
I added an issue to capture this feature request going forward: https://github.com/digital-asset/dazl-client/issues/85

How to pass a url in a dictionary to the function in python

I'm trying to call a function by passing a url to it but I can't quite figure how it can be done for my use case.
On the last line in the code below, there is what I would like to do. I know it's terrible to enter dictionary key in a function like that, but I don't know how to properly pass the def key of the urls dictionary to the get_page() function. Thanks for your guidance.
This is my code:
...
urls = {
"abc": abc_url,
"def": def_url,
}
if site in urls:
print("site: " + site, "url: " + urls[site])
products = get_index_data(get_page(urls[site]))
for link in products:
time.sleep(15)
data = get_detail_data(get_page(link))
print(data)
write_csv(data, link)
def get_page(urls[site]):
...code continues...
First of all
As python is an interpreted language (which reads code line by line and does not compile); hence function implementation should be before the function call.
Now coming to your question, when calling get_page(urls[site])) it passes the value from dictionary.
So your function should have a parameter like def get_page(website_url):
To summarise -
...
urls = {
"abc": abc_url,
"def": def_url,
}
def get_page(website_url):
...function code...
if site in urls:
print("site: " + site, "url: " + urls[site])
products = get_index_data(get_page(urls[site]))
for link in products:
time.sleep(15)
data = get_detail_data(get_page(link))
print(data)
write_csv(data, link)
...code continues...
Note: You can get both keys, values from a dictionary like
if website_name, website_url in urls.items():

Python: Cannot read returned values from functions

I am working on an Fall Detection System. I wrote the Arduino Code and connected to Firebase. So now I have two variables that get 1 or 0 status, and I created a mobile application to receive an automatic push notification whenever the system detects a fall through Firebase+Pusher. I wrote this Python code with PyCharm and I used the stream function to read live data from Firebase and send automatic notifications. The code was working for the variable "Fall_Detection_Status" and I was able to receive push notifications normally with every fall detection. But I tried to modify the code to read data from another variable "Fall_Detection_Status1" and I want my code now to send the notification if both variables are giving 1's. I came up with this code but it seems that the last if statement is not working because I am not able to receive notifications and also print(response['publishId']) at the end of the if statement is not showing any result.
So what is wrong?
import pyrebase
from pusher_push_notifications import PushNotifications
config = {
'apiKey': "***********************************",
'authDomain': "arfduinopushnotification.firebaseapp.com",
'databaseURL': "https://arduinopushnotification.firebaseio.com",
'projectId': "arduinopushnotification",
'storageBucket': "arduinopushnotification.appspot.com",
'messagingSenderId': "************"
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()
pn_client = PushNotifications(
instance_id='*****************************',
secret_key='**************************',
)
value = 0
value1 = 0
def stream_handler(message):
global value
print(message)
if message['data'] is 1:
value = message['data']
return value
def stream_handler1(message):
global value1
print(message)
if message['data'] is 1:
value1 = message['data']
return value1
if value == 1 & value1 == 1:
response = pn_client.publish(
interests=['hello'],
publish_body={
'apns': {
'aps': {
'alert': 'Hello!',
},
},
'fcm': {
'notification': {
'title': 'Notification',
'body': 'Fall Detected !!',
},
},
},
)
print(response['publishId'])
my_stream = db.child("Fall_Detection_Status").stream(stream_handler)
my_stream1 = db.child("Fall_Detection_Status1").stream(stream_handler1)
You are using the wrong operator '&' to combine the results of the two tests. In Python, '&' is the bitwise and operator! I believe you want the logical version which is 'and'.
Secondly, assuming the stream_handler/1 calls are run by your last two statements, those two statements are AFTER the place where you test the values in the if statement. Move those line above the if block.

How can I update a MongoDB document with python?

what I'm trying to do is to update a MongoDB document with python and discord.py, but the code i've put doesn't work.
elif string2 == "add":
if string3 == "administrator":
cur = coll.find({"_id" : string1.id})
for doc in cur:
if doc["perm"] == "administrator":
await self.bot.say("Permission {} already found on db for user {}".format(string3, string1.name))
else:
db.users.update_one({"_id" : string1.id, "name" : string1.name, "perm" : "administrator"}, upsert=False)
await self.bot.say("Permissions updated on db for user {}".format(string1.name))
The following is the error.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: update_one() missing 1 required positional argument: 'update'
Document from users collection:
_id: "191598787410526208"
name: "Stevyb0t"
perm: "administrator"
Essentially what other people have commented but with some formatting to make it more legible:
db.users.update_one(
{"_id": string1.id},
{"$set":
{"name": string1.name,
"perm": "administrator"
}})
I also removed upsert=False since that's the default value anyway so you don't need to specify it - though of course being explicit can be helpful
Edit: read all the comments, suggestion was already made to make accepted comment an answer so here it is. My answer is no different from that comment
If your id is a string, you may need to convert it to an ObjectId. Also, you can print the result of the update, and check success:
from bson import ObjectId
result = db.users.update_one(
{"_id": ObjectId(string1.id)},
{"$set":
{"name": string1.name,
"perm": "administrator"}
})
logger.debug('update result: {}'.format(result.raw_result))
if result.matched_count > 0:
# Success code goes here
pass
else:
# Failure code goes here
pass

Fetching data interactively from TinyDB

I'm trying to figure out how to use the data a user enters as input to get information from a TinyDB DB.
My DB looks something like this:
{"_default": {"1": {"switch": "n9k-c9372px", "names": ["nexus 9372px", "nexus 9372-px", "nexus9372px", "n9372px", "n9k-c9372px"], "fex_comp": ["2224tp", "2232pp"]}, "2": {"switch": "n9k-c9396px", "names": ["nexus 9396px", "nexus 9396-px", "nexus9396px", "n9396px", "n9k-c9396px"], "fex_comp": ["2232tm-e", "2248tp"]}}}
Basically, the DB is the result of two dictionaries with lists, like these:
{"switch": "switch1", "names": ["name1", "name2", "name3"], "fex_comp":["fex1", "fex2", "fex3"]
My idea is the following:
To have a prompt asking for a switch model (q= input("Tell me the
model")).
Take the input (q) from the user, and check if it matches
any of the "names" in the database.
If it does, then print the fex_comp list, the whole list. Otherwise, print a different message.
I understand how to form the if, else, statements and also how to use for loops, but I haven't managed to figure out how to do what I describe above.
Any help is much appreciated!
Edvard
Like so then?
from tinydb import TinyDB, Query
ql = ['nexus9372px','nexus9396px', 'not_there']
def mkdb():
db = TinyDB('db.json')
db.purge()
db.insert({'switch': 'n9k-c9372px',
'names': ['nexus 9372px',
'nexus 9372-px',
'nexus9372px', 'n9372px'],
'fex_comp': ['2224tp', '2232pp',
'2232tm', '2232tm-e']})
db.insert({"switch": "n9k-c9396px",
"names": ["nexus 9396px", "nexus 9396-px",
"nexus9396px", "n9396px",
"n9k-c9396px"],
"fex_comp": ["2232tm-e", "2248tp"]})
return(db)
def get_name():
return(input('Name? '))
def search(name, db):
Name = Query()
res = db.search(Name.names.any(name))
if res:
#print(res)
print('fex_comp for {}: {}'.format(name, res[0]['fex_comp']))
else:
print('{} not found'.format(name))
db = mkdb()
name = get_name()
search(name, db)

Categories