TelegramController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Http\Controllers\Admin\Config\Test;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Config;
  6. use Telegram\Bot\Api;
  7. class TelegramController extends Controller
  8. {
  9. private Config $configModel;
  10. public function __construct(Config $config)
  11. {
  12. $this->configModel = $config;
  13. }
  14. /**
  15. * 텔레그램 발송 확인
  16. * @method GET
  17. * @see /admin/config/test/telegram
  18. */
  19. public function index()
  20. {
  21. $config = $this->configModel->getAllMeta();
  22. $response = $this->_getResponse($config);
  23. return view('admin.config.test.telegram', [
  24. 'config' => $config,
  25. 'response' => $response->getMe()
  26. ]);
  27. }
  28. /**
  29. * 텔레그램 발송 확인 실행
  30. * @method POST
  31. * @see /admin/config/test/telegram
  32. */
  33. public function store(Request $request)
  34. {
  35. $rules = [
  36. 'g2a_order_bot_token' => 'nullable|string|max:255',
  37. 'g2a_product_bot_token' => 'nullable|string|max:255',
  38. 'g2a_error_bot_token' => 'nullable|string|max:255',
  39. 'main_bot_token' => 'nullable|string|max:255',
  40. 'message' => 'required|string'
  41. ];
  42. $attributes = [
  43. 'g2a_order_bot_token' => 'G2A Order Bot Token',
  44. 'g2a_product_bot_token' => 'G2A Product Bot Token',
  45. 'g2a_error_bot_token' => 'G2A Error Bot Token',
  46. 'main_bot_token' => 'Main Bot Token',
  47. 'message' => '보낼 내용'
  48. ];
  49. $posts = $this->validate($request, $rules, [], $attributes);
  50. $this->configModel->save($posts, $attributes);
  51. $response = $this->_getResponse(
  52. $this->configModel->getAllMeta()
  53. );
  54. if (!$response->getMe()) {
  55. return back()->with('message', '텔레그램 설정이 잘못되었습니다.');
  56. }
  57. $chatID = last($response->getUpdates())->getChat()->get('id');
  58. $response->sendMessage([
  59. 'chat_id' => $chatID,
  60. 'text' => $posts['message']
  61. ]);
  62. $message = '텔레그램 문자를 발송하였습니다.';
  63. return redirect()->route('admin.config.test.telegram.index')->with('message', $message);
  64. }
  65. private function _getResponse(Config $config): Api
  66. {
  67. return new Api(
  68. $config->item('main_bot_token')
  69. );
  70. }
  71. }