Closing a bot in AIML - aiml

I've been programming a bot that can make an appointment for a dental clinic as an example. If the human tries to make an appointment in a day when there is no hours left, the robot asks if he/she would like another day. If the human says something like 'No', I would like to close the bot so it seems like the human or the robot have hanged up.
Thank you in advance and if I haven't had explained me correctly ask anything you need.

//textLine is the human answer
if ((textLine == null) || (textLine.length() < 1))
textLine = MagicStrings.null_input;
if (textLine.equals("no")) {
System.exit(0);
} else {
String request = textLine;
if (MagicBooleans.trace_mode)
System.out.println("STATE=" + request + ":THAT=" + ((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" + chatSession.predicates.get("topic"));
String response = chatSession.multisentenceRespond(request);
while (response.contains("<"))
response = response.replace("<", "<");
while (response.contains(">"))
response = response.replace(">", ">");
}
System.out.println(response);
//response is the bot response
this is my code in java
if i send "no" the bot quit

Related

If statement to allow single and multiple if options

I have an If statement dependent on a choice made in a google form. Everything currently works as needed BUT, the question choice allows them to choose ALL OPTIONS THAT APPLY. If more than one option is chosen, the script fails.
How it currently works - person fills out form, script grabs info and inputs to a document, gives specified message based on choice from question (cif and message in script below), then emails the correct recipient (chosen in form). It works beautifully if cif is submitted with one choice.
What do I add/edit to the script to allow for multiple choices, and therefore multiple messages input to the document, without having to write an If state for each scenario?
// Global variables
var docTemplate = "1EoBcz0BK4R5hm-q5pR68xnQnR8DlR56XzjxRrgsu4uE"; // *** replace with your template ID ***
var docName = "You got a High 5";
function onFormSubmit(e) { // add an onsubmit trigger
// Values come from the spreadsheet form
var observer = e.values[1]
var teacher = e.values[2]
var email = e.values[2]
var period = e.values[4]
var time = e.values[3]
var cif = e.values[5]
var comments = e.values[6]
var message;
if (cif == 'READ - Variety of texts') {
message = 'read quote'
}
else if (cif == 'WRITE - Paper or electronic') {
message = 'write quote'
}
else if (cif == 'THINK - Actively engaged students') {
message = 'think quote'
}
else if (cif == 'TALK - Purposeful discussion') {
message = 'talk quote'
}
else if (cif == 'MOVE - Students moving through class') {
message = 'move quote'
}
else if (cif == 'CIF not observed') {
message = 'CIF not observed'
}
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+teacher)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,
copyBody.replaceText('keyobserver', observer);
copyBody.replaceText('keyperiod', period);
copyBody.replaceText('keytime', time);
copyBody.replaceText('keycif', cif);
copyBody.replaceText('keycomments', comments);
copyBody.replaceText('keymessage', message)
var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
copyBody.replaceText('keyTodaysDate', todaysDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "High 5 - it matters.";
var body = "You got a High 5! See attached PDF. " +
"Please do not reply to this email. You will be asked to supply a response thorugh a link within the attached PDF. " +
"'Do all the good you can. By all the means you can. In all the ways you can. In all the places you can. At all the times you can. To all the people you can. As long as you ever can. -John Wesley'";
MailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
Having multiple selected answer will return a comma separated values in form of string.
For example:
e.values[5] can have:
'READ - Variety of texts, WRITE - Paper or electronic, THINK - Actively engaged students, TALK - Purposeful discussion, MOVE - Students moving through class, CIF not observed'
in one single string and using == will not work since it has different content versus the string you are comparing to. This causes all of your if statements to fail because non of them matches the string. This leads to an undefined variable message which causes error on replaceText() function.
To fix the issue replace this line of code:
var message;
if (cif == 'READ - Variety of texts') {
message = 'read quote'
}
else if (cif == 'WRITE - Paper or electronic') {
message = 'write quote'
}
else if (cif == 'THINK - Actively engaged students') {
message = 'think quote'
}
else if (cif == 'TALK - Purposeful discussion') {
message = 'talk quote'
}
else if (cif == 'MOVE - Students moving through class') {
message = 'move quote'
}
else if (cif == 'CIF not observed') {
message = 'CIF not observed'
}
with:
var message = [];
if (cif.match('READ - Variety of texts')) {
message.push('read quote');
}
if (cif.match('WRITE - Paper or electronic')) {
message.push('write quote');
}
if (cif.match('THINK - Actively engaged students')) {
message.push('think quote');
}
if (cif.match('TALK - Purposeful discussion')) {
message.push('talk quote');
}
if (cif.match('MOVE - Students moving through class')) {
message.push('move quote');
}
if (cif.match('CIF not observed')) {
message.push('CIF not observed')
}
and in your
copyBody.replaceText('keymessage', message);
just add join function to make message a comma separated values when the content is more than 1:
copyBody.replaceText('keymessage', message.join(',');
Example Usage:
Multiple CIF:
var cif = 'READ - Variety of texts, WRITE - Paper or electronic, THINK - Actively engaged students, TALK - Purposeful discussion, MOVE - Students moving through class, CIF not observed';
Output:
Single CIF:
var cif = 'WRITE - Paper or electronic';
Output:
References
Array.join()
String.match()

Authorize.net Sandbox Accept page testing- always declined?

I’m attempting to test Accept Hosted payment page(redirect-method) with my sandbox. For this, I’m using the GetAnAcceptPaymentPage from the Java sample code application to generate a token string for a payment, specified the autoLoginId and transactionKey for my sandbox, and setting $1.00 as the amount. I’m then posting the returned token string to https://test.authorize.net/payment/payment with a “token” form element containing that string. This much appears to be working, and I do get a payment page showing the $1.00 amount. However, no matter what values I enter onto that payment page, pressing the “Pay” button just shows “The transaction has been declined.” in red text at the bottom of the form. I’ve confirmed that my sandbox is set to “Live” mode, and have looked at the following link to use what I believe should be valid values for testing: https://developer.authorize.net/hello_world/testing_guide/. I'm hoping someone can tell me why I can't get any result other than "The transaction has been declined".
public String getTokenValue() {
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
merchantAuthenticationType.setName("xxxxx");
merchantAuthenticationType.setTransactionKey("xxxxxx");
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
// Create the payment transaction request
TransactionRequestType txnRequest = new TransactionRequestType();
txnRequest.setTransactionType(TransactionTypeEnum.AUTH_CAPTURE_TRANSACTION.value());
txnRequest.setAmount(new BigDecimal(1.00).setScale(2, RoundingMode.CEILING));
OrderExType order = new OrderExType();
order.setInvoiceNumber("2");
txnRequest.setOrder(order);
CustomerProfilePaymentType cpp = new CustomerProfilePaymentType();
cpp.setCustomerProfileId("xxxx");
cpp.setCreateProfile(true);
txnRequest.setProfile(cpp);
SettingType setting1 = new SettingType();
setting1.setSettingName("hostedPaymentButtonOptions");
setting1.setSettingValue("{\"text\": \"Proceed\"}");
SettingType setting2 = new SettingType();
setting2.setSettingName("hostedPaymentOrderOptions");
setting2.setSettingValue("{\"show\": false}");
SettingType setting3 = new SettingType();
setting3.setSettingName("hostedPaymentPaymentOptions");
setting3.setSettingValue("{\"cardCodeRequired\": true}");
SettingType setting4 = new SettingType();
setting4.setSettingName("hostedPaymentIFrameCommunicatorUrl");
setting4.setSettingValue("{\"url\": \"http://example.com/abc\"}");
ArrayOfSetting alist = new ArrayOfSetting();
alist.getSetting().add(setting1);
alist.getSetting().add(setting2);
alist.getSetting().add(setting3);
alist.getSetting().add(setting4);
GetHostedPaymentPageRequest apiRequest = new GetHostedPaymentPageRequest();
apiRequest.setTransactionRequest(txnRequest);
apiRequest.setHostedPaymentSettings(alist);
GetHostedPaymentPageController controller = new GetHostedPaymentPageController(apiRequest);
controller.execute();
GetHostedPaymentPageResponse response = new GetHostedPaymentPageResponse();
response = controller.getApiResponse();
if (response != null) {
if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(response.getToken());
} else {
System.out.println("Failed to get hosted payment page: " + response.getMessages().getResultCode());
}
}
return response.getToken();
}
>>> order.setInvoiceNumber("2");
Set the invoice number to a different value than 2, this value is used in Sandbox to trigger decline for testing purposes.

Facebook notification encoding

When using Facebook Graph API to send some notification to my users, it delivers scrambled to them, like so:
Here is my code:
public void sendFBNotificationByUserID(Guid userID, string msg, string url)
{
try
{
// Facebook information from the user
FacebookUser fbUser = getFacebookUserByUserID(userID);
using (WebClient wc = new WebClient())
{
// Retrieve "App Access Token" from Facebook
string appAccessToken = wc.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + Global.fbAppID + "&client_secret=" + Global.fbAppSecret + "&grant_type=client_credentials");
// Create POST parameters
string POSTparam = "template=" + msg + "&href=" + url + "&" + appAccessToken;
// POST to Facebook Graph API to send notification
wc.UploadString("https://graph.facebook.com/" + fbUser.facebookID + "/notifications/", POSTparam);
}
}
catch (Exception)
{
}
}
Any idea?
EDIT:
I did a little reading about URL Encoding and this code solved my problem:
msg = HttpUtility.UrlEncode(msg);
This could be because of the encoding of your page. Some characters get scrambled if they aren't encoded properly. Maybe try using UTF-8 or something else.
Best I could think of.

Vote Restriction Coding Error by Programmer

I am not able to properly launch my site at http://www.enbloc.sg
This is because my programmer is not able to figure out a problem. Any help would be much appreciated.
Visitors vote by clicking on one colour on the traffic light. They are supposed to only have one vote.
The site first checks for cookies and then ip address of voter. If the 2 are identical to a previous visitor, then voting is not allowed. If only one of the 2 are repeated, then voting is permitted.
The idea of having a double restriction is to allow different voters behind a fixed IP to vote. E.g. the employees of a company would not be able to vote since they are likely to be accessing the site via a fixed IP address.
However, currently, visitors are able to click on ALL 3 colours to register 3 votes on their first visit to the site. My coder is not able to resolve this issue and has abandoned me.
I would be most grateful if someone can help. I believe the relevant codes are appended below.
Apologies if my posting is wrongly formatted.
Thanks very much,
Lin En
Extracted from http://www.enbloc.sg/js/functions.js
//update dashboard when vote by user
function vote_update(ip_address, issue_num, vote_status){
var vote_cookie = document.getElementById('vote_cookie').value;
if(vote_cookie != '')
{
if(document.getElementById('thanks').style.display == "none")
{
$("#multi_error").fadeIn("slow");
}
else
{
document.getElementById("thanks").style.display = "none";
$("#multi_error").fadeIn("slow");
}
}
else
{
if(ip_address != ' ' && issue_num != ' ')
{
http.open("POST", "update_vote.php"); // true
http.onreadystatechange = update_vote;
http.setRequestHeader("Content-Type", "application/x-www-form- urlencoded;charset=UTF-8");
http.send("ip="+ ip_address +"&issue_num="+ issue_num + "&vote_status=" + vote_status);
}
else
{
alert("Occur Error for IP or ISSUE!");
}
}
}
// ajax response function
function update_vote(){
if (http.readyState == 4)
{
if (http.status == 200)
{
var xmlDoc = http.responseXML;
var listElements = xmlDoc.getElementsByTagName("list");
var result = listElements[0].getElementsByTagName("total") [0].childNodes[0].nodeValue;
if (result == 1)
{
var issue_num = listElements[0].getElementsByTagName("issue")[0].childNodes[0].nodeValue;
var vote = listElements[0].getElementsByTagName("vote") [0].childNodes[0].nodeValue;
$("#thanks").fadeIn("slow");
load(issue_num, vote);
}
else if (result == 'Multi')
{
if(document.getElementById('thanks').style.display == "none")
{
$("#multi_error").fadeIn("slow");
}
else
{
document.getElementById("thanks").style.display = "none";
$("#multi_error").fadeIn("slow");
}
}
else
{
alert("error");
}
}
}
}
These changes will help:
var already_voted = false;
function vote_update(ip_address, issue_num, vote_status)
{
if(alread_voted) return;
already_voted = true;
// rest of the code
}
This will make sure that only one vote can be cast during a single visit. The cookies take care of the rest and are already working fine.

Blackberry - Is this a guaranteed approach for detecting a valid connection type?

I've created following two methods for reliably building a connection for making a data connection. So far I haven't had any issues testing this approach with users.
I'd love to get some community feedback about this approach and letting me know if anything seems in buildConnectionString(). Please see code below:
private static String buildConnectionString()
{
//The Device is a simultaor --> TCP
if (DeviceInfo.isSimulator())
return ";deviceside=true;ConnectionTimeout=20000";
String st = "";
//A carrier is providing us with the data service
if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_CARRIER) == CoverageInfo.COVERAGE_CARRIER)
{
// blackberry internet service
ServiceRecord rec = getBIBSRecord();//Apply for BIS access to get info about BIS recordset
if (rec != null)//couldn't find the right record
st = "[THIS CONNECTION STRING IS REMOVED, PLEASE APPLY FOR BIS ACCESS TO GET THIS STRING]";
else if(GetWap2().length() > 0)
st = GetWap2();
else
st = ";deviceside=true";// let the phone try to do the work
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
st = ";deviceside=false";// use the clients blackberry enterprise server
else
st = ";deviceside=true";// let the phone do the work if it can
return st + ";ConnectionTimeout=45000";
}
public static String GetWap2() {
String wap2Postfix = null;
final ServiceBook sb = ServiceBook.getSB();
final ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
// Search through all service records to find the valid non Wi-Fi
// WAP 2.0 Gateway Service Record.
if (records[i].isValid() && !records[i].isDisabled()
&& records[i].getUid() != null
&& records[i].getUid().length() != 0
&& records[i].getUid().toLowerCase().indexOf("wifi") == -1
&& records[i].getUid().toLowerCase().indexOf("mms") == -1) {
wap2Postfix = ";ConnectionUID=" + records[i].getUid();
break;
}//endif
}//end for
return wap2Postfix;
}// end wap postfix
Possible questions to consider:
If a BIS string exists (recordset found), will it always work (aside from being blocked by a corporate network)?
If a WAP2 string exists (recordset found), will it always work (aside from being blocked by a corporate network)?
Should I check for MDS support first as opposed to carrier support?
Beyond extreme cases where carriers block a connection, will the above approach work?
Let me me know!
Check this code:
http://developerlife.com/tutorials/?p=884