Example #1
0
 public StripIllegalCharacters(AltBot bot, Unifiable inputString) : base(bot, null, inputString)
 {
 }
 public abstract override float CanUnify(Unifiable with);
Example #3
0
        protected Unifiable ProcessAsIfFileLoading()
        {
            {
                GraphMaster g         = request.Graph;
                var         g0        = g;
                String      graphName = GetAttribValue("graph", null);
                if (graphName != null)
                {
                    g = Proc.GetGraph(graphName, g0);
                    if (g != null)
                    {
                        request.Graph = g;
                    }
                }
                Unifiable path    = GetAttribValue("filename,uri,file,url,dir,path,pathname,directory", null);
                string    command = GetAttribValue("command,cmd", null);
                try
                {
                    //templateNode.LocalName
                    string documentInfo = DocumentInfo();
                    request.CurrentlyLoadingFrom = documentInfo;
                    request.Graph = request.Graph;
                    string innerXML = InnerXmlText(templateNode);


                    if (!string.IsNullOrEmpty(command))
                    {
                        string more = "";
                        if (!string.IsNullOrEmpty(innerXML))
                        {
                            more = " - " + innerXML;
                        }
                        TargetBot.BotDirective(request.Requester, request,
                                               "@" + command + " " + request.Graph.ScriptingName + more,
                                               writeToLog);
                        //QueryHasSuceededN++;
                    }
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(innerXML) && innerXML.Contains("<"))
                            {
                                try
                                {
                                    long successes = request.Loader.loadAIMLNode(templateNode);
                                    return("" + successes);
                                }
                                finally
                                {
                                }
                            }
                            else if (path == "")
                            {
                                writeToLogWarn(
                                    "ERROR! Attempted (but failed) to <learn> some new AIML from the following URI: '{0}' - '{1}'",
                                    path, innerXML);
                            }
                            else
                            {
                                path = path ?? innerXML;
                                request.CurrentFilename = path;
                                long forms = request.Loader.loadAIMLURI(path);
                                QueryHasSuceededN++;
                                return("" + forms); // Succeed();
                            }
                        }
                        catch (ChatSignal e)
                        {
                            throw;
                        }
                        catch (Exception e2)
                        {
                            Proc.writeToLog(e2);
                            writeToLogWarn(
                                "ERROR! Attempted (but failed) to <learn> some new AIML from the following URI: {0} error {1}",
                                path, e2);
                        }
                    }
                    return(Succeed("learned something"));
                }
                finally
                {
                    request.Graph = g0;
                }
            }
        }
Example #4
0
 public ApplySubstitutions(AltBot bot, Unifiable inputString)
     : base(bot, null, inputString)
 {
 }
Example #5
0
        protected override Unifiable ProcessChangeU()
        {
            Unifiable defaultVal = GetAttribValue("default,defaultValue", null);

            if (CheckNode("set"))
            {
                var                 templateNodeInnerText = Recurse();
                Unifiable           name  = GetAttribValue("name,var", null);
                Unifiable           value = GetAttribValue("value", null);
                string              gName = GetAttribValue("global_name", null);
                ISettingsDictionary dict;
                string              dictName = GetNameOfDict(query, "set", templateNode, out dict);
                Succeed();
                if (name == null)
                {
                    //recursive form like <set>name value Unifiable</set>
                    name = templateNodeInnerText.First;
                    var strV = templateNodeInnerText.Rest;
                    if (!IsNull(strV))
                    {
                        if (IsNull(value))
                        {
                            value = strV;
                        }
                        else
                        {
                            writeToLogWarn("ERROR extra stuff in ", strV);
                        }
                    }
                }
                else
                {
                    if (value == null)
                    {
                        var strV = templateNodeInnerText;
                        if (IsNull(strV))
                        {
                            writeToLogWarn("ERROR null stuff in SET ", strV);
                        }
                        value = strV;
                    }
                }
                string setReturn = GetAttribValue <string>(templateNode, "set-return",
                                                           () => ((string)Proc.GetRelationMetaProps().GetMeta(name, "set-return")),
                                                           ReduceStarAttribute <string>);
                if (value == null)
                {
                    value = templateNodeInnerText;
                }
                if (IsNull(value))
                {
                    value = defaultVal;
                }
                if (IsNull(value))
                {
                    if (QueryHasFailed)
                    {
                        return(FAIL);
                    }
                }
                var retVal = NamedValuesFromSettings.SetSettingForType(dictName, query, dict, name, gName, value, setReturn, templateNode);
                if (IsNull(retVal))
                {
                    writeToLogWarn("ERROR null stuff in SET ", retVal);
                }
                else if (IsIncomplete(retVal))
                {
                    writeToLogWarn("ERROR null stuff in SET ", retVal);
                }
                return(retVal);
            }
            return(defaultVal);
        }
Example #6
0
 public void SetValue(object oldValue, object newValue, object unused)
 {
     setter.Invoke((T)(object)Unifiable.Create(newValue));
 }
Example #7
0
 public MakeCaseInsensitive(AltBot bot, Unifiable inputString)
     : base(bot, null, inputString)
 {
 }
Example #8
0
        /// <summary>
        /// The method that does the actual Processing of the text.
        /// </summary>
        /// <returns>The resulting Processed text</returns>
        protected override Unifiable ProcessChangeU()
        {
            if (templateNode.NodeType == XmlNodeType.Comment)
            {
                return(Succeed(templateNode.Value));
            }
            if (templateNode.NodeType == XmlNodeType.Text)
            {
                string s = Trim(templateNode.InnerText);
                if (String.IsNullOrEmpty(s))
                {
                    return(Unifiable.Empty);
                }
                return(s);
            }
            string currentNodeName = templateNode.Name.ToLower();

            if (currentNodeName == "substitutions")
            {
                var prevDict = request.TargetSettings;
                // Process each of these child "settings"? nodes
                try
                {
                    request.TargetSettings = request.TargetBot.InputSubstitutions;
                    SettingsDictionaryReal.loadSettingNode(request.TargetSettings, templateNode, SettingsPolicy.Default, request);
                }
                finally
                {
                    request.TargetSettings = prevDict;
                }
                return(ProcessSucceed());
            }
            if (currentNodeName == "genlmt")
            {
                string name       = GetAttribValue(templateNode, "name,mt,to,super,into", null);
                string removeTo   = GetAttribValue(templateNode, "remove", null);
                string from       = GetAttribValue(templateNode, "graph,from", null);
                bool   deleteLink = false;
                if (name == null)
                {
                    name = Trim(templateNode.InnerText);
                }
                if (removeTo != null)
                {
                    deleteLink = true;
                    name       = removeTo;
                }
                GraphMaster FROM = request.GetGraph(from);
                GraphMaster TO   = request.GetGraph(name);
                if (FROM != null && TO != null)
                {
                    if (deleteLink)
                    {
                        FROM.RemoveGenlMT(TO, writeToLog);
                    }
                    else
                    {
                        FROM.AddGenlMT(TO, writeToLog);
                    }
                    return(Succeed("GENLMT: " + FROM + " => " + name + " => " + TO));
                }
            }
            if (currentNodeName == "sraigraph")
            {
                string name = GetAttribValue(templateNode, "name,mt,to,super,into", null);
                string from = GetAttribValue(templateNode, "graph,from", null);
                if (name == null)
                {
                    name = Trim(templateNode.InnerText);
                }
                GraphMaster FROM = request.GetGraph(from);
                GraphMaster TO   = request.GetGraph(name);
                if (FROM != null && TO != null)
                {
                    FROM.Srai = name;
                    return(Succeed("SRAI: " + FROM + " => " + name + " => right now " + TO));
                }
                return(Failure("FROM '" + from + "'='" + FROM + "'" + " TO '" + name + "'='" + TO + "'"));
            }
            if (currentNodeName == "meta")
            {
                return(Succeed("UNUSED: " + templateNode.OuterXml));
            }
            if (currentNodeName == "#comment")
            {
                return(Succeed("UNUSED: " + templateNode.OuterXml));
            }
            if (currentNodeName == "item")
            {
                SettingsDictionaryReal.loadSettingNode(request.TargetSettings, templateNode, SettingsPolicy.Default, request);
                return(ProcessSucceed());
            }
            if (currentNodeName == "bot")
            {
                SettingsDictionaryReal.loadSettingNode(request.TargetBot.Settings, templateNode, SettingsPolicy.Default, request);
                return(ProcessSucceed());
            }
            string currentNodeOuterXml = templateNode.OuterXml;

            if (currentNodeOuterXml.Length > 280)
            {
                currentNodeOuterXml = TextFilter.ClipString(currentNodeOuterXml, 280);
            }
            writeToLog("ImmediateAiml: " + currentNodeOuterXml);

            /*
             * <TestCase name="connect">
             *      <Input>CONNECT</Input>
             *      <ExpectedAnswer>Connected to test case AIML set.</ExpectedAnswer>
             * </TestCase>
             */

            if (templateNode.NodeType == XmlNodeType.Comment)
            {
                return(ProcessSucceed());
            }

            // pull from late bound sustituion dictionaries
            var sd = request.GetSubstitutions(currentNodeName, false);

            if (sd != null)
            {
                if (FinalResultValid)
                {
                    return(FinalResult);
                }
                if (!Unifiable.IsIncomplete(FinalResult))
                {
                    return(FinalResult);
                }
                Func <Unifiable, Unifiable> Format = (v) => ApplySubstitutions.Substitute(sd, templateNodeInnerText);
                if (base.isRecursive && !ReadOnly)
                {
                    FinalResult = Format(TransformAtomically(null, true));
                    return(finalResult.Value);
                }
                return(FinalResult = TransformAtomically(Format, false));
            }

            if (AltBot.UnknownTagsAreBotVars)
            {
                var dict = Proc.GlobalSettings;
                if (dict.containsSettingCalled(currentNodeName))
                {
                    var v = dict.grabSetting(currentNodeName);
                    if (!Unifiable.IsMissing(v))
                    {
                        return(v);
                    }
                }
            }
            var            vs         = Proc.EvalAiml(templateNode, request, request.writeToLog);
            StringBuilder  sb         = new StringBuilder();
            int            writeThrus = 0;
            int            total      = 0;
            OutputDelegate WriteLine  = DLRConsole.SystemWriteLine;

            foreach (var node in vs)
            {
                total++;
                string nodeOuterXml = ToXmlValue(node);
                WriteLine(nodeOuterXml);
                string p = GetAttribValue(node, "PASSED", "FALSE");
                if (p == "False")
                {
                    writeThrus++;
                    sb.Append("\n" + nodeOuterXml.Replace("\" ", "\"\n ") + "\n");
                }
                WriteLine("");
            }

            WriteLine("");
            WriteLine("");
            WriteLine("" + writeThrus);
            WriteLine("");
            string ss = sb.ToString();

            WriteLine(ss);
            WriteLine("");
            WriteLine("");
            WriteLine("");
            return(Succeed("total is " + total));
        }
Example #9
0
        public string ExpandFormat(string subj, string relation, object value, bool isQuery, SettingsDictionary dictionary, Unifiable formatter, XmlNode templateNode)
        {
            string pred = Entify(relation);

            string botName = !IsBotRobot(subj) ? Entify(TheBot.BotUserID) : Entify(TheBot.LastUser.UserID);
            {
                var whword = GetDictValue(dictionary, relation, "format-whword");

                if (!Unifiable.IsNullOrEmpty(whword) && isQuery)
                {
                    value = whword;
                }
                var formatterUpper = Unifiable.ToUpper(formatter);
                if (Unifiable.IsFalseOrNo(formatterUpper))
                {
                    return("false");
                }

                formatter = ReplaceWord(formatter, "$subject", "{0}");
                formatter = ReplaceWord(formatter, "$verb", "{1}");
                formatter = ReplaceWord(formatter, "$object", "{2}");

                formatter = ReplaceWord(formatter, "$user", "{0}");
                formatter = ReplaceWord(formatter, "$relation", "{1}");
                formatter = ReplaceWord(formatter, "$value", "{2}");

                formatter = ReplaceWord(formatter, "$predicate", pred);

                formatter = ReplaceWord(formatter, "$set-return",
                                        TheBot.RelationMetaProps.grabSetting(relation + "." + "set-return"));
                formatter = ReplaceWord(formatter, "$default", TheBot.DefaultPredicates.grabSetting(relation));

                formatter = ReplaceWord(formatter, "$botname", botName);
                formatter = ReplaceWord(formatter, "$bot", botName);
            }

            string english = " " + String.Format(formatter, subj, pred, Entify(value)).Trim() + " ";

            english = ReplaceWord(english, "I", subj);
            english = ReplaceWord(english, "you", botName);
            english = english.Trim();
            User user = TheBot.FindUser(subj);

            english = FixPronouns(english, user.grabSettingNoDebug);
            return(english);
        }
Example #10
0
        /// <summary>
        /// Checks to see if a setting of a particular name exists
        /// </summary>
        /// <param name="name">The setting name to check</param>
        /// <returns>Existential truth value</returns>
        public bool containsSettingCalled(string name)
        {
            Unifiable value = grabSetting(name);

            return(!Unifiable.IsNullOrEmpty(value));
        }
Example #11
0
 public Utterance(Func <Unifiable, Unifiable> generatePhrase, User speaker, User toWhom, Unifiable rawText, int maxSentences)
 {
     Speaker                  = speaker;
     ToWhom                   = toWhom;
     OrignalRawText           = rawText;
     OutputSentencesToEnglish = generatePhrase;
     if (maxSentences < 10)
     {
         maxSentences = 10;
     }
     maxResults = maxSentences + 10;
 }
Example #12
0
 public override float CanUnify(Unifiable with)
 {
     writeToLogWarn("CANUNIFY: " + with);
     return(base.CanUnify(with));
 }
Example #13
0
        static Unifiable IfSucceed(XmlNode templateNode, ISettingsDictionary dict, SubQuery query0, Func <Unifiable> Succeed, Func <string, Unifiable> Failure)
        {
            lock (templateNode)
            {
                //  ISettingsDictionary dict = query;
                //if (GetAttribValue(templateNode, "type", "") == "bot" || GetAttribValue(templateNode,"bot", "").ToLower() == "true")
                //   dict = query0.TargetBot.GlobalSettings;

                bool yesInherit = true;
                bool noLocal    = false;

                string locally = GetAttribValue(templateNode, "scope,type,exists", "");
                if (locally.Contains("local"))
                {
                    yesInherit = false;
                }
                if (locally.Contains("inher"))
                {
                    noLocal    = true;
                    yesInherit = true;
                }

                Func <IConvertible, string> query = query0.ReduceStarAttribute <string>;

                string    name       = GetAttribValue <string>(templateNode, "name,var,if", NullStringFunct, query);
                string    expression = GetAttribValue <string>(templateNode, "expr", NullStringFunct, query);
                string    exists     = GetAttribValue(templateNode, "exists", NullStringFunct, query);
                string    contains   = GetAttribValue(templateNode, "contains", NullStringFunct, query);
                Unifiable value      = GetAttribValue(templateNode, "value", NullStringFunct, query);
                string    scope      = GetAttribValue(templateNode, "local,scope", NullStringFunct, query);
                string    realName0;
                string    type = GetAttribValue(templateNode, "type,user,bot", out realName0, NullStringFunct, query);
                if (type == null)
                {
                    type = realName0;
                }

                string varname      = name ?? exists;
                bool   mustNotExist = false;
                if (contains != null)
                {
                    value = ".*" + contains + ".*";
                }

                if (exists != null)
                {
                    bool locallyContains = dict.containsLocalCalled(name);
                    bool anyContains     = dict.containsSettingCalled(name);

                    if (exists.StartsWith("local"))
                    {
                        if (!locallyContains)
                        {
                            return(Unifiable.Empty);
                        }
                        return(Succeed());
                    }

                    exists = exists.ToLower();
                    if (exists == "inherited")
                    {
                        if (!locallyContains && anyContains)
                        {
                            return(Succeed());
                        }
                        return(Failure("" + name + "=" + anyContains + " !inherited "));
                    }
                    if (exists == "false")
                    {
                        if (!yesInherit)
                        {
                            if (!locallyContains)
                            {
                                return(Succeed());
                            }
                        }
                        if (noLocal)
                        {
                            if (anyContains && !locallyContains)
                            {
                                return(Succeed());
                            }
                        }
                        return(Failure("" + name + "=" + anyContains + " !false "));
                    }
                    if (exists == "true")
                    {
                        if (!yesInherit)
                        {
                            if (locallyContains)
                            {
                                return(Succeed());
                            }
                        }
                        if (noLocal)
                        {
                            if (!locallyContains && anyContains)
                            {
                                return(Succeed());
                            }
                        }
                        return(Failure("" + name + "=" + anyContains + "  " + templateNode.OuterXml));
                    }
                    string realName;
                    bool   succeed;
                    //ReduceStar0 query = query0.ReduceStarAttribute;
                    Unifiable actualValue = GetActualValue(templateNode, name, type ?? dict.NameSpace, out succeed, query0);
                    if (IsPredMatch(value, actualValue, query0))
                    {
                        return(Succeed());
                    }
                    else
                    {
                        return(Failure("" + name + "=" + anyContains + "  " + templateNode.OuterXml));
                    }
                }
                return(Succeed());
            }
        }
 public virtual float DefaultCanUnify(Unifiable with)
 {
     return(ComputeInnerOrNull().Unify(with, this.query));
 }
Example #15
0
 /// <summary>
 /// An ease-of-use static method that re-produces the instance transformation methods
 /// </summary>
 /// <param name="input">The Unifiable to transform</param>
 /// <returns>The resulting Unifiable</returns>
 public static Unifiable TransformInput(Unifiable input)
 {
     return(input.ToCaseInsensitive());
 }
 protected void SetWith(XmlNode childNode, Unifiable with)
 {
     MEMBER = new Unifiable[] { with };
 }
Example #17
0
        public static Action EnterTag(Request request, XmlNode templateNode, SubQuery query)
        {
            if (templateNode.NodeType != XmlNodeType.Element)
            {
                return(DoNothing);

                throw new NotImplementedException("EnterTag: " + templateNode.NodeType);
            }
            bool                needsUnwind = false;
            UndoStackHolder     thiz        = (UndoStackHolder)query ?? request;
            ISettingsDictionary dict        = query;

            if (dict == null && request != null)
            {
                dict = request.TargetSettings;
            }
            XmlAttributeCollection collection = templateNode.Attributes;

            EnterContext(request, query);
            if (collection == null || collection.Count <= 0)
            {
                return(() =>
                {
                    ExitContext(request, query);
                });
            }
            else
            {
                var    used           = new List <XmlAttribute>();
                string defaultElement = "";
                Action gmrerstore;
                gmrerstore = request.WithAttributesForUnwind(templateNode, ref defaultElement, used);
                int       uc          = used.Count;
                UndoStack savedValues = null;

                foreach (XmlAttribute node in collection)
                {
                    if (used.Contains(node))
                    {
                        continue;
                    }
                    bool   found;
                    string n = node.Name.ToLower();
                    switch (n)
                    {
                    case "state":
                    case "flag":
                    case "graph":
                    case "topic":
                    case "that":
                        break;

                    default:
                    {
                        lock (ReservedAttributes)
                        {
                            if (ReservedAttributes.Contains(n))
                            {
                                continue;
                            }
                            bool prev = NamedValuesFromSettings.UseLuceneForGet;
                            try
                            {
                                NamedValuesFromSettings.UseLuceneForGet = false;
                                if (!dict.containsSettingCalled(n))
                                {
                                    ReservedAttributes.Add(n);
                                    request.writeToLog("ReservedAttributes: {0}", n);
                                }
                                else
                                {
                                    if (!PushableAttributes.Contains(n))
                                    {
                                        PushableAttributes.Add(n);
                                        request.writeToLog("PushableAttributes: {0}", n);
                                    }
                                }
                            }
                            finally
                            {
                                NamedValuesFromSettings.UseLuceneForGet = prev;
                            }
                        }

                        // now require temp vars to s   ay  with_id="tempId"
                        // to set the id="tempid" teporarily while evalig tags
                        if (!n.StartsWith("with_"))
                        {
                            continue;
                        }
                        else
                        {
                            n = n.Substring(5);
                        }

                        Unifiable v = ReduceStar <Unifiable>(node.Value, query, dict, out found);
                        UndoStack.FindUndoAll(thiz, true);
                        savedValues = savedValues ?? UndoStack.GetStackFor(thiz);
                        //savedValues = savedValues ?? query.GetFreshUndoStack();
                        savedValues.pushValues(dict, n, v);
                        needsUnwind = true;
                    }
                    break;
                    }
                }

                // unwind

                return(() =>
                {
                    if (needsUnwind)
                    {
                        try
                        {
                            EnterContext(request, query);
                            if (savedValues != null)
                            {
                                savedValues.UndoAll();
                            }
                        }
                        catch (Exception ex)
                        {
                            request.writeToLog("ERROR " + ex);
                        }
                        finally
                        {
                            ExitContext(request, query);
                        }
                    }
                    ExitContext(request, query);
                    if (uc > 0)
                    {
                        gmrerstore();
                    }
                });
            }
        }
Example #18
0
 public override float CanUnify(Unifiable with)
 {
     throw new NotImplementedException();
 }
Example #19
0
        public static bool ContainsAiml(Unifiable unifiable)
        {
            String s = unifiable.AsString();

            return(StaticXMLUtils.ContainsXml(s));
        }
Example #20
0
        private XmlNode RunTest(Request request, XmlNode src, OutputDelegate outputdelegate, out bool m)
        {
            // request = request ?? Loader.LoaderRequest00;
            User   user  = request.Requester;
            AltBot robot = request.TargetBot ?? Loader.TargetBot;

            string tcname = StaticXMLUtils.FindNodeOrAttrib(src, "name", null);
            string tcdesc = FindNodeOrAttrib(src, "Description", null);
            string input  = FindNodeOrAttrib(src, "Input", null);

            if (input == null)
            {
                outputdelegate("ERROR cannot find 'Input' in '" + src.OuterXml + "'");
                m = false;
                return(getNodeAndSetSibling(false,
                                            "<template type=\"error\">ERROR cannot find 'Input' in '" + src.OuterXml + "'</template>", true,
                                            false, src));
            }
            string userID = FindNodeOrAttrib(src, "UserId,UserName", () => user.UserID);

            const string MISSING_EXPECTED_ANSWER = "ExpectedKeywords";
            var          matchTheseToPass        = new List <string>();
            string       expectedAnswer          = FindNodeOrAttrib(src, "ExpectedAnswer", () => MISSING_EXPECTED_ANSWER);

            expectedAnswer = Fudge(expectedAnswer);
            if (expectedAnswer == MISSING_EXPECTED_ANSWER)
            {
                var nodes = FindNodes("ExpectedKeywords", src);
                if (nodes == null || nodes.Count == 0)
                {
                    outputdelegate("ERROR cannot find 'ExpectedAnswer' in '" + src.OuterXml + "'");
                }
                else
                {
                    foreach (XmlNode list in nodes)
                    {
                        string v = Unifiable.InnerXmlText(list);

                        matchTheseToPass.Add(".*" + Fudge(v) + ".*");
                    }
                }
            }
            else
            {
                matchTheseToPass.Add("^" + Fudge(expectedAnswer) + "$");
            }

            outputdelegate("{0}: {1} ", tcname, tcdesc);
            outputdelegate("{0}: {1} ", userID, input);
            string resp = "ERROR";

            try
            {
                var requestToBot = robot.MakeRequestToBot(input, userID, true, RequestKind.ChatRealTime);
                requestToBot.IsTraced = traceIt;
                if (traceIt)
                {
                    AltBot.Breakpoint("testing...");
                    requestToBot.DebugLevel = 9;
                }
                Result result = robot.Chat(requestToBot);
                resp = result.Output ?? result.ToString() ?? resp;
                if (resp == null)
                {
                    resp = "NULLED";
                }
                resp = Fudge(resp);
                outputdelegate("{0}: {1} ", robot, resp);
                m = true;
                int good = 0;
                foreach (string s in matchTheseToPass)
                {
                    if (!Matches(resp, s, FindNodeOrAttrib(src, "MatchType,Match", null)))
                    {
                        m = false;
                    }
                    else
                    {
                        good++;
                    }
                }
                outputdelegate("PASSED={0}", m);
                if (traceIt)
                {
                    AltBot.Breakpoint("tested...");
                }
                return(GetMessage(src, "PASSED='" + m +
                                  "'", "TESTCASE='" + tcname + "' GOOD='" + good +
                                  "' RESPNS='" + resp +
                                  "' EXPECT='" + expectedAnswer +
                                  "' INPUT='" + input +
                                  "' DESC='" + tcdesc + "'"));
            }
            catch (Exception err)
            {
                string ERRMSG = "" + err;
                m = false;
                errorCount++;
                return(GetMessage(src, "PASSED='" + m +
                                  "'", "TESTCASE='" + tcname + "' ERRMSG='" + ERRMSG + "' RESP='" + resp +
                                  "' EXPECT='" + expectedAnswer +
                                  "' INPUT='" + input +
                                  "' DESC='" + tcdesc + "'"));
            }
        }
Example #21
0
 public static Unifiable AltStar(string name, SubQuery query, ISettingsDictionary dict, out bool rfound)
 {
     try
     {
         if (name.Contains(","))
         {
             foreach (string subname in NamesStrings(name))
             {
                 var val = AltStar(name, query, dict, out rfound);
                 if (rfound)
                 {
                     rfound = true;
                     return(val);
                 }
             }
         }
         if (name.StartsWith("star_"))
         {
             return(GetDictData(query.InputStars, name, 5, out rfound));
         }
         else if (name.StartsWith("inputstar_"))
         {
             return(GetDictData(query.InputStars, name, 10, out rfound));
         }
         else if (name.StartsWith("input_"))
         {
             return(GetDictData(query.InputStars, name, 6, out rfound));
         }
         else if (name.StartsWith("thatstar_"))
         {
             return(GetDictData(query.ThatStars, name, 9, out rfound));
         }
         else if (name.StartsWith("that_"))
         {
             return(GetDictData(query.ThatStars, name, 5, out rfound));
         }
         else if (name.StartsWith("topicstar_"))
         {
             return(GetDictData(query.TopicStar, name, 10, out rfound));
         }
         else if (name.StartsWith("topic_"))
         {
             return(GetDictData(query.TopicStar, name, 6, out rfound));
         }
         else if (name.StartsWith("guardstar_"))
         {
             return(GetDictData(query.GuardStar, name, 10, out rfound));
         }
         else if (name.StartsWith("guard_"))
         {
             return(GetDictData(query.GuardStar, name, 6, out rfound));
         }
         else if (name.StartsWith("@"))
         {
             Unifiable value = query.Request.TargetBot.SystemExecute(name, null, query.Request);
             rfound = true;
             if (!IsNullOrEmpty(value))
             {
                 return(value);
             }
             return(value);
         }
         else if (name.StartsWith("%dictvar_"))
         {
             Unifiable value = value = GetValue(query, dict, name.Substring(8), out rfound);
             if (rfound)
             {
                 return(value);
             }
             return(value);
         }
         else
         {
             if (name.StartsWith("%") || name.StartsWith("$"))
             {
                 string str = name.Substring(1);
                 var    vv  = ResolveVariableValue(str, query, dict, out rfound);
                 if (rfound)
                 {
                     return(vv);
                 }
                 return(vv);
             }
             else if (name.Contains("."))
             {
                 var vv = ResolveVariableValue(name, query, dict, out rfound);
                 if (rfound)
                 {
                     return(vv);
                 }
                 return(vv);
             }
             rfound = false;
             return(name);
         }
     }
     catch (Exception e)
     {
         AltBot.writeDebugLine("" + e);
         rfound = false;
         return(null);
     }
 }
Example #22
0
        protected Unifiable ProcessChangeMSM()
        {
            //if (this.templateNode.Name.ToLower() == "Processmsm")
            {
                string machine = GetAttribValue("name", null);
                string line    = templateNodeInnerText.ToValue(query);
                AltBot.writeDebugLine("\n\n >>>>>>>>>>>>>>>>>>>>>> PROCESSMSM : |{0}|<<<<<<<<<<<<<<<<<<<<", line);
                //varMSM.lastDefMachine = machine;
                var varMSM = botActionMSM;

                varMSM.addMachine(machine);
                // set topic to "collectevidencepatterns"
                //Proc.AddAiml("<set name='topic'>collectevidencepatters</set>");
                //this.user.Predicates.updateSetting("topic", "collectevidencepatters");
                user.TopicSetting = "CEP";

                // Clear the evidence and next state
                varMSM.clearEvidence();
                varMSM.clearNextStateValues();

                // estimate what evidence can be gleaned from the current state
                varMSM.inspectEvidenceStates();

                // Process the input text

                //string evidenceReply = Proc.ChatString(line, this.user.UserID);
                string evidenceReply = subChat(line, user.TopicSetting, request, true);

                AltBot.writeDebugLine("MSM: WithEvidence {0} ", varMSM.ToString());

                // TODO: we should also get evidence across machine boundries

                // compute the "TRUE" topics from the state machines,advance all machines using evidence
                Hashtable machinesTopState = new Hashtable();
                foreach (string mac in varMSM.machines.Keys)
                {
                    string top_State = varMSM.advanceMachine(mac);
                    machinesTopState[mac] = top_State;
                }
                // make the next_state values the new current state values
                varMSM.advanceStateValues();
                AltBot.writeDebugLine("MSM: AfterAdvance {0} ", varMSM.ToString());

                // For each machine set the appropriate topic, and Process the input text
                string totalReply   = "";
                double strongestVal = -9999;
                foreach (string actingMachine in machinesTopState.Keys)
                {
                    string actionState = (string)machinesTopState[actingMachine];
                    double actp        = (double)varMSM.cur_machineStateVal[actionState];

                    Hashtable topicHt = (Hashtable)varMSM.machineStateResponses[actionState];

                    if ((topicHt != null) && (topicHt.Count > 0))
                    {
                        foreach (string responseTopic in topicHt.Keys)
                        {
                            //prob = topicHt[responseTopic] = prob;
                            string responseTopicUp = ToUpper(responseTopic);
                            //string topicSet = "<set name='topic'>"+responseTopic+"</set>";
                            //this.user.Predicates.updateSetting("topic", responseTopic);
                            user.TopicSetting = responseTopicUp;
                            //Proc.AddAiml(topicSet);
                            string actionReply = "";
                            //actionReply = Proc.ChatString(line, this.user.UserID);


                            actionReply = subChat(line, responseTopicUp, request, false);

                            // Append or use non-null response with the most certainty
                            //totalReply += " " + actionReply;
                            AltBot.writeDebugLine("MSM:[[ PossReply m:{0} s:{1} p:{2} RT: {3} REPLY:{4} ]]  <<< * * * * * *", actingMachine, actionState, actp, responseTopicUp, actionReply.Trim());

                            if ((actp > strongestVal) && (actionReply.Trim().Length > 0))
                            {
                                strongestVal = actp;
                                totalReply   = actionReply;
                            }
                        }
                    }
                }
                Unifiable result = totalReply.Trim();
                AltBot.writeDebugLine("MSM: FinalReply :{0}", totalReply.Trim());
                return(result);
            }
            return(Unifiable.Empty);
        }
Example #23
0
 protected virtual Unifiable Format(Unifiable unifiable)
 {
     return(unifiable);
 }
Example #24
0
 public static CategoryInfo GetCategoryInfo(Unifiable info, XmlNode node, LoaderOptions filename, XmlNode templateNode,
                                            Unifiable template, Unifiable guard, Unifiable topicInfo, Node patternNode, Unifiable thatInfo, IEnumerable <ConversationCondition> conds)
 {
     return(filename.Graph.FindCategoryInfo(info, node, filename, templateNode, template, guard, topicInfo,
                                            patternNode, thatInfo, conds));
 }
Example #25
0
 public AIMLTagHandlerB(AltBot bot, string instr, Unifiable inu)
 {
     this.bot     = bot;
     inputStringU = inu ?? instr;
     inputString  = initialString = instr ?? inputStringU.AsString();
 }