Password validation in DialogFlow - dialogflow-es

Password validation in dialogflow
Hi
I want to make this job, but i cant uderstand how.
What i need
After welcome massage DF asks user a password.
User enters phrase
If it is = password then DF shows message1 and can get any phrases.
If it is not password then DF shows message2 and DF asks user a password again
Now I have a problem on step 4- when user enter phrase from other intents DF shows other response, not message2.
Please help.
I am tryed webhook
function StartWelcome (agent) {
// get the employee ID parameter from the request header received from Dialogflow
let password = agent.parameters.password;
if (password == 1) { agent.add(agent.request_.body.queryResult.fulfillmentText); } else { agent.add(`Неправильный пароль! Введите пароль вновь.`);
agent.parameters.password = '';
let intentMap = new Map();
intentMap.set('StartWelcome', StartWelcome);
agent.handleRequest(intentMap);
I tryed context.
But if user says phrase that is not password but matching to another phrase- DF type responce of matching phrase.

Related

When I make an e-mail intent in kotlin, the recipient mail is not added directly

binding.navView.setNavigationItemSelectedListener {
when(it.itemId){
R.id.requestWallpaper->{
val emailIntent=Intent().apply {
action=Intent.ACTION_SEND
data= Uri.parse("mailto:")
type="text/plain"
putExtra(Intent.EXTRA_EMAIL,"test#gmail.com")
putExtra(Intent.EXTRA_SUBJECT,"request wallpaper")
putExtra(Intent.EXTRA_TEXT,"request wallpaper")
}
if (emailIntent.resolveActivity(this!!.packageManager) !=null){
emailIntent.setPackage("com.google.android.gm")
startActivity(emailIntent)
}else{
Toast.makeText(this#MainActivity,"No app available to send email!!",Toast.LENGTH_SHORT).show()
}
}
When the navigation drawer opens, the user will want to make a wallpaper request and when he presses the imagebutton, I want him to send an e-mail to test#gmail.com via gmail for now, but test#gmail.com is not added directly to the "to" part of gmail.When I run it on the emulator, the email subject and e-mail text are added, but the recipient e-mail is not added, why?
You're so close here, the only thing that's missing is the Intent.EXTRA_EMAIL extra. That property is expecting an array of String values rather than a single String.
binding.navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.requestWallpaper -> {
val emailIntent = Intent().apply {
action = Intent.ACTION_SEND
data = Uri.parse("mailto:")
type = "text/plain"
putExtra(Intent.EXTRA_EMAIL, arrayOf("test#gmail.com"))
putExtra(Intent.EXTRA_SUBJECT, "request wallpaper")
putExtra(Intent.EXTRA_TEXT, "request wallpaper")
}
if (emailIntent.resolveActivity(this.packageManager) != null) {
emailIntent.setPackage("com.google.android.gm")
startActivity(emailIntent)
} else {
Toast.makeText(
this#MainActivity,
"No app available to send email!!",
Toast.LENGTH_SHORT
).show()
}
}
}
}
I don't know that you need the type="text/plain" property either, but it shouldn't hurt anything. Also, if you skip the setPackage step it'll allow the OS to ask which email app to use.

How do I get the userid of second mention in a command

So I'm trying to make a command where someone can do -kill #firstUser #secondUser. This will increase the first user's kills by 1 and add a role to the second user mentioned. I can access the the first user mentioned by doing const firstUser = message.mentions.users.first(); but I'm not sure how to do the same for the second user.
I've tried accessing the message.mentions.users collection and converting it to an array (and trying to access that) but I can't get it to work.
const firstUser = message.mentions.users.get(0);
const secondUser = message.mentions.users.get(1);
How do I get the user class from a message with multiple mentions?
And what I found was, it returns an object, not a mention, and as you can't send an object, it will return as an empty message error.
So to send a mention, you send:
// Getting the first and second users
const allMentioned = message.mentions.users.array()
// First User `[0]`
const firstUser = allMentioned[0];
// Second User `[1]`
const secondUser = allMentioned[1];
// And so on and so forth...
// Add `<#` to the begginning of the id and `>` to the end of it to make a mention.
const mentionSecondUser = "<#" + secondUser.id + ">";
// Sending a message using the fetched property
message.channel.send(`Hey ${mentionSecondUser}, or whatever.`);
Alternatively, you can try using the other fetched properties using the following format, received from getting the property, say secondUser:
User {
id: '<secondUser's id>',
username: '<secondUser's username>',
bot: <true if secondUser a bot>,
discriminator: '<secondUser's discriminator>',
avatar: '<secondUser's avatarId>',
lastMessageID: <secondUser's lastMessageId>,
lastMessageChannelID: <secondUser's lastMessageChannelId>,
flags: UserFlags { bitfield: 0 }
}
An example of this is in the picture showed above.
You can use:
message.mentions.users.array()[1]
To get the second user in a message. Appropriately, use [2] for the third, [3] for the fourth, and so on.

How to obtain virtual user id/details in gatling?

I am new to Gatling and Scala and I need your advice.
I would like to obtain load test for n-users. Each user have to send request for creating different accounts. This is obtained by sending json file with appropriate array of objects ('entries' in our case).
Each single user must send different login as our backend system is checking if username is unique. Somehow we have to be sure that gatling is sending different data for each virtual user and also for each entries as well.
We noticed that there us session element which represents virtual user's state. Problem is that code showed below will not work as Exec structure used with expression function does not send any request.
There is section that could work but I do not know how to determine third parameter to distinguish virtual user id. Please find below simple json file structure used for this test
{
"entries": [
{
"userName": "some user name",
"password": "some password"
}
}
and scala code with my comments
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class UserCreationTest extends Simulation {
val profilesNumber = 2
val virtualUsers = 2
val httpConf = http
.baseURL("some url")
.acceptHeader("application/json")
.basicAuth("username", "password")
// This method will multiply 'entries' section in JSON 'entriesNumber' times
def createJsonUserEntries(entriesNumber: Int, users: List[String], userId : Long): String = {
val header = """{"entries": ["""
val footer = """]}"""
val builder = StringBuilder.newBuilder
for (i <- 0 until entriesNumber) {
val userIndex = (userId.toInt - 1) * entriesNumber + i
val userName = users(userIndex).get
val apiString =
s"""{
"userName": "${userName}"
"password": "password"
}"""
builder.append(apiString)
if (i != entriesNumber) {
builder.append(",")
}
}
header + builder.toString() + footer
}
// We do have method for generating user names based on profilesNumber and virtualUsers variables
// but for sake of this example lets hardcode 4 (profilesNumber * virtualUsers) user names
val usersList = List("user-1", "user-2", "user-3", "user-4")
//This will throw exception as no request was send. According to documentation function block is used to debugging/editing session
val scn = scenario("Create WiFi User Profile")
.exec(session => {
http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, userslList, session.userId).toString
)
).asJSON
session})
// This exec block will send a request but I do not know how to determine third param that should be virtual user Id
// To run this section please comment previous whole scenario block
/*
val scn = scenario("")
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, ???).toString
)
).asJSON
)
*/
setUp(scn.inject(atOnceUsers(virtualUsers)).protocols(httpConf))
}
Can you help me on that please? Is there any other way to do that in gatling? Thank you very much in advance
so you are trying to have each user have a unique userId?
you could create a feeder that does this
var userIdFeeder = (1 to 999999).toStream.map(i => Map("userId" -> i)).toIterator
val scn = scenario("")
.feed(userIdFeeder)
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, "${userId}").toString
)
).asJSON
)

setting context with list of objects as prameters in dialogflow

I have a list of values each having another KEY value corresponding to it, when i present this list to user, user has to select a value and agent has to call an external api with selected value's KEY. how can i achieve this in dialogflow?
I tried to send the entire key value pair in the context and access it in the next intent but for some reason when i set a list(array) to context parameters dialogflow simply ignoring the fulfillment response.
What is happening here and is there any good way to achieve this? I am trying to develop a food ordering chatbot where the category of items in menu is presented and list items in that menu will fetched when user selects a category, this menu is not static thats why i am using api calls to get the dynamic menu.
function newOrder(agent)
{
var categories = []
var cat_parameters = {}
var catarray = []
const conv = agent.conv();
//conv.ask('sure, select a category to order');
agent.add('select a category to order');
return getAllCategories().then((result)=>{
for(let i=0; i< result.restuarantMenuList.length; i++)
{
try{
var name = result.restuarantMenuList[i].Name;
var catid = result.restuarantMenuList[i].Id;
categories.push(name)
//categories.name = catid
cat_parameters['id'] = catid;
cat_parameters['name'] = name
catarray.push(cat_parameters)
}catch(ex)
{
agent.add('trouble getting the list please try again later')
}
}
agent.context.set({
name: 'categorynames',
lifespan: 5,
parameters: catarray, // if i omit this line, the reponse is the fultillment response with categories names, if i keep this line the reponse is fetching from default static console one.
})
return agent.add('\n'+categories.toString())
})
function selectedCategory(agent)
{
//agent.add('category items should be fetched and displayed here');
var cat = agent.parameters.category
const categories = agent.context.get('categorynames')
const cat_ob = categories.parameters.cat_parameters
// use the key in the catarray with the parameter cat to call the external API
agent.add('you have selected '+ cat );
}
}
The primary issue is that the context parameters must be an object, it cannot be an array.
So when you save it, you can do something like
parameters: {
"cat_parameters": catarray
}
and when you deal with it when you get the reply, you can get the array back with
let catarray = categories.parameters.cat_parameters;
(There are some other syntax and scoping issues with your code, but this seems like it is the data availability issue you're having.)

how to stop bot to not move forward unless entity is resolves

var intent = args.intent;
var number = builder.EntityRecognizer.findEntity(intent.entities, 'builtin.numer');
when i use findentity it move forward if the answer is correct or not how can i use entity resolve on that which are not builtin entites
var location1 = builder.EntityRecognizer.findEntity(intent.entities, 'Location');
var time = builder.EntityRecognizer.resolveTime(intent.entities);
when i use resolve time it ask againand again unless entity is resolve;
var alarm = session.dialogData.alarm = {
number: number ? number.entity : null,
timestamp: time ? time.getTime() : null,
location1: location1? location1.entity :null
};
/* if (!number & !location1 time)
{} */
// Prompt for number
if (!alarm.number) {
builder.Prompts.text(session, 'how many people you are');
} else {
next();
}
},
function (session, results, next) {
var alarm = session.dialogData.alarm;
if (results.response) {
alarm.number = results.response;
}
I believe I've already answered this question on StackOverflow: "Botframework Prompt dialogs until user finishes".
You'll need to create a mini-dialog, that will have at least two waterfall steps. Your first step will take any args and check/set them as the potential value your chatbot is waiting for. It'll prompt the user to verify that these are the correct values. If no args were passed in, or the data was not valid, the user will be prompted to supply the value the chatbot is waiting for.
The second step will take the user's response to the first step and either set the value into a session data object (like session.userData or session.conversationData) or restart the dialog using session.replaceDialog() or session.beginDialog().
In your main dialog you'll modify the step where you employ your EntityRecognizers to include an if-statement that begins your mini-dialog. To trigger the if-statement, you could use the same design as shown in this GitHub example or in your code. This code might look like below:
var location1 = builder.EntityRecognizer.findEntity(intent.entities, 'Location');
session.userData.location1 = location1 ? location1.entity : null;
if(!session.userData.location1) {
session.beginDialog('<get-location-dialog>');
}

Resources