CGC_Codes

Chatbot

Jun 2nd, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.77 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8.  
  9. namespace QXS.ChatBot
  10. {
  11.     internal class DescComparer<T> : IComparer<T>
  12.     {
  13.         public int Compare(T x, T y)
  14.         {
  15.             return Comparer<T>.Default.Compare(y, x);
  16.         }
  17.     }
  18.  
  19.     /// <summary>
  20.     /// The Chatbot
  21.     /// </summary>
  22.     public class ChatBot
  23.     {
  24.         /// <summary>
  25.         /// A conversation started
  26.         /// </summary>
  27.         public event Action<ChatSessionInterface> OnConverationStarted;
  28.  
  29.         /// <summary>
  30.         /// A conversation ended
  31.         /// </summary>
  32.         public event Action<ChatSessionInterface> OnConverationEnded;
  33.  
  34.         /// <summary>
  35.         /// The chatbot received a messsage
  36.         /// </summary>
  37.         public event Action<ChatSessionInterface, string> OnMessageReceived;
  38.  
  39.         /// <summary>
  40.         /// The chatbot replied to a message
  41.         /// </summary>
  42.         public event Action<ChatSessionInterface, string> OnMessageSent;
  43.  
  44.         /// <summary>
  45.         /// Sets the Exit Condition for an ending conversation
  46.         /// </summary>
  47.         public Func<string, bool> ExitCondition;
  48.  
  49.         /// <summary>
  50.         /// Sets the default resonse in case no appropriate Rule was found
  51.         /// </summary>
  52.         public Func<string, string> DefaultAnswer;
  53.  
  54.         protected Stack<string> _commandHistory = new Stack<string>();
  55.         protected SortedList<int, List<BotRule>> _botRules = new SortedList<int, List<BotRule>>(new DescComparer<int>());
  56.  
  57.         /// <summary>
  58.         /// Creaates the Chatbot
  59.         /// </summary>
  60.         /// <param name="Rules"></param>
  61.         public ChatBot(IEnumerable<BotRule> Rules)
  62.         {
  63.             Dictionary<string, bool> ruleNames = new Dictionary<string, bool>();
  64.             foreach (BotRule rule in Rules)
  65.             {
  66.                 if (rule.Process == null)
  67.                 {
  68.                     throw new ArgumentException("Process is null.", "Rules");
  69.                 }
  70.                 if (rule.MessagePattern == null)
  71.                 {
  72.                     throw new ArgumentException("MessagePattern is null.", "Rules");
  73.                 }
  74.                 if (ruleNames.ContainsKey(rule.Name))
  75.                 {
  76.                     throw new ArgumentException("Names are not unique. Duplicate key found for rule name \"" + rule.Name + "\".", "Rules");
  77.                 }
  78.                 ruleNames[rule.Name] = true;
  79.                 if (!this._botRules.ContainsKey(rule.Weight))
  80.                 {
  81.                     this._botRules[rule.Weight] = new List<BotRule>();
  82.                 }
  83.                 this._botRules[rule.Weight].Add(rule);
  84.             }
  85.  
  86.             ExitCondition = this.isGoodBye;
  87.         }
  88.  
  89.         /// <summary>
  90.         /// Find a matching rule/reponse to a question/message
  91.         /// </summary>
  92.         /// <param name="session">The session, that should be used</param>
  93.         /// <param name="messageIn">The message that came in</param>
  94.         /// <returns>the response string or null in case no answer was found</returns>
  95.         protected string findAnswer(ChatSessionInterface session, string messageIn)
  96.         {
  97.             foreach (List<BotRule> rules in this._botRules.Values)
  98.             {
  99.                 foreach (BotRule rule in rules)
  100.                 {
  101.                     Match match = rule.MessagePattern.Match(messageIn);
  102.                     if (match.Success)
  103.                     {
  104.                         string msg = rule.Process(match, session);
  105.                         if (msg != null)
  106.                         {
  107.                             session.AddResponseToHistory(new BotResponse(rule.Name, messageIn, msg));
  108.                             return msg;
  109.                         }
  110.                     }
  111.                 }
  112.             }
  113.  
  114.             return null;
  115.         }
  116.  
  117.         protected void sendResponse(ChatSessionInterface session, string messageOut)
  118.         {
  119.             session.sendMessage(messageOut);
  120.             if (OnMessageSent != null)
  121.             {
  122.                 OnMessageSent(session, messageOut);
  123.             }
  124.         }
  125.  
  126.         /// <summary>
  127.         /// Starts a conversation over a session
  128.         /// </summary>
  129.         /// <param name="session"></param>
  130.         public void talkWith(ChatSessionInterface session)
  131.         {
  132.             if (session == null)
  133.             {
  134.                 return;
  135.             }
  136.  
  137.             if (OnConverationStarted != null)
  138.             {
  139.                 OnConverationStarted(session);
  140.             }
  141.  
  142.  
  143.             string messageIn = "";
  144.             string messageOut = "";
  145.             for (messageIn = session.readMessage(); !this.ExitCondition(messageIn); messageIn = session.readMessage())
  146.             {
  147.                 if (OnMessageReceived != null)
  148.                 {
  149.                     OnMessageReceived(session, messageIn);
  150.                 }
  151.  
  152.                 messageOut = findAnswer(session, messageIn);
  153.                 if (messageOut == null)
  154.                 {
  155.                     // do we have a default answer?
  156.                     if (DefaultAnswer != null)
  157.                     {
  158.                         messageOut = DefaultAnswer(messageIn);
  159.                     }
  160.                     // still null?
  161.                     if (messageOut == null)
  162.                     {
  163.                         sendResponse(session, "What did you say?");
  164.                     }
  165.                     else
  166.                     {
  167.                         sendResponse(session, messageOut);
  168.                     }
  169.  
  170.                 }
  171.                 else
  172.                 {
  173.                     sendResponse(session, messageOut);
  174.                 }
  175.                 // still interactive?
  176.                 if (!session.IsInteractive)
  177.                 {
  178.                     break;
  179.                 }
  180.             }
  181.  
  182.             if (OnConverationEnded != null)
  183.             {
  184.                 OnConverationEnded(session);
  185.             }
  186.         }
  187.  
  188.         /// <summary>
  189.         /// Sets the default Exit Condition for the conversation
  190.         /// </summary>
  191.         /// <seealso cref="ExitCondition"/>
  192.         /// <param name="message">Message, that came in</param>
  193.         /// <returns>Returns true, in case the conversation should be ended</returns>
  194.         public bool isGoodBye(string message)
  195.         {
  196.             switch (message.ToLower())
  197.             {
  198.                 case "quit": return true;
  199.                 case "exit": return true;
  200.                 case "goodbye": return true;
  201.                 case "good bye": return true;
  202.                 case "bye": return true;
  203.             }
  204.             return false;
  205.         }
  206.     }
  207. }
Advertisement
Add Comment
Please, Sign In to add comment