Download the PHP package samuelterra22/laravel-telegram-notifications without Composer

On this page you can find all versions of the php package samuelterra22/laravel-telegram-notifications. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-telegram-notifications

Laravel Telegram Notifications

Tests PHPStan Latest Version on Packagist Total Downloads License

A complete Laravel package for integrating the Telegram Bot API with Laravel applications. Send messages, notifications, log errors, use interactive keyboards, support multiple bots and forum topics.

Table of Contents

Features

Requirements

Installation

Publish the config file:

Configuration

Add to your .env:

All available environment variables:

Variable Description Default
TELEGRAM_BOT_TOKEN Bot token from @BotFather (required)
TELEGRAM_BOT_USERNAME Bot username (without @) for integration links null
TELEGRAM_CHAT_ID Default chat ID for the bot null
TELEGRAM_TOPIC_ID Default forum topic ID null
TELEGRAM_BOT Name of the default bot default
TELEGRAM_API_BASE_URL Telegram API base URL (useful for local Bot API server) https://api.telegram.org
TELEGRAM_TIMEOUT HTTP timeout in seconds 10
TELEGRAM_LOG_ENABLED Enable Telegram log handler false
TELEGRAM_LOG_BOT Bot to use for logging default
TELEGRAM_LOG_CHAT_ID Chat ID for log messages null
TELEGRAM_LOG_TOPIC_ID Topic ID for log messages null
TELEGRAM_WEBHOOK_SECRET Secret token for webhook verification null
TELEGRAM_RETRY_MAX_ATTEMPTS Max retry attempts on rate limit 3
TELEGRAM_RETRY_BASE_DELAY_MS Base delay in milliseconds 1000
TELEGRAM_RETRY_USE_JITTER Add random jitter to delays true

The config file config/telegram-notifications.php supports multiple bots:

Quick Start

Usage

Sending Messages via Facade

Laravel Notifications Channel

Create a notification class with a toTelegram() method:

Send notifications:

Add the routing method to your notifiable model:

You can return any message type from toTelegram() (not just TelegramMessage):

Message Types

All message builders share these methods via the HasSharedParams trait:

Method Description
to(string $chatId) Set the target chat ID
topic(string $topicId) Set the forum topic/thread ID
bot(string $bot) Set which bot to use

All builders also support silent() and protected() to disable notifications and protect content from forwarding/saving.

Text Message

Photo

Document

Video

Audio

Voice

Animation (GIF)

Sticker

Location

You can also set coordinates individually:

Venue

Contact

Poll

Dice

Facade-Only Types

These types don't have dedicated builder classes but are available via the Facade:

Text Formatting Methods

TelegramMessage provides fluent methods for HTML formatting:

Method Output Example
content(string $text) Raw text Hello world
line(string $text) Appends text + newline Line 1\nLine 2
bold(string $text) <b>text</b> text
italic(string $text) <i>text</i> text
underline(string $text) <u>text</u> text
strikethrough(string $text) <s>text</s> text
code(string $text) <code>text</code> text
pre(string $text, ?string $lang) <pre><code class="lang">text</code></pre> Code block
link(string $text, string $url) <a href="url">text</a> text
spoiler(string $text) <tg-spoiler>text</tg-spoiler> Hidden text
quote(string $text) <blockquote>text</blockquote> Blockquote
expandableQuote(string $text) <blockquote expandable>text</blockquote> Collapsible quote

Change parse mode:

Messages exceeding 4096 characters are automatically split into multiple messages using splitContent().

Interactive Keyboards

Inline Keyboard

Inline keyboards appear below the message:

All inline button types:

Method Description Parameters
url(text, url, columns) Opens a URL string $text, string $url, int $columns = 2
callback(text, data, columns) Sends callback query string $text, string $data, int $columns = 2
webApp(text, url, columns) Opens a Web App string $text, string $webAppUrl, int $columns = 2
loginUrl(text, loginUrl, columns) Authentication button string $text, array\|string $loginUrl, int $columns = 2
switchInlineQuery(text, query, columns) Switch to inline in any chat string $text, string $query = '', int $columns = 2
switchInlineQueryCurrentChat(text, query, columns) Switch to inline in current chat string $text, string $query = '', int $columns = 2
switchInlineQueryChosenChat(text, options, columns) Switch inline with chat picker string $text, array $options = [], int $columns = 2
copyText(text, textToCopy, columns) Copies text to clipboard string $text, string $textToCopy, int $columns = 2
pay(text, columns) Payment button string $text, int $columns = 2
button(button, columns) Add a custom Button instance Button $button, int $columns = 2
row() Start a new button row

The $columns parameter controls auto-layout: buttons are placed in rows of N columns. Use row() to force a new row.

Custom Button Objects

For full control, use the Button class:

Reply Keyboard

Reply keyboards replace the device keyboard:

Method Description
button(text, columns) Simple text button
requestContact(text, columns) Request user's phone number
requestLocation(text, columns) Request user's location
row() Start a new button row
resize(bool) Resize keyboard to fit buttons
oneTime(bool) Hide keyboard after one button press
placeholder(string) Input field placeholder text
selective(bool) Show only to mentioned/replied-to users
persistent(bool) Keep keyboard always visible

Force Reply & Remove Keyboard

Checking Keyboard State

Fluent Message Builder

Build and send messages with a chainable interface that returns typed TelegramResponse objects:

Available methods on PendingMessage:

Method Description
text(string $text) Set message text (default parse mode)
html(string $text) Set text with HTML parse mode
markdown(string $text) Set text with MarkdownV2 parse mode
silent() Disable notification sound
protected() Protect content from forwarding/saving
disablePreview() Disable web page link previews
keyboard(ReplyMarkupInterface $markup) Attach any keyboard/reply markup
replyTo(int\|string $messageId) Reply to a specific message
topic(string $topicId) Send to a forum topic
sendWhen(bool $condition) Only send if condition is true
send() Execute and return TelegramResponse

Conditional Sending

Broadcasting

Send the same message to multiple chats with rate limiting and error handling:

You can also add recipients dynamically:

Available methods on PendingBroadcast:

Method Description
to(string ...$chatIds) Add chat IDs to the broadcast list
text(string $text) Set message text
html(string $text) Set text with HTML parse mode
markdown(string $text) Set text with MarkdownV2 parse mode
silent() Disable notification sound
protected() Protect content
keyboard(ReplyMarkupInterface $markup) Attach keyboard
rateLimit(int $milliseconds) Delay between sends (default: 0)
onFailure(callable $callback) Handle per-chat failures: fn(string $chatId, Throwable $e)
send() Execute broadcast, returns array of TelegramResponse

Edit, Delete, Forward & Copy Messages

Chat Actions

Show what the bot is "doing" to the user:

Chat Management

Bot Management & Commands

Webhook Management & Middleware

Setting Up Webhooks

Verifying Incoming Webhooks

Protect your webhook endpoint with the built-in middleware:

The telegram.webhook middleware checks the X-Telegram-Bot-Api-Secret-Token header against your configured secret. If no secret is configured, all requests pass through.

File Operations

Uploading Local Files

Use the low-level TelegramBotApi::upload() method for sending local files:

Callbacks & Inline Queries

Moderation

Advanced Options

All Facade methods accept an optional $options array as the last parameter. This lets you pass any Telegram Bot API parameter without falling back to raw call():

Raw API Calls

For any Telegram Bot API method not wrapped by the package:

Message Effects

All message builders support the effect() method for animated visual effects (Bot API 7.4+):

Reactions

MarkdownV2 Escaping

Blade View Rendering

Use Blade templates for message content:

Example Blade template (resources/views/telegram/order-shipped.blade.php):

Media Group Builder

Payments & Invoices

Paid Media

Gifts

Stories

Checklists

Suggested Posts

Profile Management

Streaming Message Drafts

Logging (Monolog Handler)

Send application logs directly to Telegram. The handler uses callSilent() internally, so it never crashes your application even if the Telegram API is unreachable.

Setup

Add the Telegram channel to config/logging.php:

Configure in .env:

Usage

Exception Handler Integration

Report all exceptions to Telegram in bootstrap/app.php:

Log Message Format

Log messages are formatted with:

If HTML formatting fails, the handler automatically falls back to plain text.

Artisan Commands

telegram:get-me

Display bot information:

Output shows: ID, Name, Username, Is Bot, Can Join Groups, Can Read Messages, Supports Inline.

telegram:set-webhook

Manage webhook configuration:

telegram:send

Send a message from the command line:

Webhook Handler

The package provides an abstract WebhookHandler base class for processing incoming Telegram updates. Create a concrete handler by extending it:

Register it in your routes:

The handler automatically routes updates:

Queued Broadcasting

Dispatch broadcasts as Laravel queue jobs for background processing:

The SendTelegramBroadcast job handles individual failures gracefully -- if sending to one chat fails, it continues to the rest.

Error Handling

API errors throw TelegramApiException with rich context:

Rate Limiting

The package handles HTTP 429 (Too Many Requests) with configurable exponential backoff:

  1. When a 429 response is received, the client retries with exponential backoff
  2. If the response includes retry_after, that value is used as the delay
  3. Otherwise, delay doubles each attempt: base_delay * 2^(attempt-1)
  4. Optional jitter adds randomness to prevent thundering herd
  5. After max_attempts retries, TelegramApiException is thrown

Configure via config/telegram-notifications.php or environment variables:

Silent Calls

For non-critical paths where you don't want exceptions:

The logging handler (TelegramHandler) always uses callSilent() to ensure log delivery failures never crash your application.

Multi-Bot Support

Configuration

Switching Bots

Bot Usernames & Integration Links

Each bot can have its own username for generating t.me integration links:

Bots are lazy-loaded: the TelegramBotApi instance for each bot is only created when first accessed via bot().

Enums Reference

ParseMode

ChatAction

Typed Responses

The fluent builder returns TelegramResponse objects with typed accessors:

Method Return Type Description
ok() bool Whether the API request succeeded
messageId() ?int The sent message ID
date() ?Carbon Message timestamp as Carbon instance
chat() ?array Chat data (id, type, title, etc.)
text() ?string Message text content
result() array Full API result object
toArray() array Raw response data

Testing

The package uses Laravel's Http::fake() for all API calls, making it trivial to test:

Testing Notifications

Testing with Sequences

Asserting No Calls Were Made

API Quick Reference

Telegram Facade Methods

Messaging

Method Parameters Returns
sendMessage string $chatId, string $text, ?string $parseMode = 'HTML', ?string $topicId = null, array $options = [] array
sendPhoto string $chatId, string $photo, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendDocument string $chatId, string $document, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendVideo string $chatId, string $video, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendAudio string $chatId, string $audio, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendVoice string $chatId, string $voice, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendAnimation string $chatId, string $animation, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendSticker string $chatId, string $sticker, array $options = [] array
sendVideoNote string $chatId, string $videoNote, array $options = [] array
sendMediaGroup string $chatId, array $media, array $options = [] array
sendLocation string $chatId, float $latitude, float $longitude, array $options = [] array
sendVenue string $chatId, float $lat, float $lng, string $title, string $address, array $options = [] array
sendContact string $chatId, string $phone, string $firstName, ?string $lastName = null, array $options = [] array
sendPoll string $chatId, string $question, array $options, array $extra = [] array
sendDice string $chatId, ?string $emoji = null, array $options = [] array

Message Operations

Method Parameters Returns
editMessageText string $chatId, int\|string $messageId, string $text, ?string $parseMode = 'HTML', array $options = [] array
editMessageCaption string $chatId, int\|string $messageId, string $caption, ?string $parseMode = 'HTML', array $options = [] array
editMessageReplyMarkup string $chatId, int\|string $messageId, array $replyMarkup, array $options = [] array
editMessageMedia string $chatId, int\|string $messageId, array $media, array $options = [] array
deleteMessage string $chatId, int\|string $messageId, array $options = [] array
deleteMessages string $chatId, array $messageIds, array $options = [] array
forwardMessage string $chatId, string $fromChatId, int\|string $messageId, array $options = [] array
copyMessage string $chatId, string $fromChatId, int\|string $messageId, array $options = [] array

Chat Actions & Management

Method Parameters Returns
sendChatAction string $chatId, ChatAction $action, array $options = [] array
typing string $chatId array
uploadingPhoto string $chatId array
uploadingDocument string $chatId array
recordingVideo string $chatId array
recordingVoice string $chatId array
getChat string $chatId, array $options = [] array
getChatMember string $chatId, int\|string $userId, array $options = [] array
getChatMemberCount string $chatId, array $options = [] array
pinChatMessage string $chatId, int\|string $messageId, bool $disableNotification = false, array $options = [] array
unpinChatMessage string $chatId, ?int $messageId = null, array $options = [] array
unpinAllChatMessages string $chatId, array $options = [] array

Bot & Webhook

Method Parameters Returns
getMe array
setMyCommands array $commands, array $options = [] array
getMyCommands array $options = [] array
deleteMyCommands array $options = [] array
getFile string $fileId, array $options = [] array
setWebhook string $url, ?string $secretToken = null, array $options = [] array
deleteWebhook bool $dropPendingUpdates = false, array $options = [] array
getWebhookInfo array

Callbacks, Queries & Moderation

Method Parameters Returns
answerCallbackQuery string $id, ?string $text = null, bool $showAlert = false, array $options = [] array
answerInlineQuery string $id, array $results, array $options = [] array
setMessageReaction string $chatId, int\|string $messageId, array $reaction, bool $isBig = false, array $options = [] array
banChatMember string $chatId, int\|string $userId, array $options = [] array
unbanChatMember string $chatId, int\|string $userId, array $options = [] array

Payments & Commerce

Method Parameters Returns
sendInvoice string $chatId, string $title, string $description, string $payload, string $currency, array $prices, ?string $providerToken = null, array $options = [] array
createInvoiceLink string $title, string $description, string $payload, string $currency, array $prices, ?string $providerToken = null, array $options = [] array
answerPreCheckoutQuery string $preCheckoutQueryId, bool $ok, ?string $errorMessage = null, array $options = [] array
answerShippingQuery string $shippingQueryId, bool $ok, ?array $shippingOptions = null, ?string $errorMessage = null, array $options = [] array
refundStarPayment int\|string $userId, string $telegramPaymentChargeId, array $options = [] array
getStarTransactions ?int $offset = null, ?int $limit = null, array $options = [] array
sendPaidMedia string $chatId, int $starCount, array $media, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
sendGift int\|string $userId, string $giftId, ?string $text = null, ?string $textParseMode = null, array $options = [] array
getAvailableGifts array $options = [] array

Stories

Method Parameters Returns
postStory string $chatId, array $content, ?int $activePeriod = null, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
editStory string $chatId, int\|string $storyId, array $content, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] array
deleteStory string $chatId, int\|string $storyId, array $options = [] array
deleteStories string $chatId, array $storyIds, array $options = [] array

Checklists & Other

Method Parameters Returns
sendChecklist string $chatId, string $title, array $checklist, array $options = [] array
sendMessageDraft string $chatId, string $text, ?string $parseMode = 'HTML', ?string $businessConnectionId = null, array $options = [] array
approveSuggestedPost string $chatId, int\|string $messageId, array $options = [] array
declineSuggestedPost string $chatId, int\|string $messageId, array $options = [] array
setMyProfilePhoto string $photo, bool $isPersonal = false, array $options = [] array
removeMyProfilePhoto bool $isPersonal = false, array $options = [] array

Fluent Builders

Method Parameters Returns
message string $chatId PendingMessage
broadcast array $chatIds = [] PendingBroadcast
bot ?string $name = null TelegramBotApi

TelegramBotApi Methods

Method Description
call(string $method, array $params = []) Make API call, throws TelegramApiException on error
callSilent(string $method, array $params = []) Make API call, returns bool (never throws)
upload(string $method, array $params, string $fileField, string $filePath) Upload local file via multipart
getToken() Get the bot token
getBaseUrl() Get the API base URL
getTimeout() Get the HTTP timeout

Roadmap

All features from the original roadmap have been implemented. Future ideas:

Development

Docker-based development (PHP 8.4 CLI Alpine):

Without Docker:

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Contributions are welcome! Please ensure tests pass and code follows the project style (Laravel Pint).

This project uses conventional commits for automatic versioning:

License

The MIT License (MIT). Please see License File for more information.


All versions of laravel-telegram-notifications with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
illuminate/contracts Version ^11.0||^12.0
illuminate/http Version ^11.0||^12.0
illuminate/notifications Version ^11.0||^12.0
illuminate/support Version ^11.0||^12.0
monolog/monolog Version ^3.0
spatie/laravel-package-tools Version ^1.16
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package samuelterra22/laravel-telegram-notifications contains the following files

Loading the files please wait ...