private bool ShiftLane(int iLane) { List <CreatureBase> LaneCreatures = TournamentManager._instance.lanes[iLane].GetFriendliesInLane(this); //LogStack.Log("Shifting lane... creatures to shift = " + LaneCreatures.Count, LogLevel.Debug); if (iFriendlyCount >= iOffensiveThreshold) { LaneCreatures.Reverse(); } foreach (CreatureBase _creature in LaneCreatures) { //LogStack.Log("Current Creature = " + _creature.name + " Current ID = " + _creature.GetInstanceID(), LogLevel.Debug); if (AIResponse.Move(_creature, 1)) { //LogStack.Log("Current Creature = " + _creature.name + " Current ID = " + _creature.GetInstanceID() + " | Can move", LogLevel.Debug); if (TokenCheck() == false) { return(true); } } else if (iFriendlyCount > iOffensiveThreshold) { return(false); // Ensures front troops push for end. } } return(true); }
public void SendText(string question) { AIResponse response = apiAiUnity.TextRequest(question); if (response != null) { int val = 0; string type = response.Result.Metadata.IntentName; string text = response.Result.Fulfillment.Speech; if (type == "Bienvenido") { val = 0; } else if (type == "explicacion") { val = 1; } else if (type == "lugar") { val = 2; } else if (type == "nombre") { val = 3; } GameController.HandleResponse(val); Debug.Log(text); } else { Debug.LogError("Response is null"); print("-> ERROR"); } }
/// <summary> /// Отправить сообщение, если пользователь прислал документ /// </summary> /// <param name="item"></param> /// <param name="response"></param> /// <returns></returns> public BotState?DocumentSent(VK.UserLongPoll.Update item, AIResponse response) { // Вывод сообщения в соответствии с распознанным действием api.Messages_SendMessage(Program.Cfg.CommunityID, item.PeerID, response.Result.Fulfillment.Speech); //api.Documents_GetById(Program.Cfg.CommunityID, item.DocId); return(null); }
void AttemptMoveAttack(CreatureBase creature) { if (creature != null) { List <CreatureBase> searchTargetCreatures = creature.ActiveLaneNode.laneManager.SearchRange((int)creature.Range, creature.ActiveLaneNode, this); bool foundAttackTarget = false; foreach (CreatureBase _creature in searchTargetCreatures) { if (_creature.Owner != creature.Owner) //Found enemy creature in range { foundAttackTarget = true; AIResponse.Attack(creature); } } if (!foundAttackTarget) { int moveSpaces = creature.ActiveLaneNode.laneManager.GetOpenNodes(creature.ActiveLaneNode, _RightFacing); if (moveSpaces > AIResponse.Tokens) { moveSpaces = AIResponse.Tokens; } if (AIResponse.Move(creature, moveSpaces)) { LogStack.Log("Hal Move " + creature.GetInstanceID() + " - " + moveSpaces + " spaces - " + creature.LaneProgress, LogLevel.System); } } } }
protected void FormPattern(LanePattern pattern, int lane, LaneManager[] Board) { LaneManager TheLane = Board[lane - 1]; CreatureBase[] FriendlyCreatures = TheLane.GetFriendliesInLane(this).ToArray(); if (FriendlyCreatures.Length == 0) { foreach (Spawnable spawntype in pattern.PatternDefinition) { AIResponse.Spawn(spawntype, lane); } return; } LanePattern lanePattern = new LanePattern(FriendlyCreatures); if (LanePattern.Equals(lanePattern)) { return; } for (int i = 0; i < LanePattern.PatternDefinition.Length; i++) { if (lanePattern.PatternDefinition.Length <= i || LanePattern.PatternDefinition[i] != lanePattern.PatternDefinition[i]) { if (!AIResponse.Spawn(LanePattern.PatternDefinition[i], lane)) { Debug.Log("~~~~ Failed Spawn in Pattern"); } else { Debug.Log("~~~~ Success Spawn in Pattern"); } } } }
public void SendText(String text) { Debug.Log(text); AIResponse response = apiAiUnity.TextRequest(text); if (response != null) { Debug.Log("Resolved query: " + response.Result.ResolvedQuery); var outText = JsonConvert.SerializeObject(response, jsonSettings); Debug.Log("Result: " + outText); String[] new1 = outText.Split(':'); // Debug.Log(new1.Length); // for (int i=0;i<new1.Length;i++) // { Debug.Log(new1[14]); String[] res = new1[14].Split('}'); String res1 = res[0]; res1 = res1.Substring(1, res1.Length - 2); // } gm.SetActive(true); answerTextField.text = res1; ttss(); StartCoroutine(PauseRoutine()); } else { Debug.LogError("Response is null"); } }
public void MoveAtk(CreatureBase creat) { Debug.Log("Moving or attacking: " + creat.name + ", in lane: " + creat.LaneIndex.ToString()); if (creat != null) { bool TargetInRange = false; List <CreatureBase> Targets = creat.ActiveLaneNode.laneManager.SearchRange((int)creat.Range, creat.ActiveLaneNode, this); foreach (CreatureBase creature in Targets) { if (creature.Owner != creat.Owner) { TargetInRange = true; AIResponse.Attack(creat); } } if (!TargetInRange) { int spaces = creat.ActiveLaneNode.laneManager.GetOpenNodes(creat.ActiveLaneNode, creat.RightFacing); if (spaces > AIResponse.Tokens) { spaces = AIResponse.Tokens; } if (spaces > 10) { spaces = 10; } AIResponse.Move(creat, spaces); } } }
public async Task <IActionResult> DialogFlowPost() { AIResponse response = null; using (var streamReader = new StreamReader(Request.Body)) { response = JsonConvert.DeserializeObject <AIResponse>(streamReader.ReadToEnd()); } switch (response.OriginalRequest.Source) { case ApiAiSdkNetCore.Enums.Provider.Line: // populate the data object with the correct item response.OriginalRequest.Event = WebhookRequestMessageHelper.GetWebhookEventFromStringAsync(response.OriginalRequest.Data); break; default: break; } await _intentManager.ProcessIntent(response); return(Ok()); }
public AIResponse SendVoiceText(string input) { //var text = inputTextField.text; //var text = answerTextField.text; var text = input; //Debug.Log(text); AIResponse response = apiAiUnity.TextRequest(text); if (response != null) { //Debug.Log("Resolved query: " + response.Result.ResolvedQuery); //Debug.Log(response.Result.Metadata.IntentName); //var outText = fastJSON.JSON.ToJSON(response); var outText = NewJSon::Newtonsoft.Json.JsonConvert.SerializeObject(response, jsonSettings); Debug.Log("Result: " + outText); return(response); } else { Debug.LogError("Response is null"); return(response); } }
/// <summary> /// Регистрация пользователя /// </summary> /// <param name="item">Сообщение пользователя</param> /// <param name="response">Ответ AI</param> public BotState?RegisterUser(VK.UserLongPoll.Update item, AIResponse response) { // Определение E-mail string email = response.Result.Parameters["email"].ToString(); // Сообщаем пользователю api.Messages_SendMessage(Program.Cfg.CommunityID, item.PeerID, string.Format("Начинаю регистрацию пользователя с адресом {0}", email)); // Поиск студента в базе данных if (db.Students.Where(a => a.Email == email).FirstOrDefault() != null) { api.Messages_SendMessage(Program.Cfg.CommunityID, item.PeerID, string.Format("Пользователь с таким E-mail уже зарегистрирован")); return(null); } // Запрос информации о пользователе VK.Users.Get.Response user = api.Users_Get(Program.Cfg.CommunityID, item.PeerID); // Создание нового объекта var s = new Storage.Student() { ID = Guid.NewGuid(), VKID = item.PeerID, FirstName = user.FirstName, LastName = user.LastName, Email = email }; db.Students.Add(s); // Сохраняем изменение в базе данных db.SaveChanges(); api.Messages_SendMessage(Program.Cfg.CommunityID, item.PeerID, string.Format("Пользователь успешно зарегистрирован")); return(null); }
private void _aiService_OnResult(AIResponse response) { System.Diagnostics.Debug.WriteLine("We got a Response from Api.ai"); _mainActivity.RunOnUiThread(() => { if (response.IsError) { if (response.Result != null) { System.Diagnostics.Debug.WriteLine("AIServiceTest: " + response.Result.Action); } else { System.Diagnostics.Debug.WriteLine("AIServiceTest: " + response.Result.Action); } } else { // Send Close Message to PopUpPage //SendClosePopUp(); var result = response.Result; string json = JsonConvert.SerializeObject(result); SendResults(json); } }); }
private void OutputParams(AIResponse aiResponse) { var contextsParams = new Dictionary <string, string>(); if (aiResponse.Result?.Contexts != null) { foreach (var context in aiResponse.Result?.Contexts) { if (context.Parameters != null) { foreach (var parameter in context.Parameters) { if (!contextsParams.ContainsKey(parameter.Key)) { contextsParams.Add(parameter.Key, parameter.Value); } } } } } var resultBuilder = new StringBuilder(); foreach (var contextsParam in contextsParams) { resultBuilder.AppendLine(contextsParam.Key + ": " + contextsParam.Value); } parametersTextBlock.Text = resultBuilder.ToString(); }
public async Task ProcessIntent(AIResponse aIResponse) { AccessToken accessToken = await _tokenManager.GetAccessTokenFromCache().ConfigureAwait(false); _lineMessagingClient = new LineMessagingClient(accessToken.access_token); var app = new LineBotApp(_lineMessagingClient); // try case IntentName to IntentType Enum IntentType intentType = IntentType.Unknown; if (Enum.TryParse <IntentType>(aIResponse.Result.Metadata.IntentName, out intentType)) { aIResponse.Result.Metadata.IntentType = intentType; } Event tempEvent = new Event(); switch (aIResponse.Result.Metadata.IntentType) { case IntentType.ButtonIntent: // Down Cast tempEvent = aIResponse.OriginalRequest.Event; MessageEvent messageEventTemp = (MessageEvent)tempEvent; TextEventMessage eventMessageTemp = (TextEventMessage)messageEventTemp.Message; eventMessageTemp.Text = "buttons"; break; default: break; } await app.RunAsync(new List <WebhookEvent>(){ (WebhookEvent)tempEvent }); }
public void OnMessage(IBot bot, Message message) { if (bot == null || message == null) { throw new ArgumentException(); } AIResponse aiResponse = _aiService.TextRequest(message.Text); if (aiResponse.Result.Action == Data.BotAction.InputUnknown) { throw new UnrecognizableIntentException(); } IAction action = MapAiResponse(aiResponse); action.Message = message; IActionController actionController = GetActionController(action); IActionResponse actionResponse = actionController?.Handle(action); IActionResponseController actionResponseController = GetActionResponseController(actionResponse); actionResponseController?.HandleAsync(bot, actionResponse); }
public override void OnTick(IBoardState[] data) { //Spend all tokens //Spawn in each lane otherwise attack or move int maxCycles = 99; while (AIResponse.Tokens > 0 && maxCycles > 0) //Spend all tokens { maxCycles--; if (Random.Range(0, 2) == 0 || _Creatures.Count == 0) { int randomLane = Random.Range(1, TournamentManager._instance.lanes.Count + 1); // LogStack.Log ("Random Spawn Lane " + randomLane, LogLevel.System); if (!AIResponse.Spawn(Random.Range(0, 2) == 0 ? Spawnable.Bunny : Spawnable.Unicorn, randomLane)) { if (_Creatures.Count > 0) { CreatureBase randomCreature = _Creatures[Random.Range(0, _Creatures.Count)]; AttemptMoveAttack(randomCreature); } } } else if (_Creatures.Count > 0) { CreatureBase randomCreature = _Creatures[Random.Range(0, _Creatures.Count)]; AttemptMoveAttack(randomCreature); } } AIResponse.FinalizeResponse(); }
public IEnumerator AsyncDialogflowCall(string textRequest) { Task <AIResponse> nluCAll = Task.Run <AIResponse>(() => apiAiUnity.TextRequest(textRequest)); //Warte bis Anfrage beendet wurde while (!nluCAll.IsCompleted) { yield return(null); } AIResponse response = nluCAll.Result; if (response != null) { //Debug.Log("Resolved query: " + response.Result.ResolvedQuery); //Debug.Log(response.Result.Metadata.IntentName); //var outText = fastJSON.JSON.ToJSON(response); var outText = NewJSon::Newtonsoft.Json.JsonConvert.SerializeObject(response, jsonSettings); Debug.Log("Result: " + outText); } else { Debug.LogError("Response is null"); } Debug.Log("Trigger NLUAnswerDetected Event"); EventManager.TriggerEvent(EventManager.nluAnswerDetectedEvent, new EventMessageObject(EventManager.nluAnswerDetectedEvent, response)); }
public void SendText() { //var text = SelectionSlider.speak; var text = lines[compteur]; compteur++; //Debug.Log(text); AIResponse response = apiAiUnity.TextRequest(text); if (response != null) { Debug.Log(response.Result.Fulfillment.Speech); FindObjectOfType <TextToSpeech>().Speak(reponses[compteura]); compteura++; text = response.Result.Fulfillment.Speech; //FindObjectOfType<TextToSpeech>().Speak(text); /*if(SelectionSlider.speak.ToLower().Contains("presentation")) * { * StartCoroutine(FinalScore(text)); * }*/ } else { Debug.LogError("Response is null"); } }
public void SendText() { var text = inputTextField.text; Debug.Log(text); AIResponse response = apiAiUnity.TextRequest(text); if (response != null) { Debug.Log("Resolved query: " + response.Result.ResolvedQuery); var outText = JsonConvert.SerializeObject(response, jsonSettings); var pattern = @"speech"":""(.+?)"""; var match = Regex.Match(outText, pattern); Debug.Log("Result: " + match.Groups[1]); answerTextField.text = match.Groups[1].ToString(); tryToDoAction(match.Groups[1].ToString()); } else { Debug.LogError("Response is null"); } }
private void SpawnEnemy() { // Round robin spawning if (_lanetospawn > 3) { _lanetospawn = 1; } if (_lastSpawned == Spawnable.Unicorn) { if (AIResponse.Spawn(Spawnable.Bunny, _lanetospawn)) { _lastSpawned = Spawnable.Bunny; } } else if (_lastSpawned == Spawnable.Bunny) { if (AIResponse.Spawn(Spawnable.Unicorn, _lanetospawn)) { _lastSpawned = Spawnable.Unicorn; } } _lanetospawn++; }
public AiResponseExtract ProcessUserRequest(Conversation conversation, UserRequest userRequest) { AiResponseExtract response = new AiResponseExtract(); AIRequest aiRequest = new AIRequest(userRequest.Body); AIContext aiContext = new AIContext() { Name = conversation.CurrentMessage.Name }; aiRequest.Contexts = new List <AIContext>() { aiContext }; AIResponse aiResponse = apiAi.TextRequest(aiRequest); response.Intent = aiResponse.Result.Action; if (aiResponse.Result.Action.Contains("smalltalk")) { response.SmallTalk = true; } response.Speech = aiResponse.Result.Fulfillment.Speech; return(response); }
static void HandleResponse(AIResponse response) { try { if (response.IsError) { throw new Exception($"Details: {response.Status.ErrorDetails}, ErrorID: {response.Status.ErrorID}, ErrorType: {response.Status.ErrorType}, Code: {response.Status.Code}"); } if (!string.IsNullOrEmpty(response.Result.Fulfillment.Speech)) { Console.WriteLine($"bot: {response.Result.Fulfillment.Speech}"); } if (string.IsNullOrEmpty(response.Result.Action) && string.IsNullOrEmpty(response.Result.Fulfillment.Speech)) { Console.WriteLine($"bot: estou meio confuso!"); } if (!string.IsNullOrEmpty(response.Result.Action) && string.IsNullOrEmpty(response.Result.Fulfillment.Speech)) { HandleAction(response); } Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(response)); Console.ResetColor(); } catch (Exception ex) { Console.WriteLine($"bot: vixeeeeeee, algo deu errado: {ex.Message}"); } WaitText(); }
public AIResponse TextRequest(AIRequest request) { AIResponse aiResponse = new AIResponse(); string model = RasaRequestExtension.GetModelPerContexts(agent, AiConfig, request, dc); var result = CallRasa(agent.Id, request.Query.First(), model); result.Content.Log(); RasaResponse response = result.Data; aiResponse.Id = Guid.NewGuid().ToString(); aiResponse.Lang = agent.Language; aiResponse.Status = new AIResponseStatus { }; aiResponse.SessionId = AiConfig.SessionId; aiResponse.Timestamp = DateTime.UtcNow; var intentResponse = RasaRequestExtension.HandleIntentPerContextIn(agent, AiConfig, request, result.Data, dc); RasaRequestExtension.HandleParameter(agent, intentResponse, response, request); RasaRequestExtension.HandleMessage(intentResponse); aiResponse.Result = new AIResponseResult { Source = "agent", ResolvedQuery = request.Query.First(), Action = intentResponse?.Action, Parameters = intentResponse?.Parameters?.ToDictionary(x => x.Name, x => (object)x.Value), Score = response.Intent.Confidence, Metadata = new AIResponseMetadata { IntentId = intentResponse?.IntentId, IntentName = intentResponse?.IntentName }, Fulfillment = new AIResponseFulfillment { Messages = intentResponse?.Messages?.Select(x => { if (x.Type == AIResponseMessageType.Custom) { return((new { x.Type, Payload = JsonConvert.DeserializeObject(x.PayloadJson) }) as Object); } else { return((new { x.Type, x.Speech }) as Object); } }).ToList() } }; RasaRequestExtension.HandleContext(dc, AiConfig, intentResponse, aiResponse); Console.WriteLine(JsonConvert.SerializeObject(aiResponse.Result)); return(aiResponse); }
public override void OnTick(IBoardState[] data) { if (!AIResponse.Spawn(Spawnable.Unicorn, 1)) { } //IResponse[] responses = AIResponse.QueryResponse(); AIResponse.FinalizeResponse(); }
public void Map_WhenCalled_ShouldReturnGymStateActionWithName() { AIResponse aiResponse = MakeAIResponse(); var action = _gymStateMapping.Map(aiResponse); Assert.Equal(BotAction.GymStateRequest, action.Name); }
public void Map_WhenCalled_ShouldReturnGymStateAction() { AIResponse aiResponse = MakeAIResponse(); var action = _gymStateMapping.Map(aiResponse); Assert.IsType <GymStateAction>(action); }
/// <summary> /// Вывод пользователю инструкции по боту /// </summary> /// <param name="item"></param> /// <param name="response"></param> /// <returns></returns> public BotState?SendHelp(VK.UserLongPoll.Update item, AIResponse response) { // Вывод сообщения api.Messages_SendMessage(Program.Cfg.CommunityID, item.PeerID, "Вот команды: \n" + "1) Регистрация - введите свой email, чтобы я Вас запомнил\n" + "2) Отметиться - я запишу, что вы присутствовали на занятии, которое идет в данный момент\n" + "3) Создать лекцию - провести лекцию (только для администраторов!)"); return(null); }
public IActionResult Index() { using (var streamReader = new StreamReader(Request.Body)) { AIResponse response = JsonConvert.DeserializeObject <AIResponse>(streamReader.ReadToEnd()); } return(Json("Web Hook Controller Index")); }
static void HandleAction(AIResponse response) { switch (response.Result.Action) { case "wisdom.person": Console.WriteLine($"sei la quem é {response.Result.GetStringParameter("q")}"); break; } }
private void FireOnResult(AIResponse aiResponse) { var onResult = OnResult; if (onResult != null) { onResult(this, new AIResponseEventArgs(aiResponse)); } }
private bool TokenCheck() { if (AIResponse.Tokens <= 0) { AIResponse.FinalizeResponse(); return(false); } return(true); }
// --- constructors --- /// <summary>Creates a new instance of this class.</summary> /// <param name="handles">The driver handles.</param> public AIData(Handles handles) { this.MyHandles = handles; this.MyResponse = AIResponse.None; }