Skip to content

Commit ebae288

Browse files
authored
Merge pull request #11 from WizardLoop/dev
Refactor bot initialization into RunBot() with proper logging and exception handling
2 parents 98a8217 + cc1be78 commit ebae288

1 file changed

Lines changed: 154 additions & 60 deletions

File tree

bot.php

Lines changed: 154 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -3481,41 +3481,71 @@ public function cron4(): void {
34813481

34823482
#[FilterCommandCaseInsensitive('donate')]
34833483
public function Payments(Incoming & PrivateMessage $message): void {
3484-
$senderid = $message->senderId;
3485-
$messageid = $message->id;
34863484
try {
3485+
$messagetext = $message->message;
3486+
$messageid = $message->id;
3487+
$messagefile = $message->media;
3488+
$senderid = $message->senderId;
3489+
$grouped_id = $message->groupedId;
3490+
$User_Full = $this->getInfo($message->senderId);
3491+
$first_name = $User_Full['User']['first_name']?? null;
3492+
if($first_name == null){
3493+
$first_name = "null";
3494+
}
3495+
$last_name = $User_Full['User']['last_name']?? null;
3496+
if($last_name == null){
3497+
$last_name = "null";
3498+
}
3499+
3500+
$username = $User_Full['User']['username'] ?? ($User_Full['User']['usernames'][0]['username'] ?? "(null)");
3501+
34873502
$originalString = $senderid;
34883503
$encodedString = $originalString;
3504+
34893505
$labeledPrice1 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 5];
34903506
$invoice1 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice1],];
3507+
34913508
$labeledPrice2 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 25];
34923509
$invoice2 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice2],];
3510+
34933511
$labeledPrice3 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 100];
34943512
$invoice3 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice3],];
3513+
34953514
$labeledPrice4 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 150];
34963515
$invoice4 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice4],];
3516+
34973517
$labeledPrice5 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 250];
34983518
$invoice5 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice5],];
3519+
34993520
$labeledPrice6 = ['_' => 'labeledPrice', 'label' => 'star', 'amount' => 400];
35003521
$invoice6 = ['_' => 'invoice', 'currency' => 'XTR', 'prices' => [$labeledPrice6],];
3501-
$inputMediaInvoice1 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 5 ⭐️', 'invoice' => $invoice1, 'payload' => "$encodedString", 'provider_data' => 'test'];
3502-
$inputMediaInvoice2 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 25 ⭐️', 'invoice' => $invoice2, 'payload' => "$encodedString", 'provider_data' => 'test'];
3503-
$inputMediaInvoice3 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 100 ⭐️', 'invoice' => $invoice3, 'payload' => "$encodedString", 'provider_data' => 'test'];
3504-
$inputMediaInvoice4 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 150 ⭐️', 'invoice' => $invoice4, 'payload' => "$encodedString", 'provider_data' => 'test'];
3505-
$inputMediaInvoice5 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 250 ⭐️', 'invoice' => $invoice5, 'payload' => "$encodedString", 'provider_data' => 'test'];
3506-
$inputMediaInvoice6 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בי', 'description' => 'תמכו בי ב 400 ⭐️', 'invoice' => $invoice6, 'payload' => "$encodedString", 'provider_data' => 'test'];
3522+
3523+
$inputMediaInvoice1 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 5 ⭐️', 'invoice' => $invoice1, 'payload' => "donate|$senderid|5", 'provider_data' => 'test'];
3524+
$inputMediaInvoice2 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 25 ⭐️', 'invoice' => $invoice2, 'payload' => "donate|$senderid|25", 'provider_data' => 'test'];
3525+
$inputMediaInvoice3 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 100 ⭐️', 'invoice' => $invoice3, 'payload' => "donate|$senderid|100", 'provider_data' => 'test'];
3526+
$inputMediaInvoice4 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 150 ⭐️', 'invoice' => $invoice4, 'payload' => "donate|$senderid|150", 'provider_data' => 'test'];
3527+
$inputMediaInvoice5 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 250 ⭐️', 'invoice' => $invoice5, 'payload' => "donate|$senderid|250", 'provider_data' => 'test'];
3528+
$inputMediaInvoice6 = ['_' => 'inputMediaInvoice', 'title' => 'תמכו בנו!', 'description' => 'תמכו בנו ב - 400 ⭐️', 'invoice' => $invoice6, 'payload' => "donate|$senderid|400", 'provider_data' => 'test'];
3529+
3530+
35073531
$payments_ExportedInvoice1 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice1, );
3508-
$urlexp1 = $payments_ExportedInvoice1['url'];
3532+
$urlexp1 = $payments_ExportedInvoice1['url']; //5
3533+
35093534
$payments_ExportedInvoice2 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice2, );
3510-
$urlexp2 = $payments_ExportedInvoice2['url'];
3535+
$urlexp2 = $payments_ExportedInvoice2['url']; //25
3536+
35113537
$payments_ExportedInvoice3 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice3, );
3512-
$urlexp3 = $payments_ExportedInvoice3['url'];
3538+
$urlexp3 = $payments_ExportedInvoice3['url']; //100
3539+
35133540
$payments_ExportedInvoice4 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice4, );
3514-
$urlexp4 = $payments_ExportedInvoice4['url'];
3541+
$urlexp4 = $payments_ExportedInvoice4['url']; //150
3542+
35153543
$payments_ExportedInvoice5 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice5, );
3516-
$urlexp5 = $payments_ExportedInvoice5['url'];
3544+
$urlexp5 = $payments_ExportedInvoice5['url']; //250
3545+
35173546
$payments_ExportedInvoice6 = $this->payments->exportInvoice(invoice_media: $inputMediaInvoice6, );
3518-
$urlexp6 = $payments_ExportedInvoice6['url'];
3547+
$urlexp6 = $payments_ExportedInvoice6['url']; //400
3548+
35193549

35203550
$bot_API_markup = ['inline_keyboard' =>
35213551
[
@@ -3529,66 +3559,91 @@ public function Payments(Incoming & PrivateMessage $message): void {
35293559
];
35303560

35313561
$inputReplyToMessage = ['_' => 'inputReplyToMessage', 'reply_to_msg_id' => $messageid];
3532-
$this->messages->sendMessage(no_webpage: true, peer: $message->senderId, reply_to: $inputReplyToMessage, message: "היי, תודה שאתם רוצים לתרום לי🥰
3533-
בחרו את סכום התרומה שתרצו לתת👇", reply_markup: $bot_API_markup, parse_mode: 'HTML', effect: 5159385139981059251) ;
3534-
} catch (Throwable $e) {
3535-
$error = $e->getMessage();
3536-
$sentMessage = $this->messages->sendMessage(peer: $message->senderId, message: $error);
3537-
}
3538-
}
3562+
$sentMessage = $this->messages->sendMessage(peer: $senderid, reply_to: $inputReplyToMessage, message: "היי, תודה שאתם רוצים לתמוך בנו 🥰
3563+
בחרו את סכום התרומה שתרצו לתת 👇", reply_markup: $bot_API_markup, parse_mode: 'HTML', effect: 5159385139981059251);
35393564

3565+
} catch (Throwable $e) {}
3566+
}
35403567
public function onupdateBotPrecheckoutQuery($update) {
3541-
try {
3568+
try{
3569+
if ($this->isSelfBot()) {
35423570
$userid = $update['user_id'];
35433571
$total_amount = $update['total_amount'];
3544-
$query_id = $update['query_id'];
3545-
$payload = $update['payload'];
3546-
$User_Full = $this->getInfo($userid);
3572+
$query_id = $update['query_id'];
3573+
$sucses = $this->messages->setBotPrecheckoutResults(success: true, query_id: $query_id);
3574+
}
3575+
} catch (\Throwable $e) {}
3576+
}
3577+
public function onUpdateNewMessage($update) {
3578+
try{
3579+
if ($this->isSelfBot()) {
3580+
$msg = $update['message'];
3581+
$messageId = $msg['id'];
3582+
$userId = $msg['from_id'] ?? null;
3583+
3584+
$User_Full = $this->getInfo($userId);
35473585
$first_name = $User_Full['User']['first_name']?? null;
35483586
if($first_name == null){
35493587
$first_name = "null";
35503588
}
35513589

3552-
try {
3553-
$usernames = $User_Full['User']['usernames']?? null;
3554-
$newLangsCommausername = null;
3555-
$peerList2username = [];
3556-
foreach ($usernames as $username) {
3557-
$usernamexfr = $username['username'];
3558-
$usernamexfr = "@".$usernamexfr;
3559-
$peerList2username[]=$usernamexfr;
3560-
}
3561-
$newLangsCommausername = implode(" ", $peerList2username);
3562-
}catch (\danog\MadelineProto\Exception $e) {
3563-
} catch (\danog\MadelineProto\RPCErrorException $e) {
3564-
}
3565-
$username = $User_Full['User']['username']?? null;
3566-
if($username == null){
3567-
if($newLangsCommausername != null){
3568-
$username = $newLangsCommausername;
3569-
}else{
3590+
$username = $User_Full['User']['username'] ?? ($User_Full['User']['usernames'][0]['username'] ?? null);
3591+
if($username === null){
35703592
$username = "(null)";
3571-
}
35723593
}else{
35733594
$username = "@".$username;
35743595
}
35753596

3576-
$sucses = $this->messages->setBotPrecheckoutResults(success: true, query_id: $query_id);
3597+
if (isset($msg['action']['_']) && $msg['action']['_'] === 'messageActionPinMessage') {
3598+
3599+
$botId = $this->getSelf()['id'];
3600+
3601+
$actorId = $msg['from_id'] ?? null;
3602+
3603+
if ($actorId == $botId) {
3604+
$serviceMessageId = $msg['id'];
3605+
try {
3606+
$this->messages->deleteMessages(['id' => [$serviceMessageId], 'revoke' => true]);
3607+
} catch (\Throwable $e) {}
3608+
}
3609+
}
3610+
3611+
if (isset($msg['action']['_']) && $msg['action']['_'] === 'messageActionPaymentSentMe') {
3612+
$amount = $msg['action']['total_amount'];
3613+
$currency = $msg['action']['currency'];
3614+
$payload = (string) $msg['action']['payload'];
3615+
$charge = $msg['action']['charge']['id'];
3616+
echo $charge;
3617+
$parts = explode('|', $payload);
3618+
if (count($parts) < 3) return;
3619+
$type = $parts[0];
3620+
$uid = $parts[1];
3621+
$price = (int)$parts[2];
3622+
3623+
if($amount != $price){
3624+
return;
3625+
}
3626+
3627+
if($type == 'payment'){
3628+
$credits = (int)$parts[3];
3629+
$orderid = (int)$parts[4];
35773630

3578-
if($sucses == true){
3579-
$this->messages->sendMessage(peer: $userid, message: "<b>סכום:</b> $total_amount ⭐️
3631+
}
3632+
elseif($type == 'donate'){
3633+
$inputReplyToMessage = ['_' => 'inputReplyToMessage', 'reply_to_msg_id' => $messageId];
3634+
$this->messages->sendMessage(peer: $userId, reply_to: $inputReplyToMessage, message: "<b>amount:</b> $amount ⭐️
35803635
🎉 תודה על תרומתך 🎉", parse_mode: 'HTML', effect: 5159385139981059251);
35813636

3582-
$this->sendMessageToAdmins("<b>תרומה התקבלה! 🎉</b>
3583-
FIRSTNAME: <a href='mention:$userid'>$first_name </a>
3584-
ID: <a href='mention:$userid'>$userid </a>
3637+
$this->sendMessageToAdmins("<b>תרומה התקבלה במערכת! 🎉</b>
3638+
FIRSTNAME: <a href='mention:$userId'>$first_name </a>
3639+
ID: <a href='mention:$userId'>$userId </a>
35853640
USERNAME: $username
3586-
<b>סכום:</b> $total_amount ⭐️",parseMode: ParseMode::HTML);
3641+
<b>סכום:</b> $amount ⭐️",parseMode: ParseMode::HTML);
35873642
}
35883643

3589-
} catch (Throwable $e) {
3590-
$error = $e->getMessage();
3591-
}
3644+
}
3645+
}
3646+
} catch (\Throwable $e) {}
35923647
}
35933648

35943649
#########################################
@@ -4223,11 +4278,11 @@ public function StatsUsers(callbackQuery $query)
42234278
}
42244279

42254280
#[FilterButtonQueryData('closeMsg')]
4226-
public function closecommandbrod(callbackQuery $query) {
4281+
public function closeBroadcastMsg(callbackQuery $query) {
42274282
try {
42284283
$this->messages->deleteMessages(revoke: true, id: [$query->messageId]);
42294284
} catch (\Throwable $e) {
4230-
$query->answer($message = "אני לא יכול לסגור את ההודעה, סגור אותה בעצמך..", $alert = false, $url = null, $cacheTime = 0);
4285+
$query->answer($message = "I can't close the message, close it yourself.", $alert = false, $url = null, $cacheTime = 0);
42314286
}
42324287
}
42334288

@@ -4338,6 +4393,12 @@ public function setBroadcast(callbackQuery $query)
43384393
$first_name = "null";
43394394
}
43404395

4396+
$api = new \danog\MadelineProto\API(__DIR__.'/bot.madeline');
4397+
$manager = new BroadcastManager($api);
4398+
BroadcastManager::setDataDir(__DIR__ . '/data');
4399+
4400+
if(!$manager->progress()){
4401+
43414402
$bot_API_markup[] = [['text'=>"❌ ביטול ❌",'callback_data'=>"חזרהלפאנל"]];
43424403
$bot_API_markup = [ 'inline_keyboard'=> $bot_API_markup,];
43434404

@@ -4351,6 +4412,12 @@ public function setBroadcast(callbackQuery $query)
43514412
Amp\File\write(__DIR__."/data/$userid/grs1.txt", 'broadcast1');
43524413
$msgqutryid = $query->messageId;
43534414
Amp\File\write(__DIR__."/data/$userid/messagetodelete.txt", "$msgqutryid");
4415+
4416+
}else{
4417+
$message = "יש שידור פעיל כרגע אנא המתן..";
4418+
$query->answer($message = $message, $alert = true, $url = null, $cacheTime = 0);
4419+
}
4420+
43544421
} catch (Throwable $e) {}
43554422
}
43564423

@@ -4390,6 +4457,7 @@ public function handlebroadcast1(Incoming & PrivateMessage & FromAdmin $message)
43904457

43914458
if(!preg_match('/^\/([Ss]tart)/',$messagetext)){
43924459

4460+
43934461
$messageLength = mb_strlen($messagetext);
43944462

43954463
if($messageLength > 1024) {
@@ -4436,7 +4504,23 @@ public function handlebroadcast1(Incoming & PrivateMessage & FromAdmin $message)
44364504
}
44374505

44384506
}else{
4439-
unlink(__DIR__."/data/$senderid/grs1.txt");
4507+
4508+
if (file_exists(__DIR__."/data/$senderid/grs1.txt")) {
4509+
unlink(__DIR__."/data/$senderid/grs1.txt");
4510+
}
4511+
if (file_exists(__DIR__."/data/BUTTONS.txt")) {
4512+
unlink(__DIR__."/data/BUTTONS.txt");
4513+
}
4514+
if (file_exists(__DIR__."/data/$senderid/txt.txt")) {
4515+
unlink(__DIR__."/data/$senderid/txt.txt");
4516+
}
4517+
if (file_exists(__DIR__."/data/$senderid/ent.txt")) {
4518+
unlink(__DIR__."/data/$senderid/ent.txt");
4519+
}
4520+
if (file_exists(__DIR__."/data/$senderid/media.txt")) {
4521+
unlink(__DIR__."/data/$senderid/media.txt");
4522+
}
4523+
44404524

44414525
if($messagetext != null){
44424526
Amp\File\write(__DIR__."/data/$senderid/txt.txt", "$messagetext");
@@ -4759,8 +4843,6 @@ public function hosafkaf(callbackQuery $query)
47594843
$first_name = "null";
47604844
}
47614845

4762-
$buttons = __DIR__."/data/menubuttons1.txt";
4763-
47644846
$bot_API_markup[] = [['text'=>"❌ ביטול ❌",'callback_data'=>"חזרהתפריטשידור"]];
47654847
$bot_API_markup = [ 'inline_keyboard'=> $bot_API_markup,];
47664848

@@ -5170,10 +5252,22 @@ function RunBot(): void {
51705252
$BOT_TOKEN = parse_ini_file(__DIR__."/".'.env')['BOT_TOKEN'];
51715253
$settings = new \danog\MadelineProto\Settings;
51725254
$settings->setAppInfo((new \danog\MadelineProto\Settings\AppInfo)->setApiId((int)$API_ID)->setApiHash($API_HASH));
5255+
5256+
$logger = (new \danog\MadelineProto\Settings\Logger)->setLevel(\danog\MadelineProto\Logger::ERROR);
5257+
$settings->setLogger($logger);
5258+
51735259
Shabbat::startAndLoopBot(__DIR__.'/bot.madeline', $BOT_TOKEN, $settings);
51745260

51755261
} catch (\Throwable $e) {
5176-
echo "\n" . $e->getMessage() . "\n";
5262+
if ($e instanceof \Amp\TimeoutException || $e instanceof \Amp\CancelledException) {
5263+
5264+
// \Amp\Future\complete(\Amp\delay(3.0)->then(fn() => exit(1)));
5265+
// return;
5266+
5267+
exit(1);
5268+
}
5269+
5270+
// echo "\n" . $e->getMessage() . "\n";
51775271
}
51785272
}
51795273
RunBot();

0 commit comments

Comments
 (0)