SimpleStringEntityHandler.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System;
  9. using Meta.WitAi.Json;
  10. using UnityEngine;
  11. using UnityEngine.Events;
  12. namespace Meta.WitAi.CallbackHandlers
  13. {
  14. [AddComponentMenu("Wit.ai/Response Matchers/Simple String Entity Handler")]
  15. public class SimpleStringEntityHandler : WitIntentMatcher
  16. {
  17. [SerializeField] public string entity;
  18. [SerializeField] public string format;
  19. [SerializeField] private StringEntityMatchEvent onIntentEntityTriggered
  20. = new StringEntityMatchEvent();
  21. public StringEntityMatchEvent OnIntentEntityTriggered => onIntentEntityTriggered;
  22. protected override string OnValidateResponse(WitResponseNode response, bool isEarlyResponse)
  23. {
  24. // Return base
  25. string result = base.OnValidateResponse(response, isEarlyResponse);
  26. if (!string.IsNullOrEmpty(result))
  27. {
  28. return result;
  29. }
  30. // Not found
  31. var entityValue = response.GetFirstEntityValue(entity);
  32. if (string.IsNullOrEmpty(entityValue))
  33. {
  34. return $"Missing required entity: {entity}";
  35. }
  36. // Fail
  37. return string.Empty;
  38. }
  39. protected override void OnResponseInvalid(WitResponseNode response, string error) { }
  40. protected override void OnResponseSuccess(WitResponseNode response)
  41. {
  42. var entityValue = response.GetFirstEntityValue(entity);
  43. if (!string.IsNullOrEmpty(format))
  44. {
  45. onIntentEntityTriggered.Invoke(format.Replace("{value}", entityValue));
  46. }
  47. else
  48. {
  49. onIntentEntityTriggered.Invoke(entityValue);
  50. }
  51. }
  52. }
  53. [Serializable]
  54. public class StringEntityMatchEvent : UnityEvent<string> {}
  55. }