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\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
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\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);
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
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;
// 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],
]);
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 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
}