TelegramController.php 2.0 KB

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