How to make a tree like based structured conversational action on google? - dialogflow-es

I want to make an action which ask user a question and answers in yes or no. The answers affect the future of player and gets different questions according to the user answers. And also I want to store the state so that user may resume afterwards. I think a binary tree like structure will work but how implement this in dialogflow.

There are two primary ways to do this.
The first way is to use contexts, which can be dynamically configured to limit the types of intents that can be triggered. This would allow you to develop a tree-like structure in a very precise way. However, this method would be more difficult to manage as you scale.
The alternative is to store data like questions answered and difficulty in session data and have a single Dialogflow intent that is able to capture the user's answer, give them a pass/fail, and provide the next question.
app.intent('My Question', (conv, {answer}) => {
const {currentQuestion} = conv.data
if (currentQuestion.answer === answer) {
conv.ask('Correct!')
conv.data.difficulty++
} else {
conv.ask('Wrong!')
conv.data.difficulty--
}
const nextQuestion = customShuffle(conv.data.allQuestions, conv.data.difficulty)
conv.data.allQuestions[nextQuestion.id] = undefined
conv.ask('Next question! ' + nextQuestion.question)
})

Related

How to handle replies in with Pyrogram when using ForceReply?

I am building a telegram bot where I am attempting to get the user to fill in detail about an event and store them in a dictionary which is itself in a list.
However I want it be link a conversation. I want it to look like:
user: /create
bot-reply: What would you like to call it?
user-reply: Chris' birth day
bot-reply: When is it?
user-reply: 08/11/2021
bot-reply: Event Chris birth day on 08/11/2021 has been saved!
To achieve this I plan to use ForceReply which states in the documentation
This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
The problem is the documentation does not seem to explain how to handle responses.
Currently my code looks like this:
#app.on_message(filters.command('create'))
async def create_countdown(client, message):
global countdowns
countdown = {
'countdown_id': str(uuid4())[:8],
'countdown_owner_id': message.from_user.id,
'countdown_onwner_username': message.from_user.username,
}
try:
await message.reply('What do you want to name the countdown?',
reply_markup=ForceReply()
)
except FloodWait as e:
await asyncio.sleep(e.x)
Looking through the form I have found options like this:
python telegram bot ForceReply callback
which are exactly what I am looking for but they are using different libraries like python-telegram-bot which permit them to use ConversationHandler. It seems to not be part of pyrogram
How to I create user-friendly step-by-step interfaces with pyrogram?
Pyrogram doesn't have a ConversationHandler.
You could use a dict with your users' ID as the key and the state they're in as the value, then you can use that dictionary of states as your reference to know where your User is in the conversation.
Dan: (Pyrogram creator)
A conversation-like feature is not available yet in the lib. One way to do that is saving states into a dictionary using user IDs as keys. Check the dictionary before taking actions so that you know in which step your users are and update it once they successfully go past one action
https://t.me/pyrogramchat/213488

Return to the last active context on an questionnaire Bot on Dialogflow

I built a questionnaire bot on DialogFlow and I force a sequence using contexts. My output is the next intent and the input to set the current context.
The thing is that as it has several Yes and No questions I had to set lifespan as 1 to many of them. So the bot won't get confused. The side effect of this is when it goes to the fallback intent for any reason, no matter how many tries it gives, it won't understand what the user says as there is no active contexts anymore.
I'm already using fulfillment to set some conditional flows based in specific answers and to record and read data in Firebase.
Is there a way to retrieve the last active context so I can force the last context until having a valid input?
This bot will be running in Google Assistant interface.
tks!
There is no such thing as "last active context", since multiple Contexts may be active at once.
It sounds like, rather than having Contexts with a lifespan of 1, you want your Contexts to have a longer lifespan (in case they trigger an Intent that doesn't answer the question) so they can return to the path you want to ask them about.
To address the issue of multiple Intents that accept "yes" or "no", but are only valid in a particular Context, you can make a context inactive by setting its lifespan to 0 as part of an Outgoing Context or in the fulfillment for the Yes/No Intent that handles that Context.
As Prisoner mentioned there is not "Last active context" feature within action on google, but if you work with 1 lifespan context there is a trick that you can use to see which contexts were from the previous intents.
If you work with context lifespans of 1, you can look into your context collection and look for any context which has a lifespan of undefined. These are output contexts set by your previous intent. In the below example I cycle through my contexts, take their name by looking for a common identiefier "_" and use the name to reset the expired context back to 1 using their previous parameters.
const contextIdentifier = "_"
const contextLifeSpan = 1;
Object.values(conv.contexts.input).filter(c => !c.lifespan).forEach((context) => {
const start = context.name.lastIndexOf(contextIdentifier);
const end = context.name.length;
const contextName = context.name.slice(start, end);
conv.contexts.set(contextName, contextLifeSpan, context.parameters);
});
return conv;

Clear session or session variables on Bixby

Is there a way to specify that a session should be ended, or to clear out the memory of previous actions? In my testing (simulator only) I'm seeing a couple cases where Bixby is remembering a previous entry that isn't relevant anymore.
Example utterances
remove wet diaper
wet diaper
In this case there's 2 possible enums that can be said. "actionType" that is optional, in this case "remove" and "statType", in this case "wet diaper".
What is happening is on the second phrase it's caching the actionType. So, the second phrase my JavaScript still receives the "remove" even though it's not included.
I haven't tried this on an actual device (only the simulator) so it's possible this is just a simulation quirk.
This is kind of related to this question. There was a follow-up comment that the OP asked related to session management.
How does Bixby retain data from a previous NL input?
So, if you read that link. Is there a way I can signal to bixby that the conversation is over, or at least to not remember previous entries for the action?
One way would be to use the transient feature. Here is more information
For example, alter your input type so it doesn't carry over across executions.
name (ActionType) {
features {
transient
}
}
make sure all input types are NL friendly. name/enum concepts are meant for NL and you can attach vocabulary to them.
I used to have a similar issue like yours, in my case, my problem was related to the type of the 'requires' property inside the input-group declared in my action.model.bxb.
You need to handle by separate this two input cases in diferent action.model.bxb files:
In one of them you might have something like (model 1):
input-group(removeWeaper){
requires (OneOrMoreOf)
collect{
input (ActionType) {
type (Type)
min (Optional)
}
input (StatType) {
type (Type)
min (Optional)
}
}
Here, Bixby Will know that at least one of these properties will be apear in your input and will be waiting for an input with that structure.
In the other file you might have (model 2):
input-group(Weaper){
requires (OneOf)
collect{
input (StatType) {
type (Type)
min (Optional)
}
}
Here, Bixby will be waiting to catch an input that contains only one of the indicated values in you input.
(model 1) This could be ok only if you run 'wet diaper' by first time, also when you try again and run 'remove wet diaper' it might work, the problem is when you run again 'wet diaper' because Bixby Stores you previous approach including "remove". i'm not sure if there is something to clear the stored values, but, here is when (model 2) will help you to catch only the input 'wet diaper' as a different statement.
I share you this work around as my own experience, and i hope this could help you solving or getting another perspective of how you could handle or solve your problem.

cakePHP and authorization for CRUD operations

I have a cakephp 1.3 application and I have run into a 'data leak' security hole. I am looking for the best solution using cake and not just something that will work. The application is a grade tracking system that lets teachers enter grades and students can retrieve their grades. Everything is working as expected but when I started to audit security I found that the basic CRUD operations have leaks. Meaning that student X can see student Y's grades. Students should only see their own grades. I will limit this questions to the read operation.
Using cake, I have a grade_controller.php file with this view function:
function view($id = null) {
// Extra, not related code removed
$this->set('grade', $this->grade->read(null, $id));
}
And
http://localhost/grade/view/5
Shows the grade for student $id=5. That's great. But if student #5 manipulates the URL and changes it to a 6, person #6's grades are shown. The classic data leak security hole.
I had two thoughts on the best way to resolve this. 1) I can add checks to every CRUD operations called in the controller. Or 2) add code to the model (for example using beforeFind()) to check if person X has access to that data element.
Option #1 seems like it is time consuming and error prone.
Option #2 seem like the best way to go. But, it required calling find() before some operations. The read() example above never executes beforeFind() and there is no beforeRead() callback.
Suggestions?
Instead of having a generic read() in your controller, you should move ALL finds, queries..etc into the respective model.
Then, go through each model and add any type of security checks you need on any finds that need to be restricted. 1) it will be much more DRY coding, and 2) you'll better be able to manage security risks like this since you know where all your queries are held.
For your example, I would create a getGrade($id) method in my Grade model and check the student_id field (or whatever) against your Auth user id CakeSession::read("Auth.User.id");
You could also build some generic method(s) similar to is_owner() to re-use the same logic throughout multiple methods.
If CakePHP supports isAuthorized, here's something you could do:
Create a column, that has the types of users (eg. 'student', 'teacher', ...)
Now, it the type of User is 'student', you can limit their access, to view only their data. An example of isAuthorized is as follows. I am allowing the student to edit only their profile information. You can extend the concept.
if ((($role['User']['role'] & $this->user_type['student']) == $this->user_type['student']) {
if (in_array($this->action, array('view')) == true) {
$id = $this->params->pass[0];
if ($id == $user_id) {
return (true);
}
}
}
}

How do I setup my POCO's with Subsonic 3 and the SimpleRepostitory? or where is the convention?

Is there someplace that details how to setup your POCO's when using the SimpleRepository with SubSonic 3? It sounds like it's convention over configuration, but I can't find where that convention is explained.
http://www.subsonicproject.com/docs/Conventions looks like it was meant for 2.0, and is also marked incomplete. (BTW: I'd love to help reorganize the docs into more a 2.0 and 3.0 as the current docs are a bit confusing on which version they are referring to.)
For instance I'd like to know how I'd go about setting up a
one-to-one relationship
User <=> Profile
class User {
Id
ProfileId instead of Profile? or is Profile profile possible?
}
class Profile {
Id
UserId instead of User? or is User user possible?
}
One-to-many relationship
class User {
Id
IList<Post> Posts (?) or IList<int> PostIds (?) or is this implied somehow? or is this just wrong?
}
class Post {
Id
UserId instead of User? or is User user possible?
}
Many-to-many
I'm guessing I'd need to setup a many to many table?
class User {
IList<Blog> Blogs (?) or IList<int> BlogIds (?) or is this implied somehow?
}
class BlogsUsers { // Do I have to create this class?
UserId
BlogId
}
class User {
IList<User> Users (?) or IList<int> UserIds (?) or is this implied somehow?
}
In the example solution it doesn't seem like these are set so I'm wondering how you'd go about doing a (my guess proceeds example):
one-to-one
User.Profile
r.Single<Profile>(p=>p.User == userId);
parent on one-to-many
Post.User
id = r.Single<Post>(postId).UserId;
r.Single<User>(id); // which kind of stinks with two queries, JOIN?
children on one-to-many
User.Posts
r.Find<Post>(p=>p.UserId == userId)
or many-to-many
User.Blogs
ids = r.Find<BlogsUsers>(bu=>bu.UserId == userId);
r.Find<Blog>(b=>b.BlogId == ids); // again with the two queries? :)
Blog.Users
ids = r.Find<BlogsUsers>(bu=>bu.BlogId == blogId);
r.Find<User>(u=>u.UserId == ids); // again with the two queries? :)
I would assume that there's got to be a way to not have the two queries and for these properties to already be autogenerated in some way. Truth be told though I did only have an hour to play with everything last night so I am a little afraid of Rob yelling at me. I'm SORRY! :P
If these are not autogen'd then where are views and store procedures for 3.0? Please give me a link for those as well while you're at it fellow SO'er.
This is probably your best place to start:
http://subsonicproject.com/docs/Using_SimpleRepository
Relationships are setup in code, by you, and we don't carry those forward to the DB (yet - hopefully soon). Ideally you setup your model as you need to and when you're ready you go and manually "solidify" your relationships in the DB. This is to reduce friction during development - data integrity isn't really something to worry about when building a site.
That said, I know people want this feature - I just need to build it.

Resources