TelegramController.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Http\Controllers\Guest;
  3. use App\Services\TelegramService;
  4. use App\Services\UserService;
  5. use Illuminate\Http\Request;
  6. use App\Http\Controllers\Controller;
  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. $token = parse_str($subscribeUrl['query'])['token'];
  47. if (!$token) {
  48. abort(500, '订阅地址无效');
  49. }
  50. $user = User::where('token', $token)->first();
  51. if (!$user) {
  52. abort(500, '用户不存在');
  53. }
  54. $user->telegram_id = $msg->chat_id;
  55. if (!$user->save()) {
  56. abort(500, '设置失败');
  57. }
  58. $telegramService = new TelegramService();
  59. $telegramService->sendMessage($msg->chat_id, '绑定成功');
  60. }
  61. }