TelegramController.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Http\Controllers\Guest;
  3. use App\Services\TelegramService;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. class TelegramController extends Controller
  7. {
  8. protected $msg;
  9. protected $commands = [];
  10. public function __construct(Request $request)
  11. {
  12. if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) {
  13. abort(401);
  14. }
  15. }
  16. public function webhook(Request $request)
  17. {
  18. $this->msg = $this->getMessage($request->input());
  19. if (!$this->msg) return;
  20. $this->handle();
  21. }
  22. public function handle()
  23. {
  24. $msg = $this->msg;
  25. try {
  26. foreach (glob(base_path('app//Plugins//Telegram//Commands') . '/*.php') as $file) {
  27. $command = basename($file, '.php');
  28. $class = '\\App\\Plugins\\Telegram\\Commands\\' . $command;
  29. if (!class_exists($class)) continue;
  30. $instance = new $class();
  31. if ($msg->message_type === 'message') {
  32. if (!isset($instance->command)) continue;
  33. if ($msg->command !== $instance->command) continue;
  34. $instance->handle($msg);
  35. return;
  36. }
  37. if ($msg->message_type === 'reply_message') {
  38. if (!isset($instance->regex)) continue;
  39. if (!preg_match($instance->regex, $msg->reply_text, $match)) continue;
  40. $instance->handle($msg, $match);
  41. return;
  42. }
  43. }
  44. } catch (\Exception $e) {
  45. $telegramService = new TelegramService();
  46. $telegramService->sendMessage($msg->chat_id, $e->getMessage());
  47. }
  48. }
  49. private function getMessage(array $data)
  50. {
  51. if (!isset($data['message'])) return false;
  52. $obj = new \StdClass();
  53. if (!isset($data['message']['text'])) return false;
  54. $text = explode(' ', $data['message']['text']);
  55. $obj->command = $text[0];
  56. $obj->args = array_slice($text, 1);
  57. $obj->chat_id = $data['message']['chat']['id'];
  58. $obj->message_id = $data['message']['message_id'];
  59. $obj->message_type = !isset($data['message']['reply_to_message']['text']) ? 'message' : 'reply_message';
  60. $obj->text = $data['message']['text'];
  61. $obj->is_private = $data['message']['chat']['type'] === 'private';
  62. if ($obj->message_type === 'reply_message') {
  63. $obj->reply_text = $data['message']['reply_to_message']['text'];
  64. }
  65. return $obj;
  66. }
  67. }