beh.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package tg
  2. // The package implements
  3. // behaviour for the Telegram bots.
  4. // The type describes behaviour for the bot in personal chats.
  5. type Behaviour struct {
  6. Root Component
  7. Init Action
  8. Screens ScreenMap
  9. }
  10. // Returns new empty behaviour.
  11. func NewBehaviour() *Behaviour {
  12. return &Behaviour{
  13. Screens: make(ScreenMap),
  14. }
  15. }
  16. // The Action will be called on session creation,
  17. // not when starting or restarting the bot with the Start Action.
  18. func (b *Behaviour) WithInit(a Action) *Behaviour {
  19. b.Init = a
  20. return b
  21. }
  22. // Alias to WithInit to simplify behaviour definitions.
  23. func (b *Behaviour) WithInitFunc(
  24. fn ActionFunc,
  25. ) *Behaviour {
  26. return b.WithInit(fn)
  27. }
  28. func (b *Behaviour) WithRootNode(node *RootNode) *Behaviour {
  29. b.Screens = node.ScreenMap()
  30. return b
  31. }
  32. // The function sets screens.
  33. /*func (b *Behaviour) WithScreens(
  34. screens ...*Screen,
  35. ) *Behaviour {
  36. for _, screen := range screens {
  37. if screen.Id == "" {
  38. panic("empty screen ID")
  39. }
  40. _, ok := b.Screens[screen.Id]
  41. if ok {
  42. panic("duplicate keyboard IDs")
  43. }
  44. b.Screens[screen.Id] = screen
  45. }
  46. return b
  47. }*/
  48. // The function sets as the standard root widget CommandWidget
  49. // and its commands..
  50. func (b *Behaviour) WithRoot(root Component) *Behaviour {
  51. b.Root = root
  52. return b
  53. }
  54. // Check whether the screen exists in the behaviour.
  55. func (beh *Behaviour) PathExist(pth Path) bool {
  56. _, ok := beh.Screens[pth]
  57. return ok
  58. }
  59. // Returns the screen by it's ID.
  60. func (beh *Behaviour) GetScreen(pth Path) *Screen {
  61. pth = pth.Clean()
  62. if !beh.PathExist(pth) {
  63. panic(ScreenNotExistErr)
  64. }
  65. screen := beh.Screens[pth]
  66. return screen
  67. }