From 8e92d8d4735c442365399983459bf4bd179e81ef Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 2 Aug 2023 00:46:36 +0700 Subject: [PATCH 01/16] (#30) update notify and enable events action in setting --- common/helpers.php | 2 +- src/Models/Setting.php | 14 +++++++++++++- src/Services/EventService.php | 14 +++++++++++++- src/Services/SettingService.php | 13 +++++++------ 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/common/helpers.php b/common/helpers.php index 2397104..ed8e069 100644 --- a/common/helpers.php +++ b/common/helpers.php @@ -103,7 +103,7 @@ function event_config(): array */ function all_events_notify(): bool { - return (new Setting())->allEventsNotify(); + return (new Setting())->allEventsNotifyStatus(); } } diff --git a/src/Models/Setting.php b/src/Models/Setting.php index a12dc48..6bec11b 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -39,7 +39,7 @@ public function getSettingConfig(): array /** * @return bool */ - public function allEventsNotify(): bool + public function allEventsNotifyStatus(): bool { if (!empty($this->settings) && $this->settings['all_events_notify'] === true) { return true; @@ -47,4 +47,16 @@ public function allEventsNotify(): bool return false; } + + /** + * @return bool + */ + public function isNotified(): bool + { + if (!empty($this->settings) && $this->settings['is_notified'] === true) { + return true; + } + + return false; + } } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 6964a49..263e550 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -3,9 +3,17 @@ namespace TelegramGithubNotify\App\Services; use Symfony\Component\HttpFoundation\Request; +use TelegramGithubNotify\App\Models\Setting; class EventService { + protected Setting $setting; + + public function __construct() + { + $this->setting = new Setting(); + } + /** * Validate access event before send notify * @@ -15,7 +23,11 @@ class EventService */ public function validateAccessEvent(Request $request, $payload): bool { - if (all_events_notify()) { + if (!$this->setting->isNotified()) { + return false; + } + + if ($this->setting->allEventsNotifyStatus()) { return true; } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 2efd0f8..2e8c967 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -16,21 +16,22 @@ public function __construct() $this->setting = new Setting(); $this->settingConfig = $this->setting->getSettingConfig(); } + /** * @return void */ public function settingHandle(): void { if ($this->settingConfig['is_notified']) { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('❌ Notification', '', 'setting.is_notified'); + $notificationSetting = $this->telegram->buildInlineKeyBoardButton('✅ Github notification', '', 'setting.is_notified'); } else { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('✅ Notification', '', 'setting.is_notified'); + $notificationSetting = $this->telegram->buildInlineKeyBoardButton('Github notification', '', 'setting.is_notified'); } if ($this->settingConfig['all_events_notify']) { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('🔕 All Events Notify', '', 'setting.all_events_notify'); + $eventSetting = $this->telegram->buildInlineKeyBoardButton('✅ Enable All Events Notify', '', 'setting.all_events_notify'); } else { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('🔔 All Events Notify', '', 'setting.all_events_notify'); + $eventSetting = $this->telegram->buildInlineKeyBoardButton('Enable All Events Notify', '', 'setting.all_events_notify'); } $keyboard = [ @@ -38,9 +39,9 @@ public function settingHandle(): void $notificationSetting, ], [ $eventSetting, - $this->telegram->buildInlineKeyBoardButton('Custom individual events', '', 'setting.custom_events'), + $this->telegram->buildInlineKeyBoardButton('➡ Custom individual events', '', 'setting.custom_events'), ], [ - $this->telegram->buildInlineKeyBoardButton('🔙 Back', '', 'back.menu'), + $this->telegram->buildInlineKeyBoardButton('🔙 Back to menu', '', 'back.menu'), ] ]; From 24c060d42b1f3450623ff1977d6814cd09cbeee2 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 2 Aug 2023 16:50:48 +0700 Subject: [PATCH 02/16] (#30) clean and optimize code --- src/Http/Actions/SendNotifyAction.php | 14 +++++++------- src/Models/Setting.php | 5 +++++ src/Services/NotificationService.php | 20 +++++++++----------- src/Services/SettingService.php | 20 ++++++++++---------- src/Services/TelegramService.php | 15 +++++++-------- 5 files changed, 38 insertions(+), 36 deletions(-) diff --git a/src/Http/Actions/SendNotifyAction.php b/src/Http/Actions/SendNotifyAction.php index 14ea2c2..b4f6fdc 100644 --- a/src/Http/Actions/SendNotifyAction.php +++ b/src/Http/Actions/SendNotifyAction.php @@ -36,19 +36,19 @@ public function __construct() */ public function __invoke(): void { - $chatMessageId = $this->telegramService->messageData['message']['chat']['id'] ?? ''; - - if (!empty($chatMessageId)) { - $this->handleEventInTelegram($chatMessageId); - return; - } - // Send a GitHub event result to all chat ids in env if (!is_null($this->request->server->get('HTTP_X_GITHUB_EVENT'))) { $this->sendNotification(); return; } + // Telegram bot handler + $chatMessageId = $this->telegramService->messageData['message']['chat']['id'] ?? ''; + if (!empty($chatMessageId)) { + $this->handleEventInTelegram($chatMessageId); + return; + } + $this->telegramService->checkCallback(); } diff --git a/src/Models/Setting.php b/src/Models/Setting.php index 6bec11b..aed5a59 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -5,6 +5,11 @@ class Setting { public const SETTING_FILE = __DIR__ . '/../../storage/tg-setting.json'; + public const SETTING_PREFIX = 'setting.'; + + public const SETTING_IS_NOTIFIED = self::SETTING_PREFIX . 'is_notified'; + public const SETTING_ALL_EVENTS_NOTIFY = self::SETTING_PREFIX . 'all_events_notify'; + public const SETTING_CUSTOM_EVENTS = self::SETTING_PREFIX . 'custom_events'; public array $settings = []; diff --git a/src/Services/NotificationService.php b/src/Services/NotificationService.php index 5ed73fb..3d8f63b 100644 --- a/src/Services/NotificationService.php +++ b/src/Services/NotificationService.php @@ -21,14 +21,12 @@ class NotificationService */ public function accessDenied(TelegramService $telegramService, string $chatId = null): void { - $reply = view('globals.access_denied', ['chatId' => $chatId]); - $content = array( + $telegramService->telegram->sendMessage([ 'chat_id' => config('telegram-bot.chat_id'), - 'text' => $reply, + 'text' => view('globals.access_denied', ['chatId' => $chatId]), 'disable_web_page_preview' => true, 'parse_mode' => 'HTML' - ); - $telegramService->telegram->sendMessage($content); + ]); } /** @@ -39,14 +37,14 @@ public function accessDenied(TelegramService $telegramService, string $chatId = */ public function setPayload(Request $request) { - $this->payload = json_decode($request->request->get('payload')); if (is_null($request->server->get('HTTP_X_GITHUB_EVENT'))) { echo 'invalid request'; exit; - } else { - $this->setMessage($request->server->get('HTTP_X_GITHUB_EVENT')); } + $this->payload = json_decode($request->request->get('payload')); + $this->setMessage($request->server->get('HTTP_X_GITHUB_EVENT')); + return $this->payload; } @@ -96,10 +94,10 @@ public function sendNotify(string $chatId, string $message = null): bool if ($response->getStatusCode() === 200) { return true; } - - return false; } catch (GuzzleException $e) { - return false; + error_log($e->getMessage()); } + + return false; } } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 2e8c967..e2e9985 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -23,15 +23,15 @@ public function __construct() public function settingHandle(): void { if ($this->settingConfig['is_notified']) { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('✅ Github notification', '', 'setting.is_notified'); + $notificationSetting = $this->telegram->buildInlineKeyBoardButton('✅ Github notification', '', $this->setting::SETTING_IS_NOTIFIED); } else { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('Github notification', '', 'setting.is_notified'); + $notificationSetting = $this->telegram->buildInlineKeyBoardButton('Github notification', '', $this->setting::SETTING_IS_NOTIFIED); } if ($this->settingConfig['all_events_notify']) { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('✅ Enable All Events Notify', '', 'setting.all_events_notify'); + $eventSetting = $this->telegram->buildInlineKeyBoardButton('✅ Enable All Events Notify', '', $this->setting::SETTING_ALL_EVENTS_NOTIFY); } else { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('Enable All Events Notify', '', 'setting.all_events_notify'); + $eventSetting = $this->telegram->buildInlineKeyBoardButton('Enable All Events Notify', '', $this->setting::SETTING_ALL_EVENTS_NOTIFY); } $keyboard = [ @@ -39,7 +39,7 @@ public function settingHandle(): void $notificationSetting, ], [ $eventSetting, - $this->telegram->buildInlineKeyBoardButton('➡ Custom individual events', '', 'setting.custom_events'), + $this->telegram->buildInlineKeyBoardButton('⚙ Custom individual events', '', $this->setting::SETTING_CUSTOM_EVENTS), ], [ $this->telegram->buildInlineKeyBoardButton('🔙 Back to menu', '', 'back.menu'), ] @@ -54,12 +54,12 @@ public function settingHandle(): void */ public function settingCallbackHandler(string $callback): void { - if ($callback === 'setting.custom_events') { + if ($callback === $this->setting::SETTING_CUSTOM_EVENTS) { (new EventService())->eventHandle(); return; } - $callback = str_replace('setting.', '', $callback); + $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); $this->updateSetting($callback, !$this->settingConfig[$callback]); $this->settingHandle(); @@ -98,9 +98,9 @@ public function updateSetting(string $settingName, $settingValue = null): bool */ private function saveSettingsToFile(): bool { - $json = json_encode($this->settingConfig, JSON_PRETTY_PRINT); - if (file_exists(Setting::SETTING_FILE)) { - file_put_contents(Setting::SETTING_FILE, $json, LOCK_EX); + if (file_exists($this->setting::SETTING_FILE)) { + $json = json_encode($this->settingConfig, JSON_PRETTY_PRINT); + file_put_contents($this->setting::SETTING_FILE, $json, LOCK_EX); return true; } diff --git a/src/Services/TelegramService.php b/src/Services/TelegramService.php index 77b84c2..9c09773 100644 --- a/src/Services/TelegramService.php +++ b/src/Services/TelegramService.php @@ -2,6 +2,8 @@ namespace TelegramGithubNotify\App\Services; +use TelegramGithubNotify\App\Models\Setting; + class TelegramService extends AppService { public array $messageData; @@ -59,14 +61,12 @@ protected function sendCallbackResponse(string $callback = null): void } if ($callback === 'about') { - $reply = view('tools.about'); - $content = array( + $this->telegram->answerCallbackQuery([ 'callback_query_id' => $this->telegram->Callback_ID(), - 'text' => $reply, + 'text' => view('tools.about'), 'show_alert' => true - ); - $this->telegram->answerCallbackQuery($content); - } elseif (str_contains($callback, 'setting.')) { + ]); + } elseif (str_contains($callback, Setting::SETTING_PREFIX)) { $this->settingService->settingCallbackHandler($callback); } } @@ -79,8 +79,7 @@ protected function sendCallbackResponse(string $callback = null): void public function checkCallback(): bool { if (!is_null($this->telegram->Callback_ChatID())) { - $callback = $this->telegram->Callback_Data(); - $this->sendCallbackResponse($callback); + $this->sendCallbackResponse($this->telegram->Callback_Data()); return true; } return false; From e7d950c074967a4135de25e92224ce9c73f4af13 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 2 Aug 2023 22:57:27 +0700 Subject: [PATCH 03/16] (#30) update answer callback queries --- src/Models/Event.php | 2 ++ src/Services/AppService.php | 19 ++++++++++ src/Services/EventService.php | 10 ++++-- src/Services/SettingService.php | 59 ++++++++++++++++++++------------ src/Services/TelegramService.php | 6 +--- 5 files changed, 68 insertions(+), 28 deletions(-) diff --git a/src/Models/Event.php b/src/Models/Event.php index 6ccad3e..43195a2 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -6,6 +6,8 @@ class Event { public const EVENT_FILE = __DIR__ . '/../../storage/tg-event.json'; + public const EVENT_PREFIX = Setting::SETTING_PREFIX . '.event.'; + public array $eventConfig = []; public function __construct() diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 0544071..e0bfc28 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -47,4 +47,23 @@ public function sendMessage(string $message = '', array $options = [], string $s error_log($e->getMessage()); } } + + /** + * Send callback response to telegram (show alert) + * + * @param string|null $text + * @return void + */ + public function answerCallbackQuery(string $text = null): void + { + try { + $this->telegram->answerCallbackQuery([ + 'callback_query_id' => $this->telegram->Callback_ID(), + 'text' => $text, + 'show_alert' => true + ]); + } catch (Exception $e) { + error_log($e->getMessage()); + } + } } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 263e550..e797524 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -3,15 +3,21 @@ namespace TelegramGithubNotify\App\Services; use Symfony\Component\HttpFoundation\Request; +use TelegramGithubNotify\App\Models\Event; use TelegramGithubNotify\App\Models\Setting; -class EventService +class EventService extends AppService { protected Setting $setting; + protected Event $event; + public function __construct() { + parent::__construct(); + $this->setting = new Setting(); + $this->event = new Event(); } /** @@ -31,7 +37,7 @@ public function validateAccessEvent(Request $request, $payload): bool return true; } - $eventConfig = event_config(); + $eventConfig = $this->event->getEventConfig(); $event = singularity($request->server->get('HTTP_X_GITHUB_EVENT')); $eventConfig = $eventConfig[$event] ?? false; diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index e2e9985..850eba9 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -22,30 +22,44 @@ public function __construct() */ public function settingHandle(): void { - if ($this->settingConfig['is_notified']) { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('✅ Github notification', '', $this->setting::SETTING_IS_NOTIFIED); - } else { - $notificationSetting = $this->telegram->buildInlineKeyBoardButton('Github notification', '', $this->setting::SETTING_IS_NOTIFIED); - } - - if ($this->settingConfig['all_events_notify']) { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('✅ Enable All Events Notify', '', $this->setting::SETTING_ALL_EVENTS_NOTIFY); - } else { - $eventSetting = $this->telegram->buildInlineKeyBoardButton('Enable All Events Notify', '', $this->setting::SETTING_ALL_EVENTS_NOTIFY); - } + $this->sendMessage(view('tools.settings'), $this->settingMarkup()); + } + public function settingMarkup(): array + { $keyboard = [ [ - $notificationSetting, - ], [ - $eventSetting, - $this->telegram->buildInlineKeyBoardButton('⚙ Custom individual events', '', $this->setting::SETTING_CUSTOM_EVENTS), - ], [ - $this->telegram->buildInlineKeyBoardButton('🔙 Back to menu', '', 'back.menu'), + $this->telegram->buildInlineKeyBoardButton( + $this->settingConfig['is_notified'] + ? '✅ Github notification' : 'Github notification', + '', + $this->setting::SETTING_IS_NOTIFIED + ), + ], + [ + $this->telegram->buildInlineKeyBoardButton( + $this->settingConfig['all_events_notify'] + ? '✅ Enable All Events Notify' + : 'Enable All Events Notify', + '', + $this->setting::SETTING_ALL_EVENTS_NOTIFY + ), + $this->telegram->buildInlineKeyBoardButton( + '⚙ Custom individual events', + '', + $this->setting::SETTING_CUSTOM_EVENTS + ), + ], + [ + $this->telegram->buildInlineKeyBoardButton( + '🔙 Back to menu', + '', + $this->setting::SETTING_PREFIX . '.back.menu' + ), ] ]; - $this->sendMessage(view('tools.settings'), ['reply_markup' => $keyboard]); + return ['reply_markup' => $keyboard]; } /** @@ -61,8 +75,11 @@ public function settingCallbackHandler(string $callback): void $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); - $this->updateSetting($callback, !$this->settingConfig[$callback]); - $this->settingHandle(); + if ($this->updateSettingItem($callback, !$this->settingConfig[$callback])) { + $this->settingHandle(); + } else { + $this->answerCallbackQuery('Something went wrong!'); + } } /** @@ -70,7 +87,7 @@ public function settingCallbackHandler(string $callback): void * @param $settingValue * @return bool */ - public function updateSetting(string $settingName, $settingValue = null): bool + public function updateSettingItem(string $settingName, $settingValue = null): bool { $keys = explode('.', $settingName); $lastKey = array_pop($keys); diff --git a/src/Services/TelegramService.php b/src/Services/TelegramService.php index 9c09773..457f6e7 100644 --- a/src/Services/TelegramService.php +++ b/src/Services/TelegramService.php @@ -61,11 +61,7 @@ protected function sendCallbackResponse(string $callback = null): void } if ($callback === 'about') { - $this->telegram->answerCallbackQuery([ - 'callback_query_id' => $this->telegram->Callback_ID(), - 'text' => view('tools.about'), - 'show_alert' => true - ]); + $this->answerCallbackQuery(view('tools.about')); } elseif (str_contains($callback, Setting::SETTING_PREFIX)) { $this->settingService->settingCallbackHandler($callback); } From 920e16a9ebcf36cd6af85ae5658e04db6c2f96fd Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Sun, 6 Aug 2023 11:35:59 +0700 Subject: [PATCH 04/16] (#30) update method access level --- src/Http/Actions/SendNotifyAction.php | 4 ++-- src/Models/Event.php | 2 +- src/Models/Setting.php | 2 +- src/Services/NotificationService.php | 6 +++--- src/Services/SettingService.php | 4 ++-- src/Services/TelegramService.php | 4 ++-- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Http/Actions/SendNotifyAction.php b/src/Http/Actions/SendNotifyAction.php index b4f6fdc..dfa4910 100644 --- a/src/Http/Actions/SendNotifyAction.php +++ b/src/Http/Actions/SendNotifyAction.php @@ -56,7 +56,7 @@ public function __invoke(): void * @param string $chatMessageId * @return void */ - public function handleEventInTelegram(string $chatMessageId): void + private function handleEventInTelegram(string $chatMessageId): void { // Send a result to only the bot owner if ($chatMessageId == config('telegram-bot.chat_id')) { @@ -73,7 +73,7 @@ public function handleEventInTelegram(string $chatMessageId): void /** * @return void */ - protected function sendNotification(): void + private function sendNotification(): void { $payload = $this->notificationService->setPayload($this->request); diff --git a/src/Models/Event.php b/src/Models/Event.php index 43195a2..25f735e 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -22,7 +22,7 @@ public function __construct() * * @return void */ - public function setEventConfig(): void + private function setEventConfig(): void { $json = file_get_contents(self::EVENT_FILE); $this->eventConfig = json_decode($json, true); diff --git a/src/Models/Setting.php b/src/Models/Setting.php index aed5a59..c1b03f6 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -25,7 +25,7 @@ public function __construct() * * @return void */ - public function setSettingConfig(): void + private function setSettingConfig(): void { $json = file_get_contents(self::SETTING_FILE); $this->settings = json_decode($json, true); diff --git a/src/Services/NotificationService.php b/src/Services/NotificationService.php index 3d8f63b..e9de10f 100644 --- a/src/Services/NotificationService.php +++ b/src/Services/NotificationService.php @@ -8,9 +8,9 @@ class NotificationService { - public mixed $payload; + protected mixed $payload; - public string $message = ""; + protected string $message = ""; /** * Notify access denied to other chat ids @@ -54,7 +54,7 @@ public function setPayload(Request $request) * @param string $typeEvent * @return void */ - public function setMessage(string $typeEvent): void + private function setMessage(string $typeEvent): void { if (isset($this->payload->action) && !empty($this->payload->action)) { $this->message = view( diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 850eba9..a9b91a9 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -6,9 +6,9 @@ class SettingService extends AppService { - public Setting $setting; + protected Setting $setting; - public array $settingConfig = []; + protected array $settingConfig = []; public function __construct() { diff --git a/src/Services/TelegramService.php b/src/Services/TelegramService.php index 457f6e7..708f3ab 100644 --- a/src/Services/TelegramService.php +++ b/src/Services/TelegramService.php @@ -54,7 +54,7 @@ public function telegramToolHandler(string $text = null): void * @param string|null $callback * @return void */ - protected function sendCallbackResponse(string $callback = null): void + private function sendCallbackResponse(string $callback = null): void { if (empty($callback)) { return; @@ -84,7 +84,7 @@ public function checkCallback(): bool /** * @return array[] */ - public function menuMarkup(): array + private function menuMarkup(): array { return [ [ From 49955e56984695f4b80c7f1eeb24ad0acb7484b8 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Tue, 8 Aug 2023 23:06:27 +0700 Subject: [PATCH 05/16] clean and update methods --- src/Http/Actions/SendNotifyAction.php | 4 ++-- src/Services/AppService.php | 11 +++++------ src/Services/NotificationService.php | 3 +-- src/Services/SettingService.php | 9 +++++---- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Http/Actions/SendNotifyAction.php b/src/Http/Actions/SendNotifyAction.php index dfa4910..33e9c4a 100644 --- a/src/Http/Actions/SendNotifyAction.php +++ b/src/Http/Actions/SendNotifyAction.php @@ -59,7 +59,7 @@ public function __invoke(): void private function handleEventInTelegram(string $chatMessageId): void { // Send a result to only the bot owner - if ($chatMessageId == config('telegram-bot.chat_id')) { + if ($chatMessageId == $this->telegramService->chatId) { $this->telegramService->telegramToolHandler($this->telegramService->messageData['message']['text']); return; } @@ -77,7 +77,7 @@ private function sendNotification(): void { $payload = $this->notificationService->setPayload($this->request); - if (!$this->eventSettingService->validateAccessEvent($this->request, $payload)) { + if (empty($payload) || !$this->eventSettingService->validateAccessEvent($this->request, $payload)) { return; } diff --git a/src/Services/AppService.php b/src/Services/AppService.php index e0bfc28..982f2a2 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -9,9 +9,12 @@ class AppService { public Telegram $telegram; + public string $chatId; + public function __construct() { $this->telegram = new Telegram(config('telegram-bot.token')); + $this->chatId = config('telegram-bot.chat_id'); } /** @@ -25,7 +28,7 @@ public function __construct() public function sendMessage(string $message = '', array $options = [], string $sendType = 'Message'): void { $content = array( - 'chat_id' => config('telegram-bot.chat_id'), + 'chat_id' => $this->chatId, 'disable_web_page_preview' => true, 'parse_mode' => 'HTML' ); @@ -38,11 +41,7 @@ public function sendMessage(string $message = '', array $options = [], string $s $content['caption'] = $message; } - if (!empty($options) && isset($options['reply_markup'])) { - $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); - } - - $this->telegram->{'send' . $sendType}($content); + $this->telegram->{'send' . $sendType}(array_merge($content, $options)); } catch (Exception $e) { error_log($e->getMessage()); } diff --git a/src/Services/NotificationService.php b/src/Services/NotificationService.php index e9de10f..fa7aa8f 100644 --- a/src/Services/NotificationService.php +++ b/src/Services/NotificationService.php @@ -38,8 +38,7 @@ public function accessDenied(TelegramService $telegramService, string $chatId = public function setPayload(Request $request) { if (is_null($request->server->get('HTTP_X_GITHUB_EVENT'))) { - echo 'invalid request'; - exit; + return null; } $this->payload = json_decode($request->request->get('payload')); diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index a9b91a9..58e26b3 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -22,12 +22,15 @@ public function __construct() */ public function settingHandle(): void { - $this->sendMessage(view('tools.settings'), $this->settingMarkup()); + $this->sendMessage( + view('tools.settings'), + ['reply_markup' => $this->settingMarkup()] + ); } public function settingMarkup(): array { - $keyboard = [ + return [ [ $this->telegram->buildInlineKeyBoardButton( $this->settingConfig['is_notified'] @@ -58,8 +61,6 @@ public function settingMarkup(): array ), ] ]; - - return ['reply_markup' => $keyboard]; } /** From 646168158a7867dac7fa050b8f5725e82dc5dbc6 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 9 Aug 2023 11:33:43 +0700 Subject: [PATCH 06/16] (#30) create reply markup for events setting --- resources/tools/event.php | 2 ++ src/Services/AppService.php | 6 ++++- src/Services/EventService.php | 46 ++++++++++++++++++++++++++++++++++- 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 resources/tools/event.php diff --git a/resources/tools/event.php b/resources/tools/event.php new file mode 100644 index 0000000..aefb6f9 --- /dev/null +++ b/resources/tools/event.php @@ -0,0 +1,2 @@ +Please select an event to enable or disable notifications. +Click and configure child events if have the ⚙ icon diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 982f2a2..941f524 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -41,7 +41,11 @@ public function sendMessage(string $message = '', array $options = [], string $s $content['caption'] = $message; } - $this->telegram->{'send' . $sendType}(array_merge($content, $options)); + if (!empty($options) && isset($options['reply_markup'])) { + $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); + } + + $this->telegram->{'send' . $sendType}($content); } catch (Exception $e) { error_log($e->getMessage()); } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index e797524..aaefb9b 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -8,6 +8,8 @@ class EventService extends AppService { + public const LINE_ITEM_COUNT = 2; + protected Setting $setting; protected Event $event; @@ -53,7 +55,49 @@ public function validateAccessEvent(Request $request, $payload): bool return (bool)$eventConfig; } - public function eventHandle() + /** + * @return array + */ + public function eventMarkup(): array + { + $replyMarkup = $replyMarkupItem = []; + + foreach ($this->event->getEventConfig() as $event => $eventValue) { + if (count($replyMarkupItem) === self::LINE_ITEM_COUNT) { + $replyMarkup[] = $replyMarkupItem; + $replyMarkupItem = []; + } + + $callbackData = $this->event::EVENT_PREFIX . $event; + + if (is_array($eventValue)) { + $eventName = '⚙ ' . $event; + $callbackData .= '.child'; + } elseif ($eventValue) { + $eventName = '✅ ' . $event; + } else { + $eventName = '❌ ' . $event; + } + + $replyMarkupItem[] = $this->telegram->buildInlineKeyBoardButton($eventName, '', $callbackData); + } + + // add last item to a reply_markup array + if (count($replyMarkupItem) > 0) { + $replyMarkup[] = $replyMarkupItem; + } + + return $replyMarkup; + } + + /** + * @return void + */ + public function eventHandle(): void { + $this->sendMessage( + view('tools.event'), + ['reply_markup' => $this->eventMarkup()] + ); } } From 5c7f83b00ba3fb60570ae773dd14aaa2d1c0497f Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 9 Aug 2023 13:45:56 +0700 Subject: [PATCH 07/16] (#30) update event markup for multi events --- resources/tools/event.php | 4 +++- src/Services/EventService.php | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/resources/tools/event.php b/resources/tools/event.php index aefb6f9..a753ea8 100644 --- a/resources/tools/event.php +++ b/resources/tools/event.php @@ -1,2 +1,4 @@ Please select an event to enable or disable notifications. -Click and configure child events if have the ⚙ icon +Click and configure child events if the option has the ⚙ icon. +--- +Please check the GitHub documentation for more information about events. diff --git a/src/Services/EventService.php b/src/Services/EventService.php index aaefb9b..86394e7 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -56,13 +56,18 @@ public function validateAccessEvent(Request $request, $payload): bool } /** + * Create markup for select event + * + * @param string|null $event * @return array */ - public function eventMarkup(): array + public function eventMarkup(?string $event = null): array { $replyMarkup = $replyMarkupItem = []; - foreach ($this->event->getEventConfig() as $event => $eventValue) { + $events = $event === null ? $this->event->eventConfig : $this->event->eventConfig[$event]; + + foreach ($events as $event => $value) { if (count($replyMarkupItem) === self::LINE_ITEM_COUNT) { $replyMarkup[] = $replyMarkupItem; $replyMarkupItem = []; @@ -70,10 +75,10 @@ public function eventMarkup(): array $callbackData = $this->event::EVENT_PREFIX . $event; - if (is_array($eventValue)) { + if (is_array($value)) { $eventName = '⚙ ' . $event; $callbackData .= '.child'; - } elseif ($eventValue) { + } elseif ($value) { $eventName = '✅ ' . $event; } else { $eventName = '❌ ' . $event; @@ -87,6 +92,9 @@ public function eventMarkup(): array $replyMarkup[] = $replyMarkupItem; } + $replyMarkup[] = [$this->telegram->buildInlineKeyBoardButton('🔙 Back', '', 'back')]; + $replyMarkup[] = [$this->telegram->buildInlineKeyBoardButton('📚 Menu', '', $this->setting::SETTING_PREFIX . '.back.menu')]; + return $replyMarkup; } From 5ced730b0feb2997389ae82fba5755cbe8579a28 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 9 Aug 2023 15:27:54 +0700 Subject: [PATCH 08/16] (#30) Edit message from telegram --- src/Services/AppService.php | 31 +++++++++++++++++++++++++++++++ src/Services/SettingService.php | 7 ++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 941f524..bfeff0e 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -69,4 +69,35 @@ public function answerCallbackQuery(string $text = null): void error_log($e->getMessage()); } } + + /** + * Edit message from telegram + * + * @param string|null $text + * @param array $options + * @return void + */ + public function editMessageText(?string $text = null, array $options = []): void + { + try { + $content = array( + 'chat_id' => $this->telegram->Callback_ChatID(), + 'message_id' => $this->telegram->MessageID(), + 'disable_web_page_preview' => true, + 'parse_mode' => 'HTML', + ); + + if (!empty($text)) { + $content['text'] = $text; + } + + if (!empty($options) && isset($options['reply_markup'])) { + $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); + } + + $this->telegram->editMessageText($content); + } catch (Exception $e) { + error_log($e->getMessage()); + } + } } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 58e26b3..6119805 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -28,6 +28,9 @@ public function settingHandle(): void ); } + /** + * @return array[] + */ public function settingMarkup(): array { return [ @@ -77,7 +80,9 @@ public function settingCallbackHandler(string $callback): void $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); if ($this->updateSettingItem($callback, !$this->settingConfig[$callback])) { - $this->settingHandle(); + $this->editMessageText(null, [ + 'reply_markup' => $this->settingMarkup(), + ]); } else { $this->answerCallbackQuery('Something went wrong!'); } From d6e307834bd29b8407f381a2b0059cbd8ffb117d Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 9 Aug 2023 15:49:11 +0700 Subject: [PATCH 09/16] (#30) Update logic to edit message from telegram --- src/Services/AppService.php | 65 ++++++++++++++++++++++++++------- src/Services/EventService.php | 2 +- src/Services/SettingService.php | 2 +- 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/src/Services/AppService.php b/src/Services/AppService.php index bfeff0e..24a173f 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -72,6 +72,7 @@ public function answerCallbackQuery(string $text = null): void /** * Edit message from telegram + * (Edit message text and reply markup) * * @param string|null $text * @param array $options @@ -80,24 +81,60 @@ public function answerCallbackQuery(string $text = null): void public function editMessageText(?string $text = null, array $options = []): void { try { - $content = array( - 'chat_id' => $this->telegram->Callback_ChatID(), - 'message_id' => $this->telegram->MessageID(), - 'disable_web_page_preview' => true, - 'parse_mode' => 'HTML', - ); - - if (!empty($text)) { - $content['text'] = $text; - } - - if (!empty($options) && isset($options['reply_markup'])) { - $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); - } + $content = [ + 'text' => $text ?? $this->Callback_Message_Text() + ]; + $content = array_merge($content, $this->setContentEditMessage($options)); $this->telegram->editMessageText($content); } catch (Exception $e) { error_log($e->getMessage()); } } + + /** + * Edit message reply markup from a telegram + * (Edit message reply markup only) + * + * @param array $options + * @return void + */ + public function editMessageReplyMarkup(array $options = []): void + { + try { + $this->telegram->editMessageReplyMarkup($this->setContentEditMessage($options)); + } catch (Exception $e) { + error_log($e->getMessage()); + } + } + + /** + * Get the text from callback message + * + * @return string + */ + public function Callback_Message_Text(): string + { + return $this->telegram->Callback_Message()['text']; + } + + /** + * @param array $options + * @return array + */ + public function setContentEditMessage(array $options = []): array + { + $content = array( + 'chat_id' => $this->telegram->Callback_ChatID(), + 'message_id' => $this->telegram->MessageID(), + 'disable_web_page_preview' => true, + 'parse_mode' => 'HTML', + ); + + if (!empty($options) && isset($options['reply_markup'])) { + $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); + } + + return $content; + } } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 86394e7..19e3c4c 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -103,7 +103,7 @@ public function eventMarkup(?string $event = null): array */ public function eventHandle(): void { - $this->sendMessage( + $this->editMessageText( view('tools.event'), ['reply_markup' => $this->eventMarkup()] ); diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 6119805..cee797e 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -80,7 +80,7 @@ public function settingCallbackHandler(string $callback): void $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); if ($this->updateSettingItem($callback, !$this->settingConfig[$callback])) { - $this->editMessageText(null, [ + $this->editMessageReplyMarkup([ 'reply_markup' => $this->settingMarkup(), ]); } else { From 5239a784cd6fe5413765e41b9cfc0f11f7478d95 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 9 Aug 2023 22:33:25 +0700 Subject: [PATCH 10/16] (#30) Handle setting for the action of events --- resources/tools/custom_event.php | 4 ++++ resources/tools/custom_event_action.php | 8 +++++++ resources/tools/event.php | 4 ---- src/Models/Event.php | 2 +- src/Services/AppService.php | 10 ++++----- src/Services/EventService.php | 28 +++++++++++++++++++------ src/Services/SettingService.php | 4 ++-- 7 files changed, 42 insertions(+), 18 deletions(-) create mode 100644 resources/tools/custom_event.php create mode 100644 resources/tools/custom_event_action.php delete mode 100644 resources/tools/event.php diff --git a/resources/tools/custom_event.php b/resources/tools/custom_event.php new file mode 100644 index 0000000..9386020 --- /dev/null +++ b/resources/tools/custom_event.php @@ -0,0 +1,4 @@ +Click and configure child events if the option has the ⚙ icon. +--- +Go to check the GitHub documentation for more information about events. +Please select an event to enable or disable notifications: diff --git a/resources/tools/custom_event_action.php b/resources/tools/custom_event_action.php new file mode 100644 index 0000000..d2cb79d --- /dev/null +++ b/resources/tools/custom_event_action.php @@ -0,0 +1,8 @@ + +Event: +Please select an action of this event to enable or disable notifications: diff --git a/resources/tools/event.php b/resources/tools/event.php deleted file mode 100644 index a753ea8..0000000 --- a/resources/tools/event.php +++ /dev/null @@ -1,4 +0,0 @@ -Please select an event to enable or disable notifications. -Click and configure child events if the option has the ⚙ icon. ---- -Please check the GitHub documentation for more information about events. diff --git a/src/Models/Event.php b/src/Models/Event.php index 25f735e..90f2bab 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -6,7 +6,7 @@ class Event { public const EVENT_FILE = __DIR__ . '/../../storage/tg-event.json'; - public const EVENT_PREFIX = Setting::SETTING_PREFIX . '.event.'; + public const EVENT_PREFIX = Setting::SETTING_CUSTOM_EVENTS . '.event.'; public array $eventConfig = []; diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 24a173f..7012525 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -81,10 +81,9 @@ public function answerCallbackQuery(string $text = null): void public function editMessageText(?string $text = null, array $options = []): void { try { - $content = [ + $content = array_merge([ 'text' => $text ?? $this->Callback_Message_Text() - ]; - $content = array_merge($content, $this->setContentEditMessage($options)); + ], $this->setCallbackContentMessage($options)); $this->telegram->editMessageText($content); } catch (Exception $e) { @@ -102,7 +101,7 @@ public function editMessageText(?string $text = null, array $options = []): void public function editMessageReplyMarkup(array $options = []): void { try { - $this->telegram->editMessageReplyMarkup($this->setContentEditMessage($options)); + $this->telegram->editMessageReplyMarkup($this->setCallbackContentMessage($options)); } catch (Exception $e) { error_log($e->getMessage()); } @@ -119,10 +118,11 @@ public function Callback_Message_Text(): string } /** + * Create content for callback message * @param array $options * @return array */ - public function setContentEditMessage(array $options = []): array + public function setCallbackContentMessage(array $options = []): array { $content = array( 'chat_id' => $this->telegram->Callback_ChatID(), diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 19e3c4c..1f2f24b 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -10,6 +10,8 @@ class EventService extends AppService { public const LINE_ITEM_COUNT = 2; + public const EVENT_HAS_ACTION_SEPARATOR = 'action.'; + protected Setting $setting; protected Event $event; @@ -77,7 +79,7 @@ public function eventMarkup(?string $event = null): array if (is_array($value)) { $eventName = '⚙ ' . $event; - $callbackData .= '.child'; + $callbackData = $this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR . $event; } elseif ($value) { $eventName = '✅ ' . $event; } else { @@ -99,13 +101,27 @@ public function eventMarkup(?string $event = null): array } /** + * Handle event callback settings + * + * @param string|null $callback * @return void */ - public function eventHandle(): void + public function eventHandle(?string $callback = null): void { - $this->editMessageText( - view('tools.event'), - ['reply_markup' => $this->eventMarkup()] - ); + if ($this->setting::SETTING_CUSTOM_EVENTS === $callback || empty($callback)) { + $this->editMessageText( + view('tools.custom_event'), + ['reply_markup' => $this->eventMarkup()] + ); + return; + } + + if (str_contains($callback, self::EVENT_HAS_ACTION_SEPARATOR)) { + $event = str_replace($this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR, '', $callback); + $this->editMessageText( + view('tools.custom_event_action', compact('event')), + ['reply_markup' => $this->eventMarkup($event)] + ); + } } } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index cee797e..f0556bc 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -72,8 +72,8 @@ public function settingMarkup(): array */ public function settingCallbackHandler(string $callback): void { - if ($callback === $this->setting::SETTING_CUSTOM_EVENTS) { - (new EventService())->eventHandle(); + if (str_contains($callback, $this->setting::SETTING_CUSTOM_EVENTS)) { + (new EventService())->eventHandle($callback); return; } From ebd9f03d549dbe062d2b263e0b41b958a14c436c Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Thu, 10 Aug 2023 10:25:35 +0700 Subject: [PATCH 11/16] (#30) Update readme and optimize send message --- README.md | 11 ++++++----- src/Services/AppService.php | 13 +++++-------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 2d323c8..108042f 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,6 @@ - PHP ^8.0 - Composer - Telegram Bot -- SSL Certificate ## Installation @@ -70,12 +69,14 @@ APP_URL=https://123456789.ngrok.io ### Set the webhook -#### Set the webhook from the source code +We have two ways to set the webhook: + +#### 1. Set the webhook from this project After setting up your domain and SSL certificate, you need to set up the webhook for your bot. Go to: ```text -/setWebhook.php +/webhook/set.php ``` > **Note:** Replace `` with your app URL in .env file. @@ -86,7 +87,7 @@ If you see the following message, it means that the webhook has been sent succes {"ok":true,"result":true,"description":"Webhook was set"} ``` -#### Set the webhook manually +#### 2. Set the webhook manually If you want to set the webhook manually, you can use the following URL: @@ -140,4 +141,4 @@ Now you can send a message to your bot, and you will receive a notification. Here is the first notification you will receive: ♻️ **Connection Successful** -> **You can add multiple webhooks to your repository.** +> **Note: You can add multiple webhooks to your repository. Please similarly set up the webhook for each repository.** diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 7012525..b2ad69c 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -36,14 +36,12 @@ public function sendMessage(string $message = '', array $options = [], string $s try { if ($sendType === 'Message') { $content['text'] = $message; - } elseif ($sendType === 'Photo' && !empty($options)) { - $content['photo'] = $options['photo']; + } elseif ($sendType === 'Photo') { + $content['photo'] = $options['photo'] ?? null; $content['caption'] = $message; } - if (!empty($options) && isset($options['reply_markup'])) { - $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); - } + $content['reply_markup'] = $options['reply_markup'] ? $this->telegram->buildInlineKeyBoard($options['reply_markup']) : null; $this->telegram->{'send' . $sendType}($content); } catch (Exception $e) { @@ -119,6 +117,7 @@ public function Callback_Message_Text(): string /** * Create content for callback message + * * @param array $options * @return array */ @@ -131,9 +130,7 @@ public function setCallbackContentMessage(array $options = []): array 'parse_mode' => 'HTML', ); - if (!empty($options) && isset($options['reply_markup'])) { - $content['reply_markup'] = $this->telegram->buildInlineKeyBoard($options['reply_markup']); - } + $content['reply_markup'] = $options['reply_markup'] ? $this->telegram->buildInlineKeyBoard($options['reply_markup']) : null; return $content; } From 2fd4c88eccc11a32cc2b292d013128e5655d4144 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Thu, 10 Aug 2023 10:27:02 +0700 Subject: [PATCH 12/16] (#30) Update readme and optimize send message --- src/Services/AppService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Services/AppService.php b/src/Services/AppService.php index b2ad69c..ccfacbc 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -117,7 +117,7 @@ public function Callback_Message_Text(): string /** * Create content for callback message - * + * * @param array $options * @return array */ From a51f4547dddb6750241818e2e7d32b3e9e58fa6e Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Thu, 10 Aug 2023 10:44:51 +0700 Subject: [PATCH 13/16] Optimize event service --- resources/tools/start.php | 2 +- src/Services/AppService.php | 20 ++++++--------- src/Services/EventService.php | 46 +++++++++++++++++++++++++++-------- 3 files changed, 45 insertions(+), 23 deletions(-) diff --git a/resources/tools/start.php b/resources/tools/start.php index 4ec152b..30d42ec 100644 --- a/resources/tools/start.php +++ b/resources/tools/start.php @@ -9,4 +9,4 @@ Hey , I can send you notifications from your GitHub Repository instantly to your Telegram. -Use /menu for more information about me. +Use /menu for more options. diff --git a/src/Services/AppService.php b/src/Services/AppService.php index ccfacbc..5c77cf3 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -33,20 +33,16 @@ public function sendMessage(string $message = '', array $options = [], string $s 'parse_mode' => 'HTML' ); - try { - if ($sendType === 'Message') { - $content['text'] = $message; - } elseif ($sendType === 'Photo') { - $content['photo'] = $options['photo'] ?? null; - $content['caption'] = $message; - } + if ($sendType === 'Message') { + $content['text'] = $message; + } elseif ($sendType === 'Photo') { + $content['photo'] = $options['photo'] ?? null; + $content['caption'] = $message; + } - $content['reply_markup'] = $options['reply_markup'] ? $this->telegram->buildInlineKeyBoard($options['reply_markup']) : null; + $content['reply_markup'] = $options['reply_markup'] ? $this->telegram->buildInlineKeyBoard($options['reply_markup']) : null; - $this->telegram->{'send' . $sendType}($content); - } catch (Exception $e) { - error_log($e->getMessage()); - } + $this->telegram->{'send' . $sendType}($content); } /** diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 1f2f24b..c343c22 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -75,16 +75,8 @@ public function eventMarkup(?string $event = null): array $replyMarkupItem = []; } - $callbackData = $this->event::EVENT_PREFIX . $event; - - if (is_array($value)) { - $eventName = '⚙ ' . $event; - $callbackData = $this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR . $event; - } elseif ($value) { - $eventName = '✅ ' . $event; - } else { - $eventName = '❌ ' . $event; - } + $callbackData = $this->getCallbackData($event, $value); + $eventName = $this->getEventName($event, $value); $replyMarkupItem[] = $this->telegram->buildInlineKeyBoardButton($eventName, '', $callbackData); } @@ -100,6 +92,40 @@ public function eventMarkup(?string $event = null): array return $replyMarkup; } + /** + * Get event name for markup + * + * @param string $event + * @param $value + * @return string + */ + private function getEventName(string $event, $value): string + { + if (is_array($value)) { + return '⚙ ' . $event; + } elseif ($value) { + return '✅ ' . $event; + } else { + return '❌ ' . $event; + } + } + + /** + * Get callback data for markup + * + * @param string $event + * @param $value + * @return string + */ + private function getCallbackData(string $event, $value): string + { + if (is_array($value)) { + return $this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR . $event; + } else { + return $this->event::EVENT_PREFIX . $event; + } + } + /** * Handle event callback settings * From 3fc0581b4c92a7a475fade23ad7a444084a3b666 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Thu, 10 Aug 2023 11:37:28 +0700 Subject: [PATCH 14/16] (#30) handle the back button --- ...nt_action.php => custom_event_actions.php} | 0 .../{custom_event.php => custom_events.php} | 6 +-- src/Models/Setting.php | 1 + src/Services/AppService.php | 17 +++++++ src/Services/EventService.php | 33 ++++++++++--- src/Services/SettingService.php | 46 ++++++++++++++++++- src/Services/TelegramService.php | 15 ------ 7 files changed, 92 insertions(+), 26 deletions(-) rename resources/tools/{custom_event_action.php => custom_event_actions.php} (100%) rename resources/tools/{custom_event.php => custom_events.php} (80%) diff --git a/resources/tools/custom_event_action.php b/resources/tools/custom_event_actions.php similarity index 100% rename from resources/tools/custom_event_action.php rename to resources/tools/custom_event_actions.php diff --git a/resources/tools/custom_event.php b/resources/tools/custom_events.php similarity index 80% rename from resources/tools/custom_event.php rename to resources/tools/custom_events.php index 9386020..d71fdf6 100644 --- a/resources/tools/custom_event.php +++ b/resources/tools/custom_events.php @@ -1,4 +1,4 @@ -Click and configure child events if the option has the ⚙ icon. ---- Go to check the GitHub documentation for more information about events. -Please select an event to enable or disable notifications: +--- +Click and configure child events if the option has the ⚙ icon. +And select an event to enable or disable notifications: diff --git a/src/Models/Setting.php b/src/Models/Setting.php index c1b03f6..ec555e0 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -10,6 +10,7 @@ class Setting public const SETTING_IS_NOTIFIED = self::SETTING_PREFIX . 'is_notified'; public const SETTING_ALL_EVENTS_NOTIFY = self::SETTING_PREFIX . 'all_events_notify'; public const SETTING_CUSTOM_EVENTS = self::SETTING_PREFIX . 'custom_events'; + public const SETTING_BACK = self::SETTING_PREFIX . 'back.'; public array $settings = []; diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 5c77cf3..1c4bf88 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -130,4 +130,21 @@ public function setCallbackContentMessage(array $options = []): array return $content; } + + /** + * Generate menu markup + * + * @return array[] + */ + public function menuMarkup(): array + { + return [ + [ + $this->telegram->buildInlineKeyBoardButton("📰 About", "", "about", ""), + $this->telegram->buildInlineKeyBoardButton("📞 Contact", config('author.contact')) + ], [ + $this->telegram->buildInlineKeyBoardButton("💠 Source Code", config('author.source_code')) + ] + ]; + } } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index c343c22..63dc89c 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -69,14 +69,14 @@ public function eventMarkup(?string $event = null): array $events = $event === null ? $this->event->eventConfig : $this->event->eventConfig[$event]; - foreach ($events as $event => $value) { + foreach ($events as $key => $value) { if (count($replyMarkupItem) === self::LINE_ITEM_COUNT) { $replyMarkup[] = $replyMarkupItem; $replyMarkupItem = []; } - $callbackData = $this->getCallbackData($event, $value); - $eventName = $this->getEventName($event, $value); + $callbackData = $this->getCallbackData($key, $value); + $eventName = $this->getEventName($key, $value); $replyMarkupItem[] = $this->telegram->buildInlineKeyBoardButton($eventName, '', $callbackData); } @@ -86,8 +86,7 @@ public function eventMarkup(?string $event = null): array $replyMarkup[] = $replyMarkupItem; } - $replyMarkup[] = [$this->telegram->buildInlineKeyBoardButton('🔙 Back', '', 'back')]; - $replyMarkup[] = [$this->telegram->buildInlineKeyBoardButton('📚 Menu', '', $this->setting::SETTING_PREFIX . '.back.menu')]; + $replyMarkup[] = $this->getEndKeyboard($event); return $replyMarkup; } @@ -126,6 +125,26 @@ private function getCallbackData(string $event, $value): string } } + /** + * Get end keyboard buttons + * + * @param string|null $event + * @return array + */ + public function getEndKeyboard(?string $event = null): array + { + $back = $this->setting::SETTING_BACK . 'settings'; + + if ($event) { + $back = $this->setting::SETTING_BACK . 'settings.custom_events'; + } + + return [ + $this->telegram->buildInlineKeyBoardButton('🔙 Back', '', $back), + $this->telegram->buildInlineKeyBoardButton('📚 Menu', '', $this->setting::SETTING_BACK . 'menu') + ]; + } + /** * Handle event callback settings * @@ -136,7 +155,7 @@ public function eventHandle(?string $callback = null): void { if ($this->setting::SETTING_CUSTOM_EVENTS === $callback || empty($callback)) { $this->editMessageText( - view('tools.custom_event'), + view('tools.custom_events'), ['reply_markup' => $this->eventMarkup()] ); return; @@ -145,7 +164,7 @@ public function eventHandle(?string $callback = null): void if (str_contains($callback, self::EVENT_HAS_ACTION_SEPARATOR)) { $event = str_replace($this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR, '', $callback); $this->editMessageText( - view('tools.custom_event_action', compact('event')), + view('tools.custom_event_actions', compact('event')), ['reply_markup' => $this->eventMarkup($event)] ); } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index f0556bc..e59bdf2 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -18,6 +18,8 @@ public function __construct() } /** + * Send setting message + * * @return void */ public function settingHandle(): void @@ -29,6 +31,8 @@ public function settingHandle(): void } /** + * Generate setting markup + * * @return array[] */ public function settingMarkup(): array @@ -60,13 +64,15 @@ public function settingMarkup(): array $this->telegram->buildInlineKeyBoardButton( '🔙 Back to menu', '', - $this->setting::SETTING_PREFIX . '.back.menu' + $this->setting::SETTING_BACK . 'menu' ), ] ]; } /** + * Setting callback handler + * * @param string $callback * @return void */ @@ -77,6 +83,11 @@ public function settingCallbackHandler(string $callback): void return; } + if (str_contains($callback, $this->setting::SETTING_BACK)) { + $this->answerBackButton($callback); + return; + } + $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); if ($this->updateSettingItem($callback, !$this->settingConfig[$callback])) { @@ -89,6 +100,8 @@ public function settingCallbackHandler(string $callback): void } /** + * Update setting item value and save to file + * * @param string $settingName * @param $settingValue * @return bool @@ -117,6 +130,8 @@ public function updateSettingItem(string $settingName, $settingValue = null): bo } /** + * Save settings to json file + * * @return bool */ private function saveSettingsToFile(): bool @@ -130,4 +145,33 @@ private function saveSettingsToFile(): bool return false; } + + /** + * @param string $callback + * + * @return void + */ + public function answerBackButton(string $callback): void + { + $callback = str_replace($this->setting::SETTING_BACK, '', $callback); + + switch ($callback) { + case 'settings': + $view = view('tools.settings'); + $markup = $this->settingMarkup(); + break; + case 'settings.custom_events': + $view = view('tools.custom_events'); + $markup = (new EventService())->eventMarkup(); + break; + default: + $view = view('tools.menu'); + $markup = $this->menuMarkup(); + break; + } + + $this->editMessageText($view, [ + 'reply_markup' => $markup, + ]); + } } diff --git a/src/Services/TelegramService.php b/src/Services/TelegramService.php index 708f3ab..3ab1277 100644 --- a/src/Services/TelegramService.php +++ b/src/Services/TelegramService.php @@ -80,19 +80,4 @@ public function checkCallback(): bool } return false; } - - /** - * @return array[] - */ - private function menuMarkup(): array - { - return [ - [ - $this->telegram->buildInlineKeyBoardButton("📰 About", "", "about", ""), - $this->telegram->buildInlineKeyBoardButton("📞 Contact", config('author.contact')) - ], [ - $this->telegram->buildInlineKeyBoardButton("💠 Source Code", config('author.source_code')) - ] - ]; - } } From 59ca6cbcee31cf7a7b9a5c265fe286803878d9f2 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Fri, 11 Aug 2023 00:46:44 +0700 Subject: [PATCH 15/16] (#30) feat: handle to update events and actions in bot setting --- src/Models/Event.php | 31 ++++++++++++++++++++++ src/Services/EventService.php | 47 +++++++++++++++++++++++++++------ src/Services/SettingService.php | 5 ++-- 3 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/Models/Event.php b/src/Models/Event.php index 90f2bab..4b7a01e 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -37,4 +37,35 @@ public function getEventConfig(): array { return $this->eventConfig; } + + /** + * Update event config by event and action + * + * @param string $event + * @param string|null $action + * @return void + */ + public function updateEvent(string $event, string|null $action): void + { + if (!empty($action)) { + $this->eventConfig[$event][$action] = !$this->eventConfig[$event][$action]; + } else { + $this->eventConfig[$event] = !$this->eventConfig[$event]; + } + + $this->saveEventConfig(); + } + + /** + * Save event config + * + * @return void + */ + private function saveEventConfig(): void + { + if (file_exists(self::EVENT_FILE)) { + $json = json_encode($this->eventConfig, JSON_PRETTY_PRINT); + file_put_contents(self::EVENT_FILE, $json, LOCK_EX); + } + } } diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 63dc89c..94695b7 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -12,6 +12,8 @@ class EventService extends AppService public const EVENT_HAS_ACTION_SEPARATOR = 'action.'; + public const EVENT_UPDATE_SEPARATOR = '.update'; + protected Setting $setting; protected Event $event; @@ -75,7 +77,7 @@ public function eventMarkup(?string $event = null): array $replyMarkupItem = []; } - $callbackData = $this->getCallbackData($key, $value); + $callbackData = $this->getCallbackData($key, $value, $event); $eventName = $this->getEventName($key, $value); $replyMarkupItem[] = $this->telegram->buildInlineKeyBoardButton($eventName, '', $callbackData); @@ -104,25 +106,29 @@ private function getEventName(string $event, $value): string return '⚙ ' . $event; } elseif ($value) { return '✅ ' . $event; - } else { - return '❌ ' . $event; } + + return '❌ ' . $event; } /** * Get callback data for markup * * @param string $event - * @param $value + * @param array|string $value + * @param string|null $parentEvent + * * @return string */ - private function getCallbackData(string $event, $value): string + private function getCallbackData(string $event, array|string $value, ?string $parentEvent = null): string { if (is_array($value)) { return $this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR . $event; - } else { - return $this->event::EVENT_PREFIX . $event; + } elseif ($parentEvent) { + return $this->event::EVENT_PREFIX . $parentEvent . '.' . $event . self::EVENT_UPDATE_SEPARATOR; } + + return $this->event::EVENT_PREFIX . $event . self::EVENT_UPDATE_SEPARATOR; } /** @@ -153,6 +159,7 @@ public function getEndKeyboard(?string $event = null): array */ public function eventHandle(?string $callback = null): void { + // first event settings if ($this->setting::SETTING_CUSTOM_EVENTS === $callback || empty($callback)) { $this->editMessageText( view('tools.custom_events'), @@ -161,12 +168,36 @@ public function eventHandle(?string $callback = null): void return; } + $event = str_replace($this->event::EVENT_PREFIX, '', $callback); + + // if event has actions if (str_contains($callback, self::EVENT_HAS_ACTION_SEPARATOR)) { - $event = str_replace($this->event::EVENT_PREFIX . self::EVENT_HAS_ACTION_SEPARATOR, '', $callback); + $event = str_replace(self::EVENT_HAS_ACTION_SEPARATOR, '', $event); $this->editMessageText( view('tools.custom_event_actions', compact('event')), ['reply_markup' => $this->eventMarkup($event)] ); } + + if (str_contains($event, self::EVENT_UPDATE_SEPARATOR)) { + $event = str_replace(self::EVENT_UPDATE_SEPARATOR, '', $event); + $this->eventUpdateHandle($event); + } + } + + /** + * Handle event update + * + * @param string $event + * @return void + */ + public function eventUpdateHandle(string $event): void + { + $event = explode('.', $event); + $action = $event[1] ?? null; + $event = $event[0]; + + $this->event->updateEvent($event, $action); + $this->eventHandle($action ? self::EVENT_HAS_ACTION_SEPARATOR . $event : null); } } diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index e59bdf2..3174bbe 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -18,7 +18,7 @@ public function __construct() } /** - * Send setting message + * Send a setting message * * @return void */ @@ -147,8 +147,9 @@ private function saveSettingsToFile(): bool } /** - * @param string $callback + * Answer the back button * + * @param string $callback * @return void */ public function answerBackButton(string $callback): void From d77dc75967fbbc5456a00c73a754dd0d032150ef Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Fri, 11 Aug 2023 10:15:51 +0700 Subject: [PATCH 16/16] (#30) clean and refactor bot settings --- resources/tools/custom_event_actions.php | 2 +- resources/tools/menu.php | 2 +- resources/tools/settings.php | 2 +- src/Models/Event.php | 2 +- src/Models/Setting.php | 51 +++++++++++++- src/Services/AppService.php | 2 +- src/Services/EventService.php | 4 +- src/Services/NotificationService.php | 2 +- src/Services/SettingService.php | 86 ++++++------------------ 9 files changed, 77 insertions(+), 76 deletions(-) diff --git a/resources/tools/custom_event_actions.php b/resources/tools/custom_event_actions.php index d2cb79d..848cdbc 100644 --- a/resources/tools/custom_event_actions.php +++ b/resources/tools/custom_event_actions.php @@ -4,5 +4,5 @@ */ ?> -Event: +Setting actions for the event: Please select an action of this event to enable or disable notifications: diff --git a/resources/tools/menu.php b/resources/tools/menu.php index 37db9f4..589e98e 100644 --- a/resources/tools/menu.php +++ b/resources/tools/menu.php @@ -4,7 +4,7 @@ /id - To get your Chat ID. /token - To get this bot token. /usage - How to use me. -/settings - Settings github notify. +/settings - Settings GitHub notify. /menu - To get this menu. Select a button: diff --git a/resources/tools/settings.php b/resources/tools/settings.php index fa2ed29..cd7de79 100644 --- a/resources/tools/settings.php +++ b/resources/tools/settings.php @@ -1 +1 @@ -Settings for github notify. +Settings for GitHub notify. diff --git a/src/Models/Event.php b/src/Models/Event.php index 4b7a01e..be2c605 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -6,7 +6,7 @@ class Event { public const EVENT_FILE = __DIR__ . '/../../storage/tg-event.json'; - public const EVENT_PREFIX = Setting::SETTING_CUSTOM_EVENTS . '.event.'; + public const EVENT_PREFIX = Setting::SETTING_CUSTOM_EVENTS . '.evt.'; public array $eventConfig = []; diff --git a/src/Models/Setting.php b/src/Models/Setting.php index ec555e0..e9e6aef 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -5,11 +5,11 @@ class Setting { public const SETTING_FILE = __DIR__ . '/../../storage/tg-setting.json'; - public const SETTING_PREFIX = 'setting.'; + public const SETTING_PREFIX = 'stg.'; public const SETTING_IS_NOTIFIED = self::SETTING_PREFIX . 'is_notified'; public const SETTING_ALL_EVENTS_NOTIFY = self::SETTING_PREFIX . 'all_events_notify'; - public const SETTING_CUSTOM_EVENTS = self::SETTING_PREFIX . 'custom_events'; + public const SETTING_CUSTOM_EVENTS = self::SETTING_PREFIX . 'cus'; public const SETTING_BACK = self::SETTING_PREFIX . 'back.'; public array $settings = []; @@ -65,4 +65,51 @@ public function isNotified(): bool return false; } + + /** + * Update setting item value and save to file + * + * @param string $settingName + * @param $settingValue + * @return bool + */ + public function updateSettingItem(string $settingName, $settingValue = null): bool + { + $keys = explode('.', $settingName); + $lastKey = array_pop($keys); + $nestedSettings = &$this->settings; + + foreach ($keys as $key) { + if (!isset($nestedSettings[$key]) || !is_array($nestedSettings[$key])) { + return false; + } + $nestedSettings = &$nestedSettings[$key]; + } + + if (isset($nestedSettings[$lastKey])) { + $nestedSettings[$lastKey] = $settingValue ?? !$nestedSettings[$lastKey]; + if ($this->saveSettingsToFile()) { + return true; + } + } + + return false; + } + + /** + * Save settings to json file + * + * @return bool + */ + private function saveSettingsToFile(): bool + { + if (file_exists(self::SETTING_FILE)) { + $json = json_encode($this->settings, JSON_PRETTY_PRINT); + file_put_contents(self::SETTING_FILE, $json, LOCK_EX); + + return true; + } + + return false; + } } diff --git a/src/Services/AppService.php b/src/Services/AppService.php index 1c4bf88..71e317e 100644 --- a/src/Services/AppService.php +++ b/src/Services/AppService.php @@ -112,7 +112,7 @@ public function Callback_Message_Text(): string } /** - * Create content for callback message + * Create content for a callback message * * @param array $options * @return array diff --git a/src/Services/EventService.php b/src/Services/EventService.php index 94695b7..572bceb 100644 --- a/src/Services/EventService.php +++ b/src/Services/EventService.php @@ -10,9 +10,9 @@ class EventService extends AppService { public const LINE_ITEM_COUNT = 2; - public const EVENT_HAS_ACTION_SEPARATOR = 'action.'; + public const EVENT_HAS_ACTION_SEPARATOR = 'atc.'; - public const EVENT_UPDATE_SEPARATOR = '.update'; + public const EVENT_UPDATE_SEPARATOR = '.upd'; protected Setting $setting; diff --git a/src/Services/NotificationService.php b/src/Services/NotificationService.php index fa7aa8f..996619e 100644 --- a/src/Services/NotificationService.php +++ b/src/Services/NotificationService.php @@ -69,7 +69,7 @@ private function setMessage(string $typeEvent): void } /** - * Send notify to telegram + * Send notification to telegram * * @param string $chatId * @param string|null $message diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php index 3174bbe..ccba48c 100644 --- a/src/Services/SettingService.php +++ b/src/Services/SettingService.php @@ -8,13 +8,10 @@ class SettingService extends AppService { protected Setting $setting; - protected array $settingConfig = []; - public function __construct() { parent::__construct(); $this->setting = new Setting(); - $this->settingConfig = $this->setting->getSettingConfig(); } /** @@ -37,29 +34,33 @@ public function settingHandle(): void */ public function settingMarkup(): array { + $allEventKeyboard = [ + $this->telegram->buildInlineKeyBoardButton( + $this->setting->settings['all_events_notify'] + ? '✅ Enable All Events Notify' : 'Enable All Events Notify', + '', + $this->setting::SETTING_ALL_EVENTS_NOTIFY + ), + ]; + + if (!$this->setting->settings['all_events_notify']) { + $allEventKeyboard[] = $this->telegram->buildInlineKeyBoardButton( + '⚙ Custom individual events', + '', + $this->setting::SETTING_CUSTOM_EVENTS + ); + } + return [ [ $this->telegram->buildInlineKeyBoardButton( - $this->settingConfig['is_notified'] + $this->setting->settings['is_notified'] ? '✅ Github notification' : 'Github notification', '', $this->setting::SETTING_IS_NOTIFIED ), ], - [ - $this->telegram->buildInlineKeyBoardButton( - $this->settingConfig['all_events_notify'] - ? '✅ Enable All Events Notify' - : 'Enable All Events Notify', - '', - $this->setting::SETTING_ALL_EVENTS_NOTIFY - ), - $this->telegram->buildInlineKeyBoardButton( - '⚙ Custom individual events', - '', - $this->setting::SETTING_CUSTOM_EVENTS - ), - ], + $allEventKeyboard, [ $this->telegram->buildInlineKeyBoardButton( '🔙 Back to menu', @@ -90,7 +91,7 @@ public function settingCallbackHandler(string $callback): void $callback = str_replace($this->setting::SETTING_PREFIX, '', $callback); - if ($this->updateSettingItem($callback, !$this->settingConfig[$callback])) { + if ($this->setting->updateSettingItem($callback, !$this->setting->settings[$callback])) { $this->editMessageReplyMarkup([ 'reply_markup' => $this->settingMarkup(), ]); @@ -99,53 +100,6 @@ public function settingCallbackHandler(string $callback): void } } - /** - * Update setting item value and save to file - * - * @param string $settingName - * @param $settingValue - * @return bool - */ - public function updateSettingItem(string $settingName, $settingValue = null): bool - { - $keys = explode('.', $settingName); - $lastKey = array_pop($keys); - $nestedSettings = &$this->settingConfig; - - foreach ($keys as $key) { - if (!isset($nestedSettings[$key]) || !is_array($nestedSettings[$key])) { - return false; - } - $nestedSettings = &$nestedSettings[$key]; - } - - if (isset($nestedSettings[$lastKey])) { - $nestedSettings[$lastKey] = $settingValue ?? !$nestedSettings[$lastKey]; - if ($this->saveSettingsToFile()) { - return true; - } - } - - return false; - } - - /** - * Save settings to json file - * - * @return bool - */ - private function saveSettingsToFile(): bool - { - if (file_exists($this->setting::SETTING_FILE)) { - $json = json_encode($this->settingConfig, JSON_PRETTY_PRINT); - file_put_contents($this->setting::SETTING_FILE, $json, LOCK_EX); - - return true; - } - - return false; - } - /** * Answer the back button *