Skip to content

Commit d99ab18

Browse files
committed
Updated CrashPad class and Changed a few things
1 parent f59959a commit d99ab18

15 files changed

+278
-211
lines changed

src/CrashPad.php

Lines changed: 86 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33

44
namespace TelegramBot;
55

6+
use Exception;
67
use Symfony\Component\Dotenv\Dotenv;
8+
use Throwable;
79

810
/**
911
* CrashPad class
@@ -16,16 +18,28 @@ class CrashPad
1618
{
1719

1820
/**
19-
* Clear crash files.
21+
* Enable the crash handler
2022
*
2123
* @return void
2224
*/
23-
public static function clearCrashFiles(): void
25+
public static function enableCrashHandler(): void
2426
{
25-
$files = glob(getcwd() . '.telegram-bot/*.log');
26-
foreach ($files as $file) {
27-
unlink($file);
28-
}
27+
$handler = function (Throwable $throwable) {
28+
if (Telegram::getAdminId() !== -1) {
29+
$input = getenv('TG_CURRENT_UPDATE') ?? Telegram::getInput();
30+
CrashPad::sendCrash(Telegram::getAdminId(), $throwable, $input);
31+
}
32+
33+
if (!defined('DEBUG_MODE')) {
34+
throw new \RuntimeException(
35+
'Something went wrong, Unfortunately, we can not handle this error.', 0, $throwable
36+
);
37+
}
38+
39+
CrashPad::print($throwable);
40+
};
41+
42+
set_exception_handler($handler);
2943
}
3044

3145
/**
@@ -44,35 +58,19 @@ public static function setDebugMode(int $admin_id = -1): void
4458
Telegram::setAdminId($admin_id);
4559
}
4660

47-
set_exception_handler(function (\Throwable $throwable) {
48-
if (!defined('DEBUG_MODE') && !DEBUG_MODE) {
49-
throw new \RuntimeException(
50-
$throwable->getMessage(),
51-
$throwable->getCode(),
52-
$throwable->getPrevious()
53-
);
54-
} else {
55-
if (Telegram::getAdminId() !== -1) {
56-
$input = getenv('TG_CURRENT_UPDATE') ?? Telegram::getInput();
57-
$update = Telegram::processUpdate($input, Telegram::getApiToken());
58-
$exception = new \Exception($throwable->getMessage(), $throwable->getCode(), $throwable->getPrevious());
59-
CrashPad::sendCrash(Telegram::getAdminId(), $exception, json_encode($update));
60-
CrashPad::report($exception);
61-
}
62-
}
63-
});
61+
self::enableCrashHandler();
6462
}
6563

6664
/**
6765
* Send crash message and log
6866
*
6967
* @param int $chat_id The chat id of the group to send the message to.
70-
* @param \Exception|\Throwable $exception The exception to report.
68+
* @param Exception|Throwable $exception The exception to report.
7169
* @param string|null $update (Optional) The update that caused the exception.
7270
*
7371
* @retrun bool
7472
*/
75-
public static function sendCrash(int $chat_id, \Exception|\Throwable $exception, string|null $update = null): bool
73+
public static function sendCrash(int $chat_id, Exception|Throwable $exception, string|null $update = null): bool
7674
{
7775
if ($chat_id === -1) {
7876
throw new \RuntimeException(sprintf(
@@ -86,29 +84,39 @@ public static function sendCrash(int $chat_id, \Exception|\Throwable $exception,
8684
Telegram::setToken($_ENV['TELEGRAM_BOT_TOKEN']);
8785
}
8886

87+
if (($token = self::loadToken()) === null) {
88+
throw new \RuntimeException(
89+
'The token is not set. Please set the token using `Telegram::setToken()` method.'
90+
);
91+
}
92+
8993
$text = Request::sendMessage([
94+
'bot_token' => $token,
9095
'chat_id' => $chat_id,
9196
'parse_mode' => 'HTML',
92-
'text' => ($message = sprintf(
97+
'text' => sprintf(
9398
"<b>Message</b>: %s\n\n<b>File</b>: %s(%d)\n\n<b>Trace</b>: \n%s",
9499
$exception->getMessage(),
95100
$exception->getFile(),
96101
$exception->getLine(),
97102
$exception->getTraceAsString()
98-
)),
103+
),
99104
]);
100105

101-
if ($update !== null) {
102-
$document = Request::sendDocument([
103-
'chat_id' => $chat_id,
104-
'document' => self::createCrashFile(
105-
$message . "\n\n" . $update
106-
),
107-
]);
108-
return $text->isOk() && $document->isOk();
109-
}
106+
$document = Request::sendDocument([
107+
'bot_token' => $token,
108+
'chat_id' => $chat_id,
109+
'document' => self::createCrashFile(sprintf(
110+
"Message: %s\n\nFile: %s(%d)\n\nTrace: \n%s\n\nUpdate: \n%s",
111+
$exception->getMessage(),
112+
$exception->getFile(),
113+
$exception->getLine(),
114+
$exception->getTraceAsString(),
115+
$update ?? 'Did not receive update.'
116+
)),
117+
]);
110118

111-
return $text->isOk();
119+
return $text->isOk() && $document->isOk();
112120
}
113121

114122
/**
@@ -131,10 +139,10 @@ private static function createCrashFile(string $content): string
131139
/**
132140
* Report the error to the developers from the Telegram Bot API.
133141
*
134-
* @param \Exception|\Throwable $exception The exception to report.
142+
* @param Exception|Throwable $exception The exception to report.
135143
* @retrun void
136144
*/
137-
public static function report(\Exception|\Throwable $exception): void
145+
public static function print(Exception|Throwable $exception): void
138146
{
139147
TelegramLog::error(($message = sprintf(
140148
"%s(%d): %s\n%s",
@@ -146,4 +154,43 @@ public static function report(\Exception|\Throwable $exception): void
146154
echo '<b>TelegramError:</b> ' . $message;
147155
}
148156

157+
/**
158+
* Clear the crash logs.
159+
*
160+
* @return void
161+
*/
162+
public static function clearCrashLogs(): void
163+
{
164+
$base_path = $_SERVER['DOCUMENT_ROOT'] . '.telegram-bot/';
165+
if (!file_exists($base_path)) {
166+
return;
167+
}
168+
169+
$files = glob($base_path . '*');
170+
foreach ($files as $file) {
171+
if (is_file($file)) {
172+
unlink($file);
173+
}
174+
}
175+
}
176+
177+
/**
178+
* Check is there any loaded token or any token in the environment file.
179+
*
180+
* @return string|null
181+
*/
182+
private static function loadToken(): string|null
183+
{
184+
if (($token = Telegram::getApiToken()) !== false) {
185+
return $token;
186+
}
187+
188+
if (file_exists(Telegram::getEnvFilePath())) {
189+
(new Dotenv())->load(Telegram::getEnvFilePath());
190+
return $_ENV['TELEGRAM_BOT_TOKEN'] ?? null;
191+
}
192+
193+
return null;
194+
}
195+
149196
}

src/Entities/InlineKeyboardButton.php

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,7 @@
2323
* @method bool getPay() Optional. Specify True, to send a Pay button.
2424
*
2525
* @method InlineKeyboardButton setText(string $text) Label text on the button
26-
* @method InlineKeyboardButton setUrl(string $url) Optional. HTTP url to be opened when button is pressed
2726
* @method InlineKeyboardButton setLoginUrl(LoginUrl $login_url) Optional. HTTP url to be opened when button is pressed
28-
* @method InlineKeyboardButton setCallbackData(string $callback_data) Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
29-
* @method InlineKeyboardButton setWebApp(WebAppInfo $web_app) Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot.
3027
* @method InlineKeyboardButton setSwitchInlineQuery(string $switch_inline_query) Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted.
3128
* @method InlineKeyboardButton setSwitchInlineQueryCurrentChat(string $switch_inline_query_current_chat) Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted.
3229
* @method InlineKeyboardButton setCallbackGame(CallbackGame $callback_game) Optional. Description of the game that will be launched when the user presses the button.
@@ -68,32 +65,40 @@ public static function couldBe(array $data): bool
6865
}
6966

7067
/**
68+
* Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
69+
*
7170
* @param string $data
7271
* @return $this
7372
*/
74-
public function CallbackData(string $data): InlineKeyboardButton
73+
public function setCallbackData(string $data): InlineKeyboardButton
7574
{
7675
$this->raw_data['callback_data'] = $data;
7776

7877
return $this;
7978
}
8079

8180
/**
81+
* Optional. HTTP url to be opened when button is pressed
82+
*
8283
* @param string $data
8384
* @return $this
8485
*/
85-
public function Url(string $data): InlineKeyboardButton
86+
public function setUrl(string $data): InlineKeyboardButton
8687
{
8788
$this->raw_data['url'] = $data;
8889

8990
return $this;
9091
}
9192

9293
/**
94+
* Optional. Description of the Web App that will be launched when the user presses the button. The Web App will
95+
* be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only
96+
* in private chats between a user and the bot.
97+
*
9398
* @param string $url
9499
* @return $this
95100
*/
96-
public function WebApp(string $url): KeyboardButton
101+
public function setWebApp(string $url): KeyboardButton
97102
{
98103
$this->raw_data['web_app'] = new WebAppInfo(['url' => $url]);
99104

src/Entities/KeyboardButton.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
* @method $this setRequestContact(bool $request_contact) Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
3030
* @method $this setRequestLocation(bool $request_location) Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
3131
* @method $this setRequestPoll(KeyboardButtonPollType $request_poll) Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only
32-
* @method $this setWebApp(WebAppInfo $web_app) Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
3332
*/
3433
class KeyboardButton extends Entity
3534
{
@@ -70,10 +69,13 @@ public static function couldBe(array $data): bool
7069
}
7170

7271
/**
72+
* Optional. If specified, the described Web App will be launched when the button is pressed.
73+
* The Web App will be able to send a “web_app_data” service message. Available in private chats only.
74+
*
7375
* @param string $url
7476
* @return $this
7577
*/
76-
public function WebApp(string $url): KeyboardButton
78+
public function setWebApp(string $url): KeyboardButton
7779
{
7880
$this->raw_data['web_app'] = new WebAppInfo(['url' => $url]);
7981

src/Entities/Update.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
* @method ChatMemberUpdated getMyChatMember() Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
2828
* @method ChatMemberUpdated getChatMember() Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
2929
* @method ChatJoinRequest getChatJoinRequest() Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
30-
* @method WebAppData getWebData() Optional. The data from WebApp
30+
* @method WebAppData getWebAppData() Optional. The data from WebApp
3131
*/
3232
class Update extends Entity
3333
{
@@ -46,7 +46,7 @@ class Update extends Entity
4646
public const TYPE_MY_CHAT_MEMBER = 'my_chat_member';
4747
public const TYPE_CHAT_MEMBER = 'chat_member';
4848
public const TYPE_CHAT_JOIN_REQUEST = 'chat_join_request';
49-
public const TYPE_WEB_DATA = 'web_data';
49+
public const TYPE_WEB_DATA = 'web_app_data';
5050

5151
/**
5252
* Get the update type based on the set properties

src/Interfaces/PluginEventsInterface.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,9 @@ public function onPoll(int $update_id, Poll $poll): \Generator;
104104
public function onPollAnswer(int $update_id, PollAnswer $pollAnswer): \Generator;
105105

106106
/**
107-
* @param int $update_id
108107
* @param WebAppData $webAppData
109108
* @return \Generator
110109
*/
111-
public function onWebAppData(int $update_id, WebAppData $webAppData): \Generator;
110+
public function onWebAppData(WebAppData $webAppData): \Generator;
112111

113112
}

0 commit comments

Comments
 (0)