PHP code example of alexitdev91 / laravel-telegram-bot

1. Go to this page and download the library: Download alexitdev91/laravel-telegram-bot library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alexitdev91 / laravel-telegram-bot example snippets


return [
    App\Providers\AppServiceProvider::class,
    AlexItDev91\LaravelTelegramBot\Laravel\TelegramBotServiceProvider::class,
];

use AlexItDev91\LaravelTelegramBot\TelegramBot;

final class SendTelegramAlert
{
    public function __construct(
        private TelegramBot $telegram,
    ) {
    }

    public function __invoke(): void
    {
        $this->telegram->channel('inbox')->sendMessage([
            'text' => 'New inbound email',
        ]);
    }
}

use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;

TelegramBot::bot('support')->sendMessage([
    'chat_id' => '-1001234567890',
    'text' => 'New message',
]);

TelegramBot::channel('inbox')->sendMessage([
    'text' => 'New inbound email',
]);

use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;

$token = $tenant->telegram_bot_token;
$chatId = (string) $tenant->telegram_channel_id;

TelegramBot::to($chatId, token: $token)->sendMessage([
    'text' => 'Tenant alert',
]);

use AlexItDev91\LaravelTelegramBot\TelegramBot;

final readonly class TenantAlert
{
    public function __construct(private TelegramBot $telegram)
    {
    }

    public function send(Tenant $tenant): mixed
    {
        return $this->telegram->to(
            chatId: (string) $tenant->telegram_channel_id,
            token: $tenant->telegram_bot_token,
        )->sendMessage([
            'text' => 'Tenant alert',
        ]);
    }
}

TelegramBot::botToken($token)->sendMessage([
    'chat_id' => $chatId,
    'text' => 'Direct dynamic payload',
]);

TelegramBot::channel('inbox', token: $token)->sendMessage([
    'text' => 'Configured destination, dynamic bot',
]);

TelegramBot::channel('alerts')->text('Deploy finished');

TelegramBot::to('-1001234567890', token: $tenantBotToken)
    ->photo('photo-file-id', caption: 'Daily report');

TelegramBot::document('document-file-id', caption: 'Invoice', to: '-1001234567890');

use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;
use AlexItDev91\LaravelTelegramBot\Outbound\TelegramMessage;

final class TelegramOpsAlert
{
    private const string TEXT_DEPLOY_FINISHED = 'Deploy finished';

    private const string PHOTO_FILE_ID = 'photo-file-id';

    private const string DOCUMENT_FILE_ID = 'document-file-id';

    public function send(string $tenantBotToken): void
    {
        TelegramBot::channel('alerts')->send(
            TelegramMessage::text(self::TEXT_DEPLOY_FINISHED),
        );

        TelegramBot::to('-1001234567890', token: $tenantBotToken)->send(
            TelegramMessage::photo(self::PHOTO_FILE_ID)->caption('Daily report'),
        );

        TelegramBot::botToken($tenantBotToken)->send(
            TelegramMessage::document(self::DOCUMENT_FILE_ID)
                ->to('-1001234567890')
                ->caption('Invoice'),
        );
    }
}

$user = TelegramBot::getMeData();
$message = TelegramBot::channel('alerts')->sendMessageData([
    'text' => 'Deploy finished',
]);

$messageId = $message->messageId();
$chatId = $message->chat()?->id();

$file = TelegramBot::getFileData(['file_id' => 'telegram-file-id']);

if ($file->filePath() !== null) {
    TelegramBot::downloadFileTo($file->filePath(), storage_path('app/telegram/report.pdf'));
}

use AlexItDev91\LaravelTelegramBot\MiniApps\TelegramMiniAppInitDataValidator;
use Illuminate\Http\Request;

final readonly class TelegramMiniAppSessionController
{
    public function __construct(
        private TelegramMiniAppInitDataValidator $telegramMiniApps,
    ) {
    }

    public function __invoke(Request $request): array
    {
        $data = $this->telegramMiniApps->validate(
            initData: (string) $request->string('initData'),
            botToken: (string) config('telegram-bot.token'),
            maxAgeSeconds: 300,
        );

        return [
            'telegram_user_id' => (string) $data->user()?->id(),
            'start_param' => $data->startParam(),
        ];
    }
}

use AlexItDev91\LaravelTelegramBot\DeepLinks\TelegramDeepLink;
use AlexItDev91\LaravelTelegramBot\DeepLinks\TelegramStartPayloadSigner;

final readonly class ReferralLinkFactory
{
    public function __construct(
        private TelegramStartPayloadSigner $payloads,
    ) {
    }

    public function link(string $referralCode): string
    {
        $payload = $this->payloads->sign(
            payload: $referralCode,
            secret: (string) config('app.key'),
            ttlSeconds: 3600,
        );

        return TelegramDeepLink::start('CompanyBot', $payload)->url();
    }
}

use AlexItDev91\LaravelTelegramBot\Enums\TelegramParseMode;
use AlexItDev91\LaravelTelegramBot\Laravel\Notifications\TelegramBotNotificationChannel;
use AlexItDev91\LaravelTelegramBot\Laravel\Notifications\TelegramNotificationMessage;
use Illuminate\Notifications\Notification;

class DeployFinished extends Notification
{
    private const string CHANNEL = 'alerts';

    private const string TEXT = 'Deploy finished';

    public function via(object $notifiable): array
    {
        return [TelegramBotNotificationChannel::class];
    }

    public function toTelegram(object $notifiable): TelegramNotificationMessage
    {
        return TelegramNotificationMessage::text(self::TEXT)
            ->channel(self::CHANNEL)
            ->parseMode(TelegramParseMode::HTML);
    }
}

use AlexItDev91\LaravelTelegramBot\DTO\Messages\InlineKeyboardMarkup;
use AlexItDev91\LaravelTelegramBot\DTO\Messages\LinkPreviewOptions;
use AlexItDev91\LaravelTelegramBot\DTO\Messages\SendMessageData;
use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;
use AlexItDev91\LaravelTelegramBot\Support\TelegramCallbackData;

final class DeployAlert
{
    private const string BOT = 'support';

    private const string BUTTON_RETRY = 'Retry';

    private const string BUTTON_OPEN = 'Open run';

    private const string CALLBACK_RETRY = 'deploy:retry';

    private const string CHAT_ID = '-1001234567890';

    private const int RUN_ID = 42;

    private const string RUN_URL = 'https://example.test/runs/42';

    private const string TEXT = 'Build failed';

    public function send(): mixed
    {
        return TelegramBot::bot(self::BOT)->sendMessage(new SendMessageData(
            chatId: self::CHAT_ID,
            text: self::TEXT,
            linkPreviewOptions: LinkPreviewOptions::disabled(),
            replyMarkup: InlineKeyboardMarkup::make()
                ->callback(self::BUTTON_RETRY, TelegramCallbackData::action(self::CALLBACK_RETRY)->with('run', self::RUN_ID))
                ->url(self::BUTTON_OPEN, self::RUN_URL),
        ));
    }
}

use AlexItDev91\LaravelTelegramBot\DTO\Requests\SendRichMessageRequestData;
use AlexItDev91\LaravelTelegramBot\DTO\Rich\InputRichMessage;
use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;

TelegramBot::bot('support')->sendRichMessage(SendRichMessageRequestData::make(
    chatId: '-1001234567890',
    richMessage: InputRichMessage::html('<h1>Deploy</h1><p>Finished</p>')
        ->skipEntityDetection(),
));

$message = $update->effectiveMessage();
$chatId = $update->effectiveChat()?->id();
$user = $update->effectiveUser();
$callbackData = $update->callbackQuery()?->data();
$preCheckoutId = $update->preCheckoutQueryData()?->id();
$inlineQuery = $update->inlineQuery()?->query();
$pollId = $update->poll()?->id();
$boostId = $update->chatBoost()?->boostData()?->boostId();
$text = $message?->text();
$documentName = $message?->documentData()?->fileName();
$paymentCharge = $message?->successfulPaymentData()?->telegramPaymentChargeId();

use AlexItDev91\LaravelTelegramBot\Laravel\TelegramWebhookReply;

return TelegramWebhookReply::fromUpdate($update)->text('Ready.');
return TelegramWebhookReply::fromUpdate($update)->answerCallback('Saved.');
return TelegramWebhookReply::method('sendChatAction', ['chat_id' => $chatId, 'action' => 'typing']);

use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;

TelegramBot::bot('default')->setWebhook([
    'url' => route('telegram-bot.webhook'),
    'secret_token' => config('telegram-bot.webhook.secret_token'),
    'allowed_updates' => ['message', 'callback_query'],
]);

use AlexItDev91\LaravelTelegramBot\InputFile;

$telegram->bot('support')->sendMediaGroup([
    'chat_id' => '-1001234567890',
    'media' => [
        [
            'type' => 'photo',
            'media' => InputFile::fromPath(storage_path('app/photo.jpg')),
        ],
    ],
]);

$telegram->bot('support')->sendDocument([
    'chat_id' => '-1001234567890',
    'document' => InputFile::fromContents('generated report', 'report.txt', 'text/plain'),
]);

$file = $telegram->bot('support')->getFileData(['file_id' => 'telegram-file-id']);

if ($file->filePath() !== null) {
    $telegram->bot('support')->downloadFileTo(
        $file->filePath(),
        storage_path('app/telegram/report.pdf'),
    );
}

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;

$this->app->bind(ClientInterface::class, fn (): ClientInterface => new Client([
    'timeout' => 5,
    'http_errors' => false,
]));

use AlexItDev91\LaravelTelegramBot\Facades\TelegramBot;

$fake = TelegramBot::fake();

TelegramBot::bot('support')->sendMessage([
    'chat_id' => '123456789',
    'text' => 'Hello support',
]);

$fake->assertCalled('sendMessage', function (array $parameters, string $botName): bool {
    return $botName === 'support'
        && $parameters['text'] === 'Hello support';
});

TelegramBot::channel('alerts')->sendMessage([
    'text' => 'Deploy finished',
]);

$fake->assertSentMessageToChannel('alerts', function (array $parameters): bool {
    return $parameters['chat_id'] === '-1001234567890'
        && $parameters['text'] === 'Deploy finished';
});
bash
php artisan vendor:publish --provider="AlexItDev91\\LaravelTelegramBot\\Laravel\\TelegramBotServiceProvider" --tag=telegram-bot-config
bash
php artisan telegram-bot:install
bash
php artisan boost:install
bash
php artisan boost:update