You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.5 KiB

1 year ago
  1. <?php
  2. /**
  3. * This file is part of the PHP Telegram Bot example-bot package.
  4. * https://github.com/php-telegram-bot/example-bot/
  5. *
  6. * (c) PHP Telegram Bot Team
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /**
  12. * User "/cancel" command
  13. *
  14. * This command cancels the currently active conversation and
  15. * returns a message to let the user know which conversation it was.
  16. *
  17. * If no conversation is active, the returned message says so.
  18. */
  19. namespace Longman\TelegramBot\Commands\UserCommands;
  20. use Longman\TelegramBot\Commands\UserCommand;
  21. use Longman\TelegramBot\Conversation;
  22. use Longman\TelegramBot\Entities\Keyboard;
  23. use Longman\TelegramBot\Entities\ServerResponse;
  24. use Longman\TelegramBot\Exception\TelegramException;
  25. class CancelCommand extends UserCommand
  26. {
  27. /**
  28. * @var string
  29. */
  30. protected $name = 'cancel';
  31. /**
  32. * @var string
  33. */
  34. protected $description = 'Cancel the currently active conversation';
  35. /**
  36. * @var string
  37. */
  38. protected $usage = '/cancel';
  39. /**
  40. * @var string
  41. */
  42. protected $version = '0.3.0';
  43. /**
  44. * @var bool
  45. */
  46. protected $need_mysql = true;
  47. /**
  48. * Main command execution if no DB connection is available
  49. *
  50. * @throws TelegramException
  51. */
  52. public function executeNoDb(): ServerResponse
  53. {
  54. return $this->removeKeyboard('Nothing to cancel.');
  55. }
  56. /**
  57. * Main command execution
  58. *
  59. * @return ServerResponse
  60. * @throws TelegramException
  61. */
  62. public function execute(): ServerResponse
  63. {
  64. $text = 'No active conversation!';
  65. // Cancel current conversation if any
  66. $conversation = new Conversation(
  67. $this->getMessage()->getFrom()->getId(),
  68. $this->getMessage()->getChat()->getId()
  69. );
  70. if ($conversation_command = $conversation->getCommand()) {
  71. $conversation->cancel();
  72. $text = 'Conversation "' . $conversation_command . '" cancelled!';
  73. }
  74. return $this->removeKeyboard($text);
  75. }
  76. /**
  77. * Remove the keyboard and output a text.
  78. *
  79. * @param string $text
  80. *
  81. * @return ServerResponse
  82. * @throws TelegramException
  83. */
  84. private function removeKeyboard(string $text): ServerResponse
  85. {
  86. return $this->replyToChat($text, [
  87. 'reply_markup' => Keyboard::remove(['selective' => true]),
  88. ]);
  89. }
  90. }