PHPackages                             andisiahaan/gramsea-telegram-bot - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. andisiahaan/gramsea-telegram-bot

ActiveLibrary[API Development](/categories/api)

andisiahaan/gramsea-telegram-bot
================================

A simple and powerful PHP library for Telegram Bot API

3.2.5(2mo ago)16MITPHPPHP &gt;=8.0

Since Mar 29Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/andisiahaan/gramsea-telegram-bot)[ Packagist](https://packagist.org/packages/andisiahaan/gramsea-telegram-bot)[ RSS](/packages/andisiahaan-gramsea-telegram-bot/feed)WikiDiscussions main Synced yesterday

READMEChangelog (10)Dependencies (2)Versions (14)Used By (0)

Gramsea Telegram Bot PHP Library
================================

[](#gramsea-telegram-bot-php-library)

[![PHP Version](https://camo.githubusercontent.com/f575af1b648be492e22e809caebece8d6ae4d5319ad769664ee7a52e1c31c939/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e302d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e)](LICENSE)

Library PHP sederhana dan powerful untuk berinteraksi dengan Telegram Bot API tanpa dependensi framework.

✨ Fitur
-------

[](#-fitur)

- 🚀 **Zero Framework Dependencies** - PHP murni, bisa digunakan di mana saja
- 🎯 **Magic Method** - Panggil method API Telegram langsung
- 📦 **Fluent Sender Classes** - Method chaining untuk mengirim pesan
- 📨 **Update Wrapper** - Object-oriented access ke webhook data
- 🖼️ **Media Helper** - Deteksi otomatis tipe file
- ⌨️ **Keyboard Builder** - Fluent builder untuk inline &amp; reply keyboard
- 🔘 **Callback Data** - Encode/decode callback data dengan kompresi
- 🔗 **Deep Link** - Generate &amp; parse deep links dan referral codes
- ✍️ **Text Formatter** - Fluent builder untuk formatting HTML
- 📏 **Limits Helper** - Constants dan validasi untuk Telegram limits
- 😀 **Emoji Constants** - Collection emoji yang sering dipakai
- 🔧 **Moderation Tools** - Ban, mute, restrict, pin messages
- ⚠️ **Exception Handling** - Custom exception untuk error handling

📦 Instalasi
-----------

[](#-instalasi)

```
composer require andisiahaan/gramsea-telegram-bot
```

🚀 Quick Start
-------------

[](#-quick-start)

### Penggunaan Dasar

[](#penggunaan-dasar)

```
use AndiSiahaan\GramseaTelegramBot\Gramsea;

$bot = new Gramsea('YOUR_BOT_TOKEN');

// Kirim pesan
$bot->sendMessage([
    'chat_id' => 123456789,
    'text' => 'Halo dari Gramsea!'
]);

// Kirim photo
$bot->sendPhoto([
    'chat_id' => 123456789,
    'photo' => 'https://example.com/image.jpg',
    'caption' => 'Photo caption'
]);
```

### Menggunakan Fluent Sender (Recommended)

[](#menggunakan-fluent-sender-recommended)

```
use AndiSiahaan\GramseaTelegramBot\Gramsea;
use AndiSiahaan\GramseaTelegramBot\Support\InlineKeyboard;

$bot = new Gramsea('YOUR_BOT_TOKEN');

// Text message dengan keyboard
$bot->message()
    ->to($chatId)
    ->text('Hello **world**!')  // Markdown otomatis dikonversi ke HTML
    ->keyboard(InlineKeyboard::make()->callback('Click Me', 'action'))
    ->send();

// Photo dengan caption
$bot->media()
    ->to($chatId)
    ->photo('https://example.com/image.jpg')
    ->caption('Check this out!')
    ->silent()
    ->send();

// Media group (album)
$bot->mediaGroup()
    ->to($chatId)
    ->photo('photo1.jpg')
    ->photo('photo2.jpg')
    ->video('video.mp4')
    ->caption('My album!')
    ->send();

// Text dengan link preview options
$bot->text()
    ->to($chatId)
    ->text('Check this article!')
    ->previewUrl('https://example.com/article')
    ->largePreview()
    ->send();
```

---

📖 Dokumentasi
-------------

[](#-dokumentasi)

### Class `Gramsea`

[](#class-gramsea)

Class utama dengan magic method untuk semua Telegram Bot API.

```
$bot = new Gramsea('YOUR_BOT_TOKEN');

// Magic method - panggil API langsung
$bot->sendMessage([...]);
$bot->sendPhoto([...]);
$bot->sendDocument([...]);
// dll...
```

#### Sender Factory Methods

[](#sender-factory-methods)

```
// MessageSender - auto-delegates based on content
$bot->message()->to($chatId)->text('Hello!')->send();

// TextSender - text dengan link preview options
$bot->text()->to($chatId)->text('Hello!')->noPreview()->send();

// MediaSender - single media
$bot->media()->to($chatId)->photo('url')->caption('Nice!')->send();

// MediaGroupSender - album (2-10 items)
$bot->mediaGroup()->to($chatId)->photo('a.jpg')->photo('b.jpg')->send();
```

#### Webhook Management

[](#webhook-management)

```
$bot->setWebhook('https://yourdomain.com/webhook');
$bot->deleteWebhook();
$bot->getWebhookInfo();
```

#### Chat Member Checks

[](#chat-member-checks)

```
$bot->isChatMember($chatId, $userId);   // bool
$bot->isChatAdmin($chatId, $userId);    // bool
$bot->isChatCreator($chatId, $userId);  // bool
$bot->getChatMemberStatus($chatId, $userId); // string|null
```

#### Chat Actions

[](#chat-actions)

```
$bot->sendTyping($chatId);
$bot->sendUploadPhotoAction($chatId);
$bot->sendUploadDocumentAction($chatId);
$bot->sendUploadVideoAction($chatId);
$bot->sendRecordVideoAction($chatId);
$bot->sendRecordVoiceAction($chatId);
$bot->sendChatAction($chatId, 'typing');
```

#### Moderation

[](#moderation)

```
// Ban & Unban
$bot->banChatMember($chatId, $userId, $untilDate, $revokeMessages);
$bot->unbanChatMember($chatId, $userId);

// Mute & Unmute
$bot->muteUser($chatId, $userId, $untilDate);
$bot->unmuteUser($chatId, $userId);

// Restrict & Promote
$bot->restrictChatMember($chatId, $userId, $permissions, $untilDate);
$bot->promoteChatMember($chatId, $userId, $rights);

// Messages
$bot->deleteMessage($chatId, $messageId);
$bot->deleteMessages($chatId, $messageIds);
$bot->pinChatMessage($chatId, $messageId);
$bot->unpinChatMessage($chatId, $messageId);
$bot->unpinAllChatMessages($chatId);
```

#### Keyboard Builders

[](#keyboard-builders)

```
$inline = $bot->inlineKeyboard([
    [
        ['text' => 'Button 1', 'callback_data' => 'btn1'],
        ['text' => 'Button 2', 'url' => 'https://example.com']
    ]
]);

$reply = $bot->replyKeyboard([
    [['text' => 'Option A'], ['text' => 'Option B']]
]);

$bot->removeKeyboard();
$bot->forceReply();
```

#### Bot Commands

[](#bot-commands)

```
$bot->setCommands([
    'start' => 'Mulai bot',
    'help' => 'Bantuan'
]);
$bot->getCommands();
$bot->deleteCommands();
```

#### File Operations

[](#file-operations)

```
$url = $bot->getFileUrl($fileId);
$content = $bot->downloadFile($fileId);
```

---

📨 Sender Classes
----------------

[](#-sender-classes)

Library menyediakan 5 sender class dengan fluent chaining API:

ClassKegunaan`MessageSender`General sender, auto-delegates ke sender yang tepat`TextSender`Khusus text message dengan link preview options`MediaSender`Khusus single media (photo, video, audio, document)`MediaGroupSender`Khusus media group/album (2-10 items)`MassMessageSender`Concurrent mass sending ke banyak target sekaligus### MessageSender (Recommended)

[](#messagesender-recommended)

Auto-detects dan delegates ke sender yang tepat:

- Text only → `TextSender`
- 1 media → `MediaSender`
- 2+ media → `MediaGroupSender`

```
use AndiSiahaan\GramseaTelegramBot\MessageSender;

// Text only
MessageSender::bot($bot)
    ->to($chatId)
    ->text('Hello **world**!')
    ->keyboard($keyboard)
    ->send();

// Single media
MessageSender::bot($bot)
    ->to($chatId)
    ->photo('https://example.com/image.jpg')
    ->text('Caption here')
    ->send();

// Media group
MessageSender::bot($bot)
    ->to($chatId)
    ->photo('photo1.jpg')
    ->photo('photo2.jpg')
    ->text('Album!')
    ->send();
```

### TextSender

[](#textsender)

Untuk text message dengan kontrol penuh atas link preview.

```
use AndiSiahaan\GramseaTelegramBot\TextSender;

TextSender::bot($bot)
    ->to($chatId)
    ->text('Check this: https://example.com')
    ->noPreview()           // Disable link preview
    ->send();

// Advanced link preview options
TextSender::bot($bot)
    ->to($chatId)
    ->text('Amazing article!')
    ->previewUrl('https://example.com/article')
    ->largePreview()        // Prefer large media
    ->previewAboveText()    // Show preview above text
    ->send();
```

**Link Preview Methods:**

- `noPreview()` - Disable link preview
- `previewUrl($url)` - Set custom URL for preview
- `smallPreview()` - Prefer small media
- `largePreview()` - Prefer large media
- `previewAboveText()` - Show preview above message text

### MediaSender

[](#mediasender)

Untuk single media dengan caption.

```
use AndiSiahaan\GramseaTelegramBot\MediaSender;

MediaSender::bot($bot)
    ->to($chatId)
    ->photo('https://example.com/image.jpg')
    ->caption('Check this out!')
    ->keyboard($keyboard)
    ->send();

// Dengan auto-detect media type
MediaSender::bot($bot)
    ->to($chatId)
    ->media('https://example.com/video.mp4')  // Auto-detect: video
    ->caption('My video')
    ->send();
```

**Media Methods:**

- `photo($url)`, `video($url)`, `audio($url)`, `document($url)`, `animation($url)`, `voice($url)`
- `media($url)` - Auto-detect type dari extension
- `caption($text)` - Set caption (supports markdown)
- `captionHtml($html)` - Set caption tanpa konversi

### MediaGroupSender

[](#mediagroupsender)

Untuk mengirim album (2-10 media items).

```
use AndiSiahaan\GramseaTelegramBot\MediaGroupSender;

MediaGroupSender::bot($bot)
    ->to($chatId)
    ->photo('photo1.jpg')
    ->photo('photo2.jpg')
    ->video('video.mp4')
    ->caption('My album!')
    ->send();

// Dari array
MediaGroupSender::bot($bot)
    ->to($chatId)
    ->media(['photo1.jpg', 'photo2.jpg', 'photo3.jpg'])
    ->caption('Photos collection')
    ->send();
```

**Media Group Rules:**

- ✅ Photo + Video = OK
- ✅ Document + Document = OK
- ✅ Audio + Audio = OK
- ❌ Photo + Document = NOT OK
- ❌ Video + Audio = NOT OK

### Common Chaining Methods

[](#common-chaining-methods)

Semua sender class memiliki method berikut:

```
->to($chatId)           // Set target chat
->keyboard($markup)     // Set reply markup
->parseMode('HTML')     // Set parse mode
->silent()              // Disable notification
->protect()             // Protect content from forwarding
->replyTo($messageId)   // Reply to message
->allowPaidBroadcast()  // Allow paid broadcast
->send()                // Execute
->reset()               // Reset state for reuse
```

---

### MassMessageSender

[](#massmessagesender)

Untuk mengirim pesan secara concurrent ke banyak target sekaligus menggunakan Guzzle Pool. Setiap target memiliki konten sendiri (text, media, reply\_markup).

```
use AndiSiahaan\GramseaTelegramBot\MassMessageSender;

// Fluent - addTarget satu per satu
$result = $bot->mass()
    ->addTarget([
        'chat_id' => '123',
        'text' => 'Hello John!',
        'media' => ['https://example.com/img.jpg'],
        'reply_markup' => $keyboard
    ])
    ->addTarget([
        'chat_id' => '456',
        'text' => 'Hi Jane!',
        'media' => ['https://example.com/img2.jpg', 'https://example.com/vid.mp4']
    ])
    ->allowPaidBroadcast()
    ->send();

// Bulk - addTargets dari array
$targets = [
    ['chat_id' => '123', 'text' => 'Hello!'],
    ['chat_id' => '456', 'text' => 'Hi!', 'media' => ['img.jpg']],
];
$result = $bot->mass()
    ->addTargets($targets)
    ->concurrency(50)  // default 30
    ->send();
```

**Target Format:**

- `chat_id` (required) - Target chat ID
- `text` (optional) - Text pesan (supports markdown)
- `media` (optional) - String atau array URL media
- `reply_markup` (optional) - Keyboard (hasil dari ReplyMarkup class)

**Result Methods (`MassSendResult`):**

```
$result->totalSent();       // Jumlah sukses
$result->totalBlocked();    // Jumlah blocked (403/404)
$result->totalFailed();     // Jumlah gagal lainnya
$result->totalProcessed();  // Total yang diproses
$result->successRate();     // Persentase sukses

$result->getSent();         // Array of chat_ids yang sukses
$result->getBlocked();      // Array of chat_ids yang blocked
$result->getFailed();       // Array of chat_ids yang failed
$result->isAllSuccess();    // True jika semua sukses
```

**Global Options:**

```
->concurrency(30)       // Set concurrent limit (default 30)
->silent()              // Disable notification
->protect()             // Protect content
->allowPaidBroadcast()  // Allow paid broadcast
->parseMode('HTML')     // Set parse mode
```

---

📨 Update Wrapper
----------------

[](#-update-wrapper)

Object-oriented wrapper untuk mengakses data webhook.

```
use AndiSiahaan\GramseaTelegramBot\Support\Update;

// Dari webhook
$update = Update::fromWebhook();

// Atau dari JSON/array
$update = Update::fromJson($jsonString);
$update = Update::fromArray($data);

// Check update type
if ($update->isMessage()) {
    $msg = $update->message();

    echo $msg->text();
    echo $msg->from()->fullName();
    echo $msg->chat()->id();
    echo $msg->chat()->type();

    // Command parsing
    if ($msg->isCommand()) {
        echo $msg->command();      // 'start'
        echo $msg->commandArgs();  // 'ref123'
    }

    // Media checks
    if ($msg->hasPhoto()) {
        $photo = $msg->largestPhoto();
    }
}

// Shortcuts
echo $update->text();       // $update->anyMessage()->text()
echo $update->chatId();     // $update->anyMessage()->chatId()
echo $update->fromName();   // $update->from()->fullName()

// Callback query
if ($update->isCallbackQuery()) {
    echo $update->callbackData();
    echo $update->callbackQueryId();
}
```

**Type Checks:**

- `isMessage()`, `isEditedMessage()`, `isChannelPost()`, `isEditedChannelPost()`
- `isCallbackQuery()`, `isInlineQuery()`
- `isMyChatMember()`, `isChatMember()`, `isChatJoinRequest()`
- `hasMessage()` - any message type

**Message Object:**

- `text()`, `caption()`, `textOrCaption()`
- `from()`, `chat()`, `chatId()`, `fromId()`
- `hasPhoto()`, `hasVideo()`, `hasDocument()`, `hasMedia()`
- `isCommand()`, `command()`, `commandArgs()`
- `isReply()`, `replyToMessage()`

**Chat Object:**

- `id()`, `type()`, `name()`, `username()`
- `isPrivate()`, `isGroup()`, `isSupergroup()`, `isChannel()`

**User Object:**

- `id()`, `fullName()`, `username()`, `languageCode()`
- `isPremium()`, `mentionHtml()`

---

### Support Classes

[](#support-classes)

#### `Support\DeepLink`

[](#supportdeeplink)

Generate dan parse Telegram deep links.

```
use AndiSiahaan\GramseaTelegramBot\Support\DeepLink;

// Generate links
DeepLink::start('mybot', 'ref123');  // https://t.me/mybot?start=ref123
DeepLink::startGroup('mybot');        // https://t.me/mybot?startgroup
DeepLink::startChannel('mybot');      // https://t.me/mybot?startchannel
DeepLink::chat('username');           // https://t.me/username
DeepLink::message('channel', 123);    // https://t.me/channel/123
DeepLink::share('https://url.com', 'Check this!');

// Parse start parameter
$param = DeepLink::parseStartParameter('/start ref123');  // 'ref123'

// Referral codes
$code = DeepLink::generateReferralCode(123456, 'ref');  // 'ref_MTIzNDU2'
$userId = DeepLink::decodeReferralCode('ref_MTIzNDU2', 'ref');  // '123456'
```

#### `Support\TextFormatter`

[](#supporttextformatter)

Fluent builder untuk HTML formatting.

```
use AndiSiahaan\GramseaTelegramBot\Support\TextFormatter;

// Fluent builder
$text = TextFormatter::make()
    ->bold('Welcome!')
    ->newLine()
    ->text('Hello, ')
    ->mention('John', 123456789)
    ->newLine(2)
    ->italic('Status: ')
    ->code('Active')
    ->toString();

// Static shortcuts
echo TextFormatter::b('bold');           // bold
echo TextFormatter::i('italic');         // italic
echo TextFormatter::c('code');           // code
echo TextFormatter::a('Click', 'url');   // Click
echo TextFormatter::user('John', 123);   // John

// Markdown to HTML conversion
$html = TextFormatter::markdownToHtml('**bold** and *italic*');
// Output: bold and italic
```

#### `Support\ReplyMarkup`

[](#supportreplymarkup)

Format keyboard markup dengan auto row wrapping.

```
use AndiSiahaan\GramseaTelegramBot\Support\ReplyMarkup;

// Inline dengan URL
ReplyMarkup::inlineUrl([
    'Google' => 'https://google.com',
    'GitHub' => 'https://github.com'
]);

// Inline dengan callback
ReplyMarkup::inlineCallback([
    'Yes' => 'answer_yes',
    'No' => 'answer_no'
]);

// Reply keyboard
ReplyMarkup::reply(['Option A', 'Option B', 'Option C']);

// Remove & Force reply
ReplyMarkup::remove();
ReplyMarkup::forceReply(false, 'Type here...');
```

#### `Support\Limit`

[](#supportlimit)

Constants untuk Telegram API limits.

```
use AndiSiahaan\GramseaTelegramBot\Support\Limit;

// Constants
Limit::MESSAGE_TEXT;        // 4096
Limit::CAPTION;             // 1024
Limit::CALLBACK_DATA;       // 64
Limit::MEDIA_GROUP_MAX;     // 10
Limit::START_PARAMETER;     // 64

// Helper methods
Limit::truncateMessage($longText);     // Truncate dengan '...'
Limit::truncateCaption($longText);
Limit::splitText($veryLongText);       // Split ke array chunks
Limit::exceedsMessageLimit($text);     // bool
Limit::isValidStartParameter($param);  // bool
```

#### `Support\Emoji`

[](#supportemoji)

Emoji constants yang sering dipakai.

```
use AndiSiahaan\GramseaTelegramBot\Support\Emoji;

echo Emoji::CHECK;      // ✅
echo Emoji::CROSS;      // ❌
echo Emoji::WARNING;    // ⚠️
echo Emoji::FIRE;       // 🔥
echo Emoji::ROCKET;     // 🚀

// Helpers
Emoji::status(true);    // ✅ atau ❌
Emoji::number(5);       // 5️⃣
Emoji::circle('success'); // 🟢

// Progress bar
Emoji::progressBar(7, 10);  // ▓▓▓▓▓▓▓░░░
```

#### `Support\MediaHelper`

[](#supportmediahelper)

Deteksi tipe media dari file extension.

```
use AndiSiahaan\GramseaTelegramBot\Support\MediaHelper;

MediaHelper::getMediaType('photo.jpg');   // 'photo'
MediaHelper::getMediaType('video.mp4');   // 'video'
MediaHelper::getMimeType('doc.pdf');      // 'application/pdf'

MediaHelper::isImage('photo.png');  // true
MediaHelper::isVideo('clip.mp4');   // true
MediaHelper::isAudio('song.mp3');   // true
```

#### `Support\InlineKeyboard`

[](#supportinlinekeyboard)

Fluent builder untuk inline keyboard dengan pattern umum.

```
use AndiSiahaan\GramseaTelegramBot\Support\InlineKeyboard;

// Fluent builder
$keyboard = InlineKeyboard::make()
    ->callback('Option 1', 'opt_1')
    ->callback('Option 2', 'opt_2')
    ->row()
    ->url('Visit Site', 'https://example.com')
    ->row()
    ->back('main_menu')
    ->toArray();

// Pagination
$keyboard = InlineKeyboard::make()
    ->pagination(currentPage: 3, totalPages: 10, callbackPrefix: 'page_')
    ->toArray();

// Confirmation
$keyboard = InlineKeyboard::make()
    ->confirm('delete_yes_123', 'delete_no')
    ->toArray();

// Grid layout
$keyboard = InlineKeyboard::make()
    ->grid([
        ['text' => 'A', 'callback' => 'a'],
        ['text' => 'B', 'callback' => 'b'],
        ['text' => 'C', 'callback' => 'c'],
        ['text' => 'D', 'callback' => 'd'],
    ], columns: 2)
    ->toArray();

// Static helpers
InlineKeyboard::yesNo('confirm_yes', 'confirm_no');
InlineKeyboard::singleUrl('Click Here', 'https://example.com');
```

#### `Support\CallbackData`

[](#supportcallbackdata)

Encode/decode callback data dengan kompresi untuk ID besar.

```
use AndiSiahaan\GramseaTelegramBot\Support\CallbackData;

// Encode callback
$data = CallbackData::encode('user', ['123', 'view']);  // 'user:123:view'

// Decode callback
$parts = CallbackData::decode('user:123:view');  // ['user', '123', 'view']

// Parse dengan named params
$parsed = CallbackData::parse('user:123:view', ['id', 'action']);
// ['action' => 'user', 'id' => '123', 'action' => 'view']

// Check action
CallbackData::is($data, 'user');           // true
CallbackData::startsWith($data, 'user');   // true
CallbackData::getAction($data);            // 'user'
CallbackData::getParam($data, 0);          // '123'

// Compact encoding untuk ID besar (base62)
$compact = CallbackData::compact('u', [1234567890]);  // 'u:1LY7VK' (lebih pendek!)
$parsed = CallbackData::parseCompact('u:1LY7VK', [0]); // decode balik ke integer

// Validasi
CallbackData::isValid($data);        // true jika sendMessage([...]);
} catch (ForbiddenException $e) {
    // Bot diblok atau tidak punya akses
    if ($e->isBotBlocked()) {
        echo "User telah memblokir bot";
    } elseif ($e->isBotKicked()) {
        echo "Bot telah di-kick dari group";
    }
} catch (TooManyRequestsException $e) {
    // Rate limited - tunggu dan retry
    sleep($e->getWaitTime());
    // retry...
} catch (ApiException $e) {
    // Catch-all untuk API error lain
    echo "Error: " . $e->getMessage();
    echo "Code: " . $e->getErrorCode();
} catch (NetworkException $e) {
    // Network error (timeout, connection, SSL)
    if ($e->isTimeout()) {
        echo "Request timed out";
    }
}
```

#### Exception Methods

[](#exception-methods)

**ApiException (Base Class)**

```
$e->getMessage();        // Pesan error dari Telegram
$e->getErrorCode();      // HTTP error code (400, 403, 429, dll)
$e->getDescription();    // Description dari Telegram response
$e->getResponse();       // Full response array
$e->getRetryAfter();     // Waktu tunggu (untuk rate limit), null jika tidak ada
$e->getMigrateToChatId(); // Chat ID baru (untuk supergroup migration)
$e->isRetryable();       // True jika error bisa di-retry
```

**ForbiddenException**

```
$e->isBotBlocked();        // Bot diblok user
$e->isBotKicked();         // Bot di-kick dari group
$e->hasNoRightsToSend();   // Bot tidak punya hak kirim pesan
$e->isUserDeactivated();   // User sudah dihapus/nonaktif
```

**NotFoundException**

```
$e->isChatNotFound();      // Chat tidak ditemukan
$e->isMessageNotFound();   // Message tidak ditemukan
```

**ConflictException**

```
$e->isWebhookConflict();     // Conflict karena webhook
$e->isGetUpdatesConflict();  // Conflict karena getUpdates aktif
```

**TooManyRequestsException**

```
$e->getWaitTime();   // Waktu tunggu dalam detik (default 30)
$e->isRetryable();   // Selalu true
```

**NetworkException**

```
$e->getCurlErrorCode();  // cURL error code
$e->isTimeout();         // Timeout error
$e->isConnectionError(); // Connection error
$e->isSslError();        // SSL certificate error
```

---

📁 Struktur Library
------------------

[](#-struktur-library)

```
src/
├── Gramsea.php           # Class utama dengan magic method
├── BaseSender.php        # Abstract base class untuk senders
├── MessageSender.php     # General sender (auto-delegates)
├── TextSender.php        # Text message sender
├── MediaSender.php       # Single media sender
├── MediaGroupSender.php  # Media group sender
├── Curl.php              # HTTP client
├── HelperMethods.php     # Trait helper methods
├── Exception/
│   ├── ApiException.php           # Base exception untuk API errors
│   ├── BadRequestException.php    # 400 errors
│   ├── UnauthorizedException.php  # 401 errors
│   ├── ForbiddenException.php     # 403 errors
│   ├── NotFoundException.php      # 404 errors
│   ├── ConflictException.php      # 409 errors
│   ├── TooManyRequestsException.php # 429 rate limit
│   ├── TelegramServerException.php  # 500+ server errors
│   └── NetworkException.php       # Network/connection errors
└── Support/
    ├── CallbackData.php   # Callback data encoder
    ├── Chat.php           # Chat object wrapper
    ├── DeepLink.php       # Deep link generator
    ├── Emoji.php          # Emoji constants
    ├── InlineKeyboard.php # Inline keyboard builder
    ├── Limit.php          # API limits
    ├── MediaHelper.php    # Media type detection
    ├── Message.php        # Message object wrapper
    ├── ReplyMarkup.php    # Keyboard formatting
    ├── TextFormatter.php  # HTML text formatting
    ├── Update.php         # Update wrapper
    └── User.php           # User object wrapper

```

🧪 Testing
---------

[](#-testing)

```
composer test
```

📄 License
---------

[](#-license)

MIT License - lihat [LICENSE](LICENSE)

👤 Author
--------

[](#-author)

**Andi Saputra Siahaan**

- Website: [andipedia.com](https://andipedia.com)
- Email:

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance85

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~30 days

Recently: every ~14 days

Total

12

Last Release

77d ago

Major Versions

1.3.1 → 3.1.22025-12-19

PHP version history (2 changes)v1.1PHP &gt;=7.4

1.3PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/dd441fe5ce198a5c7e1b26a1dc0932edf674bd171e060c30f33a59f33275b630?d=identicon)[andisiahaan](/maintainers/andisiahaan)

---

Top Contributors

[![andisiahaan](https://avatars.githubusercontent.com/u/103436266?v=4)](https://github.com/andisiahaan "andisiahaan (17 commits)")

---

Tags

bottelegramtelegram bottelegram apigramsea

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/andisiahaan-gramsea-telegram-bot/health.svg)

```
[![Health](https://phpackages.com/badges/andisiahaan-gramsea-telegram-bot/health.svg)](https://phpackages.com/packages/andisiahaan-gramsea-telegram-bot)
```

###  Alternatives

[irazasyed/telegram-bot-sdk

The Unofficial Telegram Bot API PHP SDK

3.3k4.5M84](/packages/irazasyed-telegram-bot-sdk)[longman/telegram-bot

PHP Telegram bot

4.0k2.1M50](/packages/longman-telegram-bot)[tg-bot-api/bot-api-base

Clear and simple Telegram bot API

22278.8k2](/packages/tg-bot-api-bot-api-base)[telegram-bot-sdk/telegram-bot-sdk

The Telegram Bot API PHP SDK

32480.5k](/packages/telegram-bot-sdk-telegram-bot-sdk)[klev-o/telegram-bot-api

Simple and convenient object-oriented implementation Telegram bot API with php version ^7.4 support. You'll like it)

457.8k1](/packages/klev-o-telegram-bot-api)[luzrain/telegram-bot-api

PHP Wrapper for Telegram Bot API

1032.8k1](/packages/luzrain-telegram-bot-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
