TelegramController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. use App\Models\User;
  7. class TelegramController extends Controller
  8. {
  9. protected $msg;
  10. public function __construct(Request $request)
  11. {
  12. if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) {
  13. abort(500, 'authentication failed');
  14. }
  15. }
  16. public function webhook(Request $request)
  17. {
  18. $this->msg = $this->getMessage($request->input());
  19. if (!$this->msg) return;
  20. try {
  21. switch($this->msg->command) {
  22. case '/bind': $this->bind();
  23. break;
  24. default: $this->help();
  25. }
  26. } catch (\Exception $e) {
  27. $telegramService = new TelegramService();
  28. $telegramService->sendMessage($this->msg->chat_id, $e->getMessage());
  29. }
  30. }
  31. private function getMessage(array $data)
  32. {
  33. if (!$data['message']) return false;
  34. $obj = new \StdClass();
  35. $obj->is_private = $data['message']['chat']['type'] === 'private' ? true : false;
  36. $text = explode(' ', $data['message']['text']);
  37. $obj->command = $text[0];
  38. $obj->args = array_slice($text, 1);
  39. $obj->chat_id = $data['message']['chat']['id'];
  40. $obj->message_id = $data['message']['message_id'];
  41. return $obj;
  42. }
  43. private function bind()
  44. {
  45. $msg = $this->msg;
  46. if (!$msg->is_private) return;
  47. $subscribeUrl = $msg->args[0];
  48. $subscribeUrl = parse_url($subscribeUrl);
  49. parse_str($subscribeUrl['query'], $query);
  50. $token = $query['token'];
  51. if (!$token) {
  52. abort(500, '订阅地址无效');
  53. }
  54. $user = User::where('token', $token)->first();
  55. if (!$user) {
  56. abort(500, '用户不存在');
  57. }
  58. $user->telegram_id = $msg->chat_id;
  59. if (!$user->save()) {
  60. abort(500, '设置失败');
  61. }
  62. $telegramService = new TelegramService();
  63. $telegramService->sendMessage($msg->chat_id, '绑定成功');
  64. }
  65. private function help()
  66. {
  67. $msg = $this->msg;
  68. if (!$msg->is_private) return;
  69. $telegramService = new TelegramService();
  70. $telegramService->sendMessage($msg->chat_id, "
  71. 绑定账号\r\n
  72. ------------------------\r\n
  73. 发送:/bind 订阅地址
  74. ");
  75. }
  76. }