PHP code example of samuelterra22 / laravel-telegram-notifications

1. Go to this page and download the library: Download samuelterra22/laravel-telegram-notifications 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/ */

    

samuelterra22 / laravel-telegram-notifications example snippets


return [
    'default' => env('TELEGRAM_BOT', 'default'),

    'bots' => [
        'default' => [
            'token' => env('TELEGRAM_BOT_TOKEN'),
            'username' => env('TELEGRAM_BOT_USERNAME'),
            'chat_id' => env('TELEGRAM_CHAT_ID'),
            'topic_id' => env('TELEGRAM_TOPIC_ID'),
        ],
        'alerts' => [
            'token' => env('TELEGRAM_ALERTS_BOT_TOKEN'),
            'username' => env('TELEGRAM_ALERTS_BOT_USERNAME'),
            'chat_id' => env('TELEGRAM_ALERTS_CHAT_ID'),
        ],
    ],

    'api_base_url' => env('TELEGRAM_API_BASE_URL', 'https://api.telegram.org'),
    'timeout' => (int) env('TELEGRAM_TIMEOUT', 10),

    'logging' => [
        'enabled' => (bool) env('TELEGRAM_LOG_ENABLED', false),
        'bot' => env('TELEGRAM_LOG_BOT', 'default'),
        'chat_id' => env('TELEGRAM_LOG_CHAT_ID'),
        'topic_id' => env('TELEGRAM_LOG_TOPIC_ID'),
    ],

    'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),

    'retry' => [
        'max_attempts' => (int) env('TELEGRAM_RETRY_MAX_ATTEMPTS', 3),
        'base_delay_ms' => (int) env('TELEGRAM_RETRY_BASE_DELAY_MS', 1000),
        'use_jitter' => (bool) env('TELEGRAM_RETRY_USE_JITTER', true),
    ],
];

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Send a simple message
Telegram::sendMessage('-1001234567890', 'Hello from Laravel!');

// Send with fluent builder
Telegram::message('-1001234567890')
    ->html('<b>Hello!</b> Welcome to the app.')
    ->send();

// Send a photo
Telegram::sendPhoto('-1001234567890', 'https://example.com/photo.jpg', 'Caption');

// Use in a Laravel Notification
$user->notify(new OrderShipped($order));

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Simple message
Telegram::sendMessage('-1001234567890', 'Hello from Laravel!');

// Message with parse mode
Telegram::sendMessage('-1001234567890', '<b>Bold</b> and <i>italic</i>', 'HTML');

// Message to a forum topic
Telegram::sendMessage('-1001234567890', 'Error report', topicId: '42');

// Using a specific bot
Telegram::bot('alerts')->call('sendMessage', [
    'chat_id' => '-1001234567890',
    'text' => 'ALERT!',
]);

use Illuminate\Notifications\Notification;
use SamuelTerra22\TelegramNotifications\Messages\TelegramMessage;

class OrderShipped extends Notification
{
    public function __construct(private Order $order) {}

    public function via(mixed $notifiable): array
    {
        return ['telegram'];
    }

    public function toTelegram(mixed $notifiable): TelegramMessage
    {
        return TelegramMessage::create()
            ->bold('Order Shipped!')
            ->line('')
            ->line("Order #{$this->order->id}")
            ->line("Tracking: {$this->order->tracking_code}")
            ->button('Track Order', $this->order->tracking_url)
            ->button('View Order', route('orders.show', $this->order));
    }
}

// Via a notifiable model
$user->notify(new OrderShipped($order));

// On-demand (without a model)
Notification::route('telegram', '-1001234567890')
    ->notify(new OrderShipped($order));

public function routeNotificationForTelegram(): ?string
{
    return $this->telegram_chat_id;
}

public function toTelegram(mixed $notifiable): TelegramPhoto
{
    return TelegramPhoto::create()
        ->photo($this->order->receipt_image_url)
        ->caption("Receipt for Order #{$this->order->id}");
}

use SamuelTerra22\TelegramNotifications\Messages\TelegramMessage;

TelegramMessage::create()
    ->to('-1001234567890')
    ->bold('Title')
    ->line('Regular text')
    ->italic('Italic text')
    ->underline('Underlined')
    ->strikethrough('Deleted text')
    ->code('inline_code()')
    ->pre('echo "code block";', 'php')
    ->link('Click here', 'https://example.com')
    ->spoiler('Hidden text')
    ->quote('A blockquote')
    ->silent()
    ->protected()
    ->disableWebPagePreview()
    ->replyTo('42');

use SamuelTerra22\TelegramNotifications\Messages\TelegramPhoto;

TelegramPhoto::create()
    ->to('-1001234567890')
    ->photo('https://example.com/image.jpg') // URL or file_id
    ->caption('Photo caption')
    ->spoiler();

use SamuelTerra22\TelegramNotifications\Messages\TelegramDocument;

TelegramDocument::create()
    ->to('-1001234567890')
    ->document('https://example.com/report.pdf') // URL or file_id
    ->caption('Monthly report')
    ->thumbnail('https://example.com/thumb.jpg')
    ->disableContentTypeDetection();

use SamuelTerra22\TelegramNotifications\Messages\TelegramVideo;

TelegramVideo::create()
    ->to('-1001234567890')
    ->video('https://example.com/video.mp4') // URL or file_id
    ->caption('Check this out!')
    ->duration(120)
    ->width(1920)
    ->height(1080)
    ->dimensions(1920, 1080) // shortcut for width + height
    ->streaming()            // optimize for streaming playback
    ->spoiler();

use SamuelTerra22\TelegramNotifications\Messages\TelegramAudio;

TelegramAudio::create()
    ->to('-1001234567890')
    ->audio('https://example.com/song.mp3') // URL or file_id
    ->caption('Now playing')
    ->performer('Artist Name')
    ->title('Song Title')
    ->duration(240)
    ->thumbnail('https://example.com/cover.jpg');

use SamuelTerra22\TelegramNotifications\Messages\TelegramVoice;

TelegramVoice::create()
    ->to('-1001234567890')
    ->voice('https://example.com/voice.ogg') // URL or file_id
    ->caption('Voice message')
    ->duration(30);

use SamuelTerra22\TelegramNotifications\Messages\TelegramAnimation;

TelegramAnimation::create()
    ->to('-1001234567890')
    ->animation('https://example.com/animation.gif') // URL or file_id
    ->caption('Funny GIF')
    ->width(320)
    ->height(240)
    ->duration(5)
    ->thumbnail('https://example.com/thumb.jpg')
    ->spoiler();

use SamuelTerra22\TelegramNotifications\Messages\TelegramSticker;

TelegramSticker::create()
    ->to('-1001234567890')
    ->sticker('CAACAgIAAxkBAAI...') // file_id, URL, or sticker set name
    ->emoji('thumbs up');

use SamuelTerra22\TelegramNotifications\Messages\TelegramLocation;

TelegramLocation::create()
    ->to('-1001234567890')
    ->coordinates(-23.5505, -46.6333)   // latitude, longitude
    ->livePeriod(3600)                  // live location for 1 hour (60-86400 seconds)
    ->horizontalAccuracy(50.0)          // accuracy in meters (0-1500)
    ->heading(90)                       // direction in degrees (1-360)
    ->proximityAlertRadius(100);        // alert when within N meters

TelegramLocation::create()
    ->latitude(-23.5505)
    ->longitude(-46.6333);

use SamuelTerra22\TelegramNotifications\Messages\TelegramVenue;

TelegramVenue::create()
    ->to('-1001234567890')
    ->coordinates(-23.5505, -46.6333)
    ->title('Ibirapuera Park')
    ->address('Av. Pedro Alvares Cabral, Sao Paulo')
    ->foursquareId('4b5bc7eef964a520e22529e3')
    ->foursquareType('parks_outdoors/park')
    ->googlePlaceId('ChIJ...')
    ->googlePlaceType('park');

use SamuelTerra22\TelegramNotifications\Messages\TelegramContact;

TelegramContact::create()
    ->to('-1001234567890')
    ->phoneNumber('+5511999999999')
    ->firstName('Samuel')
    ->lastName('Terra')
    ->vcard("BEGIN:VCARD\nVERSION:3.0\nFN:Samuel Terra\nEND:VCARD");

use SamuelTerra22\TelegramNotifications\Messages\TelegramPoll;

// Regular poll
TelegramPoll::create()
    ->to('-1001234567890')
    ->question('What time works best?')
    ->options(['08:00', '10:00', '14:00', '16:00'])
    ->allowsMultipleAnswers()
    ->anonymous(false);

// Quiz mode (with correct answer)
TelegramPoll::create()
    ->to('-1001234567890')
    ->question('What is the capital of Brazil?')
    ->options(['Rio de Janeiro', 'Sao Paulo', 'Brasilia', 'Salvador'])
    ->quiz(2, 'Brasilia has been the capital since 1960'); // correct option index, explanation

// Auto-close poll
TelegramPoll::create()
    ->to('-1001234567890')
    ->question('Quick vote!')
    ->options(['Yes', 'No'])
    ->openPeriod(300)    // auto-close after 5 minutes
    // or ->closeDate($timestamp)  // close at specific time
    // or ->closed()               // send as already closed

use SamuelTerra22\TelegramNotifications\Messages\TelegramDice;

TelegramDice::create()
    ->to('-1001234567890')
    ->dice();          // random value 1-6
    // ->darts()       // random value 1-6
    // ->basketball()  // random value 1-5
    // ->football()    // random value 1-5
    // ->bowling()     // random value 1-6
    // ->slotMachine() // random value 1-64
    // ->emoji('custom')

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Video Note (round video)
Telegram::sendVideoNote($chatId, 'video_note_file_id');

// Media Group (album of photos/videos)
Telegram::sendMediaGroup($chatId, [
    ['type' => 'photo', 'media' => 'https://example.com/1.jpg', 'caption' => 'First'],
    ['type' => 'photo', 'media' => 'https://example.com/2.jpg'],
    ['type' => 'video', 'media' => 'https://example.com/video.mp4'],
]);

use SamuelTerra22\TelegramNotifications\Enums\ParseMode;

TelegramMessage::create()
    ->parseMode(ParseMode::MarkdownV2)
    ->content('*bold* _italic_ `code`');

use SamuelTerra22\TelegramNotifications\Keyboards\InlineKeyboard;

$keyboard = InlineKeyboard::make()
    ->url('Open App', 'https://app.example.com')
    ->url('Docs', 'https://docs.example.com')
    ->row()
    ->callback('Confirm', 'action:confirm:123')
    ->callback('Cancel', 'action:cancel:123');

TelegramMessage::create()
    ->to($chatId)
    ->content('Choose an option:')
    ->keyboard($keyboard);

// Extended button types example
$keyboard = InlineKeyboard::make()
    ->loginUrl('Login', 'https://example.com/auth')
    ->switchInlineQuery('Search Everywhere', 'query')
    ->row()
    ->switchInlineQueryCurrentChat('Search Here', 'query')
    ->switchInlineQueryChosenChat('Pick Chat', ['allow_user_chats' => true])
    ->row()
    ->copyText('Copy Code', 'ABC-123-XYZ')
    ->pay('Pay $10');

use SamuelTerra22\TelegramNotifications\Keyboards\Button;

$button = Button::url('Visit Site', 'https://example.com');
$button = Button::callback('Click Me', 'callback_data');
$button = Button::webApp('Open App', 'https://app.example.com');
$button = Button::loginUrl('Login', ['url' => 'https://example.com/auth']);
$button = Button::switchInlineQuery('Search', 'default query');
$button = Button::switchInlineQueryCurrentChat('Search Here', '');
$button = Button::switchInlineQueryChosenChat('Pick Chat', ['allow_user_chats' => true]);
$button = Button::copyText('Copy', 'text to copy');
$button = Button::pay('Buy Now');

$keyboard = InlineKeyboard::make()->button($button);

use SamuelTerra22\TelegramNotifications\Keyboards\ReplyKeyboard;

$keyboard = ReplyKeyboard::make()
    ->button('Option A')
    ->button('Option B')
    ->row()
    ->requestContact('Share Contact')
    ->requestLocation('Share Location')
    ->resize()                       // fit keyboard to buttons
    ->oneTime()                      // hide after one press
    ->placeholder('Choose...')       // input field placeholder
    ->selective()                    // show only to specific users
    ->persistent();                  // keep keyboard visible

use SamuelTerra22\TelegramNotifications\Keyboards\ForceReply;
use SamuelTerra22\TelegramNotifications\Keyboards\ReplyKeyboardRemove;

// Force the user to reply
$forceReply = ForceReply::make()
    ->placeholder('Type your answer...')
    ->selective();

// Remove the reply keyboard
$remove = ReplyKeyboardRemove::make()
    ->selective();

// Use with any message
TelegramMessage::create()
    ->to($chatId)
    ->content('Please answer:')
    ->replyKeyboard($forceReply);

$keyboard = InlineKeyboard::make();
$keyboard->isEmpty(); // true

$keyboard->url('Click', 'https://example.com');
$keyboard->isEmpty(); // false

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

$response = Telegram::message('-1001234567890')
    ->html('<b>Important Update</b>')
    ->silent()
    ->protected()
    ->disablePreview()
    ->keyboard($inlineKeyboard)
    ->replyTo($previousMessageId)
    ->topic('42')
    ->send();

$response->ok();         // true
$response->messageId();  // 123
$response->date();       // Carbon instance
$response->text();       // 'Important Update'
$response->chat();       // ['id' => -1001234567890, 'type' => 'supergroup', ...]

Telegram::message($chatId)
    ->text('Only sent if condition is true')
    ->sendWhen($user->wantsNotifications())
    ->send();

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

$responses = Telegram::broadcast(['-100001', '-100002', '-100003'])
    ->html('<b>Announcement</b>')
    ->silent()
    ->keyboard($keyboard)
    ->rateLimit(50) // 50ms delay between each send
    ->onFailure(function (string $chatId, Throwable $e) {
        Log::warning("Failed to send to {$chatId}: {$e->getMessage()}");
    })
    ->send();

// $responses is an array of TelegramResponse objects

$broadcast = Telegram::broadcast()
    ->to('-100001', '-100002')
    ->to('-100003')
    ->text('Hello everyone!')
    ->send();

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Edit message text
Telegram::editMessageText($chatId, $messageId, 'Updated text');

// Edit message caption
Telegram::editMessageCaption($chatId, $messageId, 'New caption');

// Edit reply markup (keyboard)
Telegram::editMessageReplyMarkup($chatId, $messageId, $inlineKeyboard->toArray());

// Edit message media
Telegram::editMessageMedia($chatId, $messageId, [
    'type' => 'photo',
    'media' => 'https://example.com/new-photo.jpg',
]);

// Delete a single message
Telegram::deleteMessage($chatId, $messageId);

// Delete multiple messages at once
Telegram::deleteMessages($chatId, [$msgId1, $msgId2, $msgId3]);

// Forward a message to another chat
Telegram::forwardMessage($toChatId, $fromChatId, $messageId);

// Copy a message (sends as new, without "Forwarded from" header)
Telegram::copyMessage($toChatId, $fromChatId, $messageId);

use SamuelTerra22\TelegramNotifications\Facades\Telegram;
use SamuelTerra22\TelegramNotifications\Enums\ChatAction;

// Shortcut methods
Telegram::typing($chatId);
Telegram::uploadingPhoto($chatId);
Telegram::uploadingDocument($chatId);
Telegram::recordingVideo($chatId);
Telegram::recordingVoice($chatId);

// Using the enum directly
Telegram::sendChatAction($chatId, ChatAction::Typing);
Telegram::sendChatAction($chatId, ChatAction::ChooseSticker);
Telegram::sendChatAction($chatId, ChatAction::FindLocation);
Telegram::sendChatAction($chatId, ChatAction::RecordVideoNote);
Telegram::sendChatAction($chatId, ChatAction::UploadVideoNote);

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Get chat info
$chat = Telegram::getChat($chatId);

// Get a specific member's info
$member = Telegram::getChatMember($chatId, $userId);

// Get total member count
$count = Telegram::getChatMemberCount($chatId);

// Pin a message
Telegram::pinChatMessage($chatId, $messageId);
Telegram::pinChatMessage($chatId, $messageId, disableNotification: true);

// Unpin a specific message or all messages
Telegram::unpinChatMessage($chatId, $messageId);
Telegram::unpinAllChatMessages($chatId);

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Get bot info
$me = Telegram::getMe();

// Set bot commands (shown in the menu)
Telegram::setMyCommands([
    ['command' => 'start', 'description' => 'Start the bot'],
    ['command' => 'help', 'description' => 'Show help'],
    ['command' => 'settings', 'description' => 'Bot settings'],
]);

// Get current commands
$commands = Telegram::getMyCommands();

// Delete all commands
Telegram::deleteMyCommands();

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Set webhook
Telegram::setWebhook('https://example.com/telegram/webhook');

// Set webhook with secret token
Telegram::setWebhook('https://example.com/webhook', secretToken: 'my-secret');

// Get current webhook info
$info = Telegram::getWebhookInfo();

// Delete webhook
Telegram::deleteWebhook();
Telegram::deleteWebhook(dropPendingUpdates: true);

// In your routes file
Route::post('/telegram/webhook', TelegramWebhookController::class)
    ->middleware('telegram.webhook');

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Get file info (returns file_path for downloading)
$file = Telegram::getFile($fileId);
// Download URL: https://api.telegram.org/file/bot<token>/<file_path>

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

Telegram::bot()->upload('sendDocument', [
    'chat_id' => $chatId,
    'caption' => 'Uploaded file',
], 'document', '/path/to/local/file.pdf');

Telegram::bot()->upload('sendPhoto', [
    'chat_id' => $chatId,
    'caption' => 'Local photo',
], 'photo', '/path/to/image.jpg');

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Answer a callback query (from inline keyboard button press)
Telegram::answerCallbackQuery($callbackQueryId, 'Done!');
Telegram::answerCallbackQuery($callbackQueryId, 'Are you sure?', showAlert: true);

// Answer an inline query
Telegram::answerInlineQuery($inlineQueryId, [
    [
        'type' => 'article',
        'id' => '1',
        'title' => 'Result',
        'input_message_content' => ['message_text' => 'Selected result'],
    ],
]);

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Ban a user
Telegram::banChatMember($chatId, $userId);

// Ban with expiry
Telegram::banChatMember($chatId, $userId, ['until_date' => now()->addDays(7)->timestamp]);

// Unban a user
Telegram::unbanChatMember($chatId, $userId);
Telegram::unbanChatMember($chatId, $userId, ['only_if_banned' => true]);

use SamuelTerra22\TelegramNotifications\Facades\Telegram;
use SamuelTerra22\TelegramNotifications\Keyboards\InlineKeyboard;

// Send with extra options
Telegram::sendMessage($chatId, 'Hello', options: [
    'reply_markup' => InlineKeyboard::make()->callback('OK', 'ok'),
    'disable_notification' => true,
    'protect_content' => true,
    'message_thread_id' => 42,
]);

// reply_markup auto-encodes: ReplyMarkupInterface instances and arrays → JSON
Telegram::sendPhoto($chatId, $photoUrl, 'Caption', options: [
    'reply_markup' => $keyboard,  // auto-encoded to JSON
    'has_spoiler' => true,
]);

// Any Telegram Bot API parameter works
Telegram::sendMessage($chatId, 'Reply to this', options: [
    'reply_parameters' => ['message_id' => 123],
    'link_preview_options' => ['is_disabled' => true],
]);

// call() throws TelegramApiException on error
$result = Telegram::bot()->call('getChatAdministrators', [
    'chat_id' => $chatId,
]);

// callSilent() never throws (returns bool), safe for non-critical paths
$success = Telegram::bot()->callSilent('leaveChat', [
    'chat_id' => $chatId,
]);

// All message builders support the effect() method (Bot API 7.4+)
TelegramMessage::create()
    ->to($chatId)
    ->content('Congratulations!')
    ->effect('5104841245755180586'); // confetti animation

TelegramPhoto::create()
    ->to($chatId)
    ->photo('https://example.com/photo.jpg')
    ->effect('5104841245755180586');

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Add emoji reaction
Telegram::setMessageReaction($chatId, $messageId, [
    ['type' => 'emoji', 'emoji' => 'thumbs up'],
]);

// Big animated reaction
Telegram::setMessageReaction($chatId, $messageId, [
    ['type' => 'emoji', 'emoji' => 'fire'],
], isBig: true);

// Custom emoji reaction
Telegram::setMessageReaction($chatId, $messageId, [
    ['type' => 'custom_emoji', 'custom_emoji_id' => '5368324170671202286'],
]);

use SamuelTerra22\TelegramNotifications\Helpers\MarkdownV2;
use SamuelTerra22\TelegramNotifications\Messages\TelegramMessage;

// Escape special characters manually
$safe = MarkdownV2::escape('Hello_World *bold* [link](url)');
// Result: 'Hello\_World \*bold\* \[link\]\(url\)'

// Use the fluent builder method (auto-sets MarkdownV2 parse mode)
TelegramMessage::create()
    ->to($chatId)
    ->escapedMarkdown('Price: $10.00 (50% off!)')
    ->send();

// Use a Blade template for message content
TelegramMessage::create()
    ->to($chatId)
    ->view('telegram.order-shipped', [
        'order' => $order,
        'tracking_url' => $trackingUrl,
    ]);

// With custom parse mode
TelegramMessage::create()
    ->to($chatId)
    ->view('telegram.alert', ['title' => 'Warning'], 'MarkdownV2');

use SamuelTerra22\TelegramNotifications\Messages\TelegramMediaGroup;

// Send an album of photos
TelegramMediaGroup::create()
    ->to($chatId)
    ->photo('https://example.com/1.jpg', 'First photo')
    ->photo('https://example.com/2.jpg', 'Second photo')
    ->video('https://example.com/video.mp4', 'A video')
    ->silent();

// Use in a notification
public function toTelegram(mixed $notifiable): TelegramMediaGroup
{
    return TelegramMediaGroup::create()
        ->photo($this->receipt->image_url, 'Receipt')
        ->document($this->receipt->pdf_url, 'PDF Receipt');
}

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Send an invoice (Telegram Stars)
Telegram::sendInvoice(
    chatId: $chatId,
    title: 'Premium Access',
    description: '30 days of premium features',
    payload: 'premium_30d_user_123',
    currency: 'XTR', // Telegram Stars
    prices: [['label' => 'Premium Access', 'amount' => 100]],
);

// Send invoice with third-party payment provider
Telegram::sendInvoice(
    chatId: $chatId,
    title: 'Product',
    description: 'Description',
    payload: 'product_123',
    currency: 'USD',
    prices: [['label' => 'Product', 'amount' => 1000]], // $10.00
    providerToken: 'your-provider-token',
);

// Create a shareable invoice link
$result = Telegram::createInvoiceLink(
    title: 'Donation',
    description: 'Support our project',
    payload: 'donation_user_123',
    currency: 'XTR',
    prices: [['label' => 'Donation', 'amount' => 50]],
);

// Answer pre-checkout query (in webhook handler)
Telegram::answerPreCheckoutQuery($preCheckoutQueryId, ok: true);
Telegram::answerPreCheckoutQuery($preCheckoutQueryId, ok: false, errorMessage: 'Item out of stock');

// Answer shipping query
Telegram::answerShippingQuery($shippingQueryId, ok: true, shippingOptions: [
    ['id' => 'standard', 'title' => 'Standard', 'prices' => [['label' => 'Shipping', 'amount' => 500]]],
]);

// Refund a Telegram Stars payment
Telegram::refundStarPayment($userId, $telegramPaymentChargeId);

// Get Telegram Stars transactions
$transactions = Telegram::getStarTransactions(offset: 0, limit: 100);

Telegram::sendPaidMedia($chatId, starCount: 10, media: [
    ['type' => 'photo', 'media' => 'https://example.com/exclusive.jpg'],
], caption: 'Exclusive content');

// Send a gift to a user
Telegram::sendGift($userId, $giftId, text: 'Happy birthday!');

// Get available gifts
$gifts = Telegram::getAvailableGifts();

// Post a story
Telegram::postStory($chatId, content: ['type' => 'photo', 'photo' => 'photo_file_id'], caption: 'Check this out!');

// Edit a story
Telegram::editStory($chatId, $storyId, content: ['type' => 'photo', 'photo' => 'new_photo_id']);

// Delete stories
Telegram::deleteStory($chatId, $storyId);
Telegram::deleteStories($chatId, [$storyId1, $storyId2]);

use SamuelTerra22\TelegramNotifications\Messages\TelegramChecklist;

// Create a checklist
TelegramChecklist::create()
    ->to($chatId)
    ->title('Sprint Tasks')
    ->checkedItem('Design review')
    ->checkedItem('Write tests')
    ->uncheckedItem('Implementation')
    ->uncheckedItem('Code review')
    ->item('Deploy', checked: false);

// Via facade
Telegram::sendChecklist($chatId, 'Todo', [
    ['text' => 'Buy groceries', 'checked' => false],
    ['text' => 'Clean house', 'checked' => true],
]);

// Use in a notification
public function toTelegram(mixed $notifiable): TelegramChecklist
{
    return TelegramChecklist::create()
        ->title('Deployment Checklist')
        ->checkedItem('Tests passing')
        ->uncheckedItem('Deploy to production');
}

Telegram::approveSuggestedPost($chatId, $messageId);
Telegram::declineSuggestedPost($chatId, $messageId);

Telegram::setMyProfilePhoto($photoFileId);
Telegram::setMyProfilePhoto($photoFileId, isPersonal: true);
Telegram::removeMyProfilePhoto();

// Send partial/draft messages (Bot API 9.3, useful for AI/LLM streaming)
Telegram::sendMessageDraft($chatId, 'Partial response so far...');
Telegram::sendMessageDraft($chatId, 'Complete response.', businessConnectionId: 'conn_123');

'channels' => [
    // ...
    'telegram' => [
        'driver' => 'custom',
        'via' => \SamuelTerra22\TelegramNotifications\Logging\CreateTelegramLogger::class,
        'level' => env('LOG_TELEGRAM_LEVEL', 'error'),
    ],
],

// Send errors to Telegram
Log::channel('telegram')->error('Something went wrong');

// With context
Log::channel('telegram')->critical('Payment failed', [
    'order_id' => 123,
    'amount' => 99.99,
]);

// With exception
Log::channel('telegram')->error($exception->getMessage(), [
    'exception' => $exception,
]);

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->reportable(function (\Throwable $e) {
        try {
            if (config('telegram-notifications.logging.enabled')) {
                Log::channel('telegram')->error($e->getMessage(), [
                    'exception' => $e,
                ]);
            }
        } catch (\Throwable) {
            // Never break the application
        }
    });
})

use Illuminate\Http\JsonResponse;
use SamuelTerra22\TelegramNotifications\Http\WebhookHandler;
use SamuelTerra22\TelegramNotifications\Facades\Telegram;

class MyBotHandler extends WebhookHandler
{
    protected function onStartCommand(array $message, string $args): JsonResponse
    {
        Telegram::sendMessage($message['chat']['id'], 'Welcome! Use /help for commands.');
        return $this->ok();
    }

    protected function onHelpCommand(array $message, string $args): JsonResponse
    {
        Telegram::sendMessage($message['chat']['id'], 'Available commands: /start, /help');
        return $this->ok();
    }

    protected function onMessage(array $message): JsonResponse
    {
        // Handle non-command messages
        Telegram::sendMessage($message['chat']['id'], "You said: {$message['text']}");
        return $this->ok();
    }

    protected function onCallbackQuery(array $callbackQuery): JsonResponse
    {
        Telegram::answerCallbackQuery($callbackQuery['id'], 'Button pressed!');
        return $this->ok();
    }
}

Route::post('/telegram/webhook', function (Request $request) {
    return app(MyBotHandler::class)->handle($request);
})->middleware('telegram.webhook');

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Dispatch broadcast as a queued job
Telegram::broadcast($chatIds)
    ->html('<b>Scheduled announcement</b>')
    ->rateLimit(50)
    ->queue();

// Dispatch to a specific queue
Telegram::broadcast($chatIds)
    ->text('Newsletter')
    ->queue('telegram');

// Dispatch to a specific connection
Telegram::broadcast($chatIds)
    ->text('Important update')
    ->queue(connection: 'redis');

use SamuelTerra22\TelegramNotifications\Exceptions\TelegramApiException;

try {
    Telegram::sendMessage($chatId, 'Hello');
} catch (TelegramApiException $e) {
    $e->getMessage();              // Human-readable error
    $e->getStatusCode();           // HTTP status code (e.g. 400, 403, 429)
    $e->getApiMethod();            // API method called (e.g. 'sendMessage')
    $e->getTelegramDescription();  // Original Telegram error description
    $e->getRetryAfter();           // Seconds to wait (only on 429), null otherwise
    $e->isRateLimited();           // true if HTTP 429
}

'retry' => [
    'max_attempts' => (int) env('TELEGRAM_RETRY_MAX_ATTEMPTS', 3),
    'base_delay_ms' => (int) env('TELEGRAM_RETRY_BASE_DELAY_MS', 1000),
    'use_jitter' => (bool) env('TELEGRAM_RETRY_USE_JITTER', true),
],

// Returns true on success, false on any error (never throws)
$success = Telegram::bot()->callSilent('sendMessage', [
    'chat_id' => $chatId,
    'text' => 'Optional notification',
]);

// config/telegram-notifications.php
'default' => 'default',

'bots' => [
    'default' => [
        'token' => env('TELEGRAM_BOT_TOKEN'),
        'username' => env('TELEGRAM_BOT_USERNAME'),
        'chat_id' => env('TELEGRAM_CHAT_ID'),
    ],
    'alerts' => [
        'token' => env('TELEGRAM_ALERTS_BOT_TOKEN'),
        'username' => env('TELEGRAM_ALERTS_BOT_USERNAME'),
        'chat_id' => env('TELEGRAM_ALERTS_CHAT_ID'),
    ],
    'support' => [
        'token' => env('TELEGRAM_SUPPORT_BOT_TOKEN'),
        'username' => env('TELEGRAM_SUPPORT_BOT_USERNAME'),
        'chat_id' => env('TELEGRAM_SUPPORT_CHAT_ID'),
        'topic_id' => env('TELEGRAM_SUPPORT_TOPIC_ID'),
    ],
],

use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Use the default bot
Telegram::sendMessage($chatId, 'From default bot');

// Switch to another bot
Telegram::bot('alerts')->call('sendMessage', [
    'chat_id' => $chatId,
    'text' => 'From alerts bot',
]);

// In message builders
TelegramMessage::create()
    ->bot('alerts')
    ->to($chatId)
    ->content('Sent via alerts bot');

// In fluent builder - uses the default bot
Telegram::message($chatId)->text('Hello')->send();

// Access bot config
Telegram::getDefaultBot();   // 'default'
Telegram::getBotsConfig();   // full bots config array

// Get bot username
Telegram::getUsername();           // 'your_bot'
Telegram::getUsername('alerts');   // 'alerts_bot'

// Generate integration links
Telegram::getIntegrationLink();
// => 'https://t.me/your_bot'

Telegram::getIntegrationLink('abc123');
// => 'https://t.me/your_bot?start=abc123'

Telegram::getIntegrationLink('start_param', 'alerts');
// => 'https://t.me/alerts_bot?start=start_param'

use SamuelTerra22\TelegramNotifications\Enums\ParseMode;

ParseMode::HTML;        // 'HTML'
ParseMode::MarkdownV2;  // 'MarkdownV2'
ParseMode::Markdown;    // 'Markdown' (legacy)

use SamuelTerra22\TelegramNotifications\Enums\ChatAction;

ChatAction::Typing;           // 'typing'
ChatAction::UploadPhoto;      // 'upload_photo'
ChatAction::RecordVideo;      // 'record_video'
ChatAction::UploadVideo;      // 'upload_video'
ChatAction::RecordVoice;      // 'record_voice'
ChatAction::UploadVoice;      // 'upload_voice'
ChatAction::UploadDocument;   // 'upload_document'
ChatAction::ChooseSticker;    // 'choose_sticker'
ChatAction::FindLocation;     // 'find_location'
ChatAction::RecordVideoNote;  // 'record_video_note'
ChatAction::UploadVideoNote;  // 'upload_video_note'

$response = Telegram::message($chatId)->text('Hello')->send();

use Illuminate\Support\Facades\Http;
use SamuelTerra22\TelegramNotifications\Facades\Telegram;

// Fake all Telegram API calls
Http::fake([
    'api.telegram.org/*' => Http::response([
        'ok' => true,
        'result' => ['message_id' => 1],
    ]),
]);

// Test sending a message
Telegram::sendMessage('-1001234567890', 'Hello');

// Assert it was sent
Http::assertSent(function ($request) {
    return str_contains($request->url(), '/sendMessage')
        && $request['text'] === 'Hello';
});

Http::fake([
    'api.telegram.org/*' => Http::response(['ok' => true, 'result' => ['message_id' => 1]]),
]);

$user->notify(new OrderShipped($order));

Http::assertSent(function ($request) {
    return str_contains($request->url(), '/sendMessage')
        && str_contains($request['text'], 'Order Shipped');
});

Http::fake(function ($request) {
    static $count = 0;
    $count++;
    return Http::response([
        'ok' => true,
        'result' => ['message_id' => $count],
    ]);
});

Http::fake();

// ... code that conditionally sends ...

Http::assertNothingSent();
bash
php artisan vendor:publish --tag=telegram-notifications-config
env
TELEGRAM_LOG_ENABLED=true
TELEGRAM_LOG_CHAT_ID=-1001234567890
TELEGRAM_LOG_TOPIC_ID=99
LOG_TELEGRAM_LEVEL=error
bash
php artisan telegram:get-me
php artisan telegram:get-me --bot=alerts