PHP code example of erfanvahabpour / bale-bot-sdk
1. Go to this page and download the library: Download erfanvahabpour/bale-bot-sdk 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/ */
erfanvahabpour / bale-bot-sdk example snippets
return [
'default' => env('BALE_BOT_NAME', 'main_bot'),
'bots' => [
'main_bot' => [
'token' => env('BALE_BOT_TOKEN'),
'certificate_path' => env('BALE_CERTIFICATE_PATH'),
'webhook_url' => env('BALE_WEBHOOK_URL'),
'allowed_updates' => null,
'commands' => [
// Acme\Project\Commands\StartCommand::class,
],
],
'support_bot' => [
'token' => env('BALE_SUPPORT_BOT_TOKEN'),
'webhook_url' => env('BALE_SUPPORT_WEBHOOK_URL'),
'commands' => [
// Acme\Project\Commands\SupportTicketCommand::class,
],
],
],
'async_requests' => env('BALE_ASYNC_REQUESTS', false),
'http_client_handler' => null,
'base_bot_url' => null,
'resolve_command_dependencies' => true,
'commands' => [
\EFive\Bale\Commands\HelpCommand::class,
],
'command_groups' => [
// 'admin' => [Acme\Project\Commands\BanUserCommand::class],
],
'shared_commands' => [
// 'start' => Acme\Project\Commands\StartCommand::class,
],
];
use EFive\Bale\Api;
$bale = new Api('YOUR_BOT_TOKEN');
// 1. Authenticate and retrieve bot profile
$botUser = $bale->getMe();
echo "Connected as @{$botUser->username} (ID: {$botUser->id})
";
// 2. Send a text message
$message = $bale->sendMessage([
'chat_id' => '123456789',
'text' => 'Hello from Bale Bot PHP SDK! 🚀',
]);
echo "Message sent with ID: {$message->message_id}";
use EFive\Bale\Laravel\Facades\Bale;
// Uses default bot from config/bale.php
Bale::sendMessage([
'chat_id' => '123456789',
'text' => 'Hello from Laravel! 🎉',
]);
// Or target a specific configured bot instance:
Bale::bot('support_bot')->sendMessage([
'chat_id' => '123456789',
'text' => 'Support notification',
]);
use EFive\Bale\Laravel\Facades\Bale;
$response = Bale::sendMessage([
'chat_id' => '123456789',
'text' => '<b>Bold</b>, <i>Italic</i>, and <code>Code</code> message!',
'parse_mode' => 'HTML', // or 'Markdown'
'disable_web_page_preview' => false,
]);
// Forward message (with original sender header)
Bale::forwardMessage([
'chat_id' => 'TARGET_CHAT_ID',
'from_chat_id' => 'SOURCE_CHAT_ID',
'message_id' => 1024,
]);
// Copy message (without forward header)
$copiedId = Bale::copyMessage([
'chat_id' => 'TARGET_CHAT_ID',
'from_chat_id' => 'SOURCE_CHAT_ID',
'message_id' => 1024,
'caption' => 'New custom caption for copied media',
]);
// Edit message text
Bale::editMessageText([
'chat_id' => '123456789',
'message_id' => 1024,
'text' => 'Updated text content.',
]);
// Edit media caption
Bale::editMessageCaption([
'chat_id' => '123456789',
'message_id' => 1024,
'caption' => 'Updated photo caption.',
]);
// Delete message
Bale::deleteMessage([
'chat_id' => '123456789',
'message_id' => 1024,
]);
use EFive\Bale\Laravel\Facades\Bale;
$replyMarkup = [
'inline_keyboard' => [
[
['text' => '🌐 Visit Website', 'url' => 'https://bale.ai'],
['text' => '🔔 Subscribe', 'callback_data' => 'action_subscribe'],
],
[
// Open a Bale WebApp / Mini-App
['text' => '📱 Launch Mini-App', 'web_app' => ['url' => 'https://miniapp.example.com']],
// Copy text button
['text' => '📋 Copy Promo Code', 'copy_text' => ['text' => 'DISCOUNT2026']],
],
],
];
Bale::sendMessage([
'chat_id' => '123456789',
'text' => 'Select an option from the menu:',
'reply_markup' => $replyMarkup,
]);
$replyKeyboard = [
'keyboard' => [
[
['text' => '📦 View Products'],
['text' => '📞 Contact Us'],
],
[
['text' => '📍 Send Location', 'request_location' => true],
['text' => '📱 Share Phone Number', 'request_contact' => true],
],
],
'resize_keyboard' => true,
'one_time_keyboard' => false,
];
Bale::sendMessage([
'chat_id' => '123456789',
'text' => 'Welcome! Choose a menu action:',
'reply_markup' => $replyKeyboard,
]);
// Remove Reply Keyboard
Bale::sendMessage([
'chat_id' => '123456789',
'text' => 'Keyboard removed.',
'reply_markup' => ['remove_keyboard' => true],
]);
use EFive\Bale\FileUpload\InputFile;
use EFive\Bale\Laravel\Facades\Bale;
// 1. Send Photo from local filesystem
Bale::sendPhoto([
'chat_id' => '123456789',
'photo' => InputFile::file('/path/to/banner.jpg'),
'caption' => 'Check out our new release! 📸',
]);
// 2. Send Document from dynamic string content
Bale::sendDocument([
'chat_id' => '123456789',
'document' => InputFile::createFromContents('Invoice Data: ...', 'invoice_982.txt'),
'caption' => 'Your monthly statement',
]);
// 3. Send Audio / MP3
Bale::sendAudio([
'chat_id' => '123456789',
'audio' => InputFile::file('/path/to/podcast.mp3'),
'title' => 'Episode 42',
'performer' => 'Bale Podcast',
]);
// 4. Send Video & GIF Animations
Bale::sendVideo([
'chat_id' => '123456789',
'video' => InputFile::file('/path/to/demo.mp4'),
'caption' => 'Video tutorial 🎥',
]);
Bale::sendAnimation([
'chat_id' => '123456789',
'animation' => InputFile::file('/path/to/sticker.gif'),
]);
// 5. Send Voice note
Bale::sendVoice([
'chat_id' => '123456789',
'voice' => InputFile::file('/path/to/voice.ogg'),
]);
// 6. Send Media Group (Album)
Bale::sendMediaGroup([
'chat_id' => '123456789',
'media' => [
[
'type' => 'photo',
'media' => InputFile::file('/path/to/image1.jpg'),
'caption' => 'Photo Album #1',
],
[
'type' => 'photo',
'media' => InputFile::file('/path/to/image2.jpg'),
],
],
]);
// Retrieve file metadata
$file = Bale::getFile(['file_id' => 'FILE_ID_FROM_UPDATE']);
echo "File size: {$file->file_size} bytes
";
// Download file to local storage
$savedPath = Bale::downloadFile($file, storage_path('app/downloads/' . basename($file->file_path)));
use EFive\Bale\Laravel\Facades\Bale;
// Possible actions: typing, upload_photo, record_video, upload_video, record_audio, upload_audio, upload_document, find_location
Bale::sendChatAction([
'chat_id' => '123456789',
'action' => 'typing',
]);
use EFive\Bale\Laravel\Facades\Bale;
$chatId = '-100123456789';
// 1. Get Chat information and member count
$chat = Bale::getChat(['chat_id' => $chatId]);
$membersCount = Bale::getChatMembersCount(['chat_id' => $chatId]);
// 2. Retrieve administrators list
$admins = Bale::getChatAdministrators(['chat_id' => $chatId]);
foreach ($admins as $admin) {
echo "{$admin->user->first_name} - Status: {$admin->status}
";
}
// 3. Promote chat member
Bale::promoteChatMember([
'chat_id' => $chatId,
'user_id' => 123456,
'can_change_info' => true,
'can_delete_messages' => true,
'can_invite_users' => true,
'can_restrict_members' => false,
'can_pin_messages' => true,
'can_promote_members' => false,
]);
// 4. Ban & Unban members
Bale::banChatMember(['chat_id' => $chatId, 'user_id' => 123456]);
Bale::unbanChatMember(['chat_id' => $chatId, 'user_id' => 123456]);
// 5. Pin and Unpin messages
Bale::pinChatMessage(['chat_id' => $chatId, 'message_id' => 1024, 'disable_notification' => false]);
Bale::unpinChatMessage(['chat_id' => $chatId, 'message_id' => 1024]);
Bale::unpinAllChatMessages(['chat_id' => $chatId]);
// 6. Manage Invite Links
$newInvite = Bale::createChatInviteLink([
'chat_id' => $chatId,
'expire_date' => time() + 86400,
'member_limit' => 50,
]);
use Illuminate\Http\Request;
use EFive\Bale\Laravel\Facades\Bale;
Route::post('/bale/webhook', function (Request $request) {
// Automatically parses incoming request into Update object
$update = Bale::getWebhookUpdate();
// 1. Handle incoming text message
if ($update->isType('message')) {
$message = $update->message;
$chatId = $message->chat->id;
$text = $message->text;
if ($text === '/start') {
Bale::sendMessage([
'chat_id' => $chatId,
'text' => "Hello {$message->from->first_name}! Welcome to our bot.",
]);
}
}
// 2. Handle Inline Button Callbacks
elseif ($update->isType('callback_query')) {
$callback = $update->callbackQuery;
// Answer callback to remove loading state on button
Bale::answerCallbackQuery([
'callback_query_id' => $callback->id,
'text' => 'Action performed successfully! ✅',
'show_alert' => false,
]);
}
return response()->json(['ok' => true]);
});
use EFive\Bale\Api;
$bale = new Api('YOUR_BOT_TOKEN');
$offset = 0;
while (true) {
$updates = $bale->getUpdates(['offset' => $offset, 'timeout' => 30]);
foreach ($updates as $update) {
$offset = $update->updateId + 1;
if ($update->isType('message')) {
$bale->sendMessage([
'chat_id' => $update->message->chat->id,
'text' => "Echo: " . $update->message->text,
]);
}
}
sleep(1);
}
namespace App\Bale\Commands;
use EFive\Bale\Commands\Command;
use App\Services\UserService;
class StartCommand extends Command
{
/** @var string Command trigger */
protected string $name = 'start';
/** @var string[] Aliases */
protected array $aliases = ['begin', 'welcome'];
/** @var string Description */
protected string $description = 'Start interaction with the bot';
/** @var string Argument Pattern (e.g. /start {ref}) */
protected string $pattern = '{ref}';
// Automatic Dependency Injection via Laravel Container!
public function __construct(protected UserService $userService)
{
}
public function handle(): void
{
$user = $this->getUpdate()->getMessage()->from;
$referral = $this->argument('ref', 'none');
$this->userService->registerOrUpdate($user->id, $user->username);
// Helper reply method (automatically populates chat_id)
$this->replyWithMessage([
'text' => "Welcome {$user->first_name}! (Referral: {$referral})",
'reply_markup' => [
'inline_keyboard' => [
[['text' => '🚀 Get Started', 'callback_data' => 'get_started']]
]
]
]);
}
}
'commands' => [
\App\Bale\Commands\StartCommand::class,
\EFive\Bale\Commands\HelpCommand::class,
],
Route::post('/bale/webhook', function () {
// Process inbound commands automatically
Bale::commandsHandler(true);
return response()->json(['ok' => true]);
});
use EFive\Bale\Laravel\Facades\Bale;
// 1. Send an Invoice in chat
Bale::sendInvoice([
'chat_id' => '123456789',
'title' => 'VIP Subscription',
'description' => '1-Month access to VIP trading channel',
'payload' => 'user_order_88319',
'provider_token' => 'YOUR_PAYMENT_PROVIDER_TOKEN',
'prices' => [
['label' => 'Base Price', 'amount' => 500000], // Amount in Rials / Tomans
['label' => 'Tax', 'amount' => 45000],
],
]);
// 2. Generate a shareable Invoice Link
$paymentUrl = Bale::createInvoiceLink([
'title' => 'E-Book Download',
'description' => 'Full PDF Guide',
'payload' => 'ebook_order_102',
'provider_token' => 'YOUR_PAYMENT_PROVIDER_TOKEN',
'prices' => [
['label' => 'Total', 'amount' => 150000],
],
]);
// 3. Handle Pre-Checkout Query in Webhook
if ($update->isType('pre_checkout_query')) {
$queryId = $update->pre_checkout_query->id;
// Verify stock or condition and approve payment
Bale::answerPreCheckoutQuery([
'pre_checkout_query_id' => $queryId,
'ok' => true,
]);
}
// 4. Inquire Transaction Status
$transaction = Bale::inquireTransaction([
'payment_charge_id' => 'chg_sample_id_123',
]);
echo "Transaction Status: {$transaction->status}
";
use EFive\Bale\FileUpload\InputFile;
use EFive\Bale\Laravel\Facades\Bale;
// Send existing sticker by file_id
Bale::sendSticker([
'chat_id' => '123456789',
'sticker' => 'STICKER_FILE_ID',
]);
// Upload sticker image file
$file = Bale::uploadStickerFile([
'user_id' => 123456,
'sticker' => InputFile::file('/path/to/sticker.png'),
'sticker_format' => 'static',
]);
// Create new sticker set
Bale::createNewStickerSet([
'user_id' => 123456,
'name' => 'animals_by_mybot',
'title' => 'Cool Animals Pack',
'stickers' => [
[
'sticker' => InputFile::file('/path/to/lion.png'),
'emoji_list' => ['🦁', '👑'],
]
],
'sticker_format' => 'static',
]);
use EFive\Bale\Laravel\Facades\Bale;
// Set Bot Commands
Bale::setMyCommands([
'commands' => [
['command' => 'start', 'description' => 'Start the bot'],
['command' => 'help', 'description' => 'Show help menu'],
['command' => 'account', 'description' => 'Manage your subscription'],
],
]);
// Retrieve registered commands
$commands = Bale::getMyCommands();
// Clear commands menu
Bale::deleteMyCommands();
use EFive\Bale\Events\UpdateWasReceived;
use App\Listeners\LogBaleUpdateListener;
protected $listen = [
UpdateWasReceived::class => [
LogBaleUpdateListener::class,
],
];
namespace App\Listeners;
use EFive\Bale\Events\UpdateWasReceived;
class LogBaleUpdateListener
{
public function handle(UpdateWasReceived $event): void
{
$update = $event->update;
$botApi = $event->bale;
\Log::info('Received Bale Update ID: ' . $update->updateId);
}
}
use EFive\Bale\Exceptions\BaleSDKException;
use EFive\Bale\Exceptions\BaleResponseException;
use EFive\Bale\Exceptions\BaleBotNotFoundException;
try {
$response = Bale::sendMessage([
'chat_id' => '123456789',
'text' => 'Test message',
]);
} catch (BaleResponseException $e) {
// API returned error response
echo "HTTP Status: " . $e->getHttpStatusCode();
echo "Error Message: " . $e->getMessage();
echo "Error Code: " . $e->getErrorCode();
$rawResponse = $e->getRawResponse();
} catch (BaleBotNotFoundException $e) {
// Referenced unconfigured bot name
echo "Bot not found: " . $e->getMessage();
} catch (BaleSDKException $e) {
// General SDK exception
echo "SDK Error: " . $e->getMessage();
}
$bale = new \EFive\Bale\Api('YOUR_TOKEN', async: true);
$bale = new \EFive\Bale\Api('YOUR_TOKEN', baseBotUrl: 'https://proxy.example.com/bot');
use EFive\Bale\Laravel\Facades\Bale;
Bale::sendMessage([
'chat_id' => $chatId,
'text' => 'سلام! ربات بله لاراول شما با موفقیت راهاندازی شد 🚀',
]);
$inlineKeyboard = [
'inline_keyboard' => [
[
['text' => '🌐 مشاهده وبسایت', 'url' => 'https://github.com/ErfanVahabpour/Bale-Bot-SDK'],
['text' => '⚡ تأیید درخواست', 'callback_data' => 'confirm_action'],
],
[
['text' => '📱 باز کردن مینیاپ', 'web_app' => ['url' => 'https://app.example.com']],
]
]
];
Bale::sendMessage([
'chat_id' => $chatId,
'text' => 'لطفاً یکی از گزینههای زیر را انتخاب کنید:',
'reply_markup' => json_encode($inlineKeyboard),
]);
Bale::sendInvoice([
'chat_id' => $chatId,
'title' => 'اشتراک ویژه یکماهه',
'description' => 'دسترسی نامحدود به تمامی خدمات ربات',
'payload' => 'order_invoice_id_1002',
'provider_token' => env('BALE_PAYMENT_PROVIDER_TOKEN'),
'currency' => 'IRR',
'prices' => [
['label' => 'اشتراک ویژه', 'amount' => 500000] // 500,000 Rials
],
]);
'bots' => [
'default' => ['token' => env('BALE_BOT_TOKEN')],
'support_bot' => ['token' => env('BALE_SUPPORT_BOT_TOKEN')],
'sales_bot' => ['token' => env('BALE_SALES_BOT_TOKEN')],
],
// Dispatch message via support bot
Bale::bot('support_bot')->sendMessage([
'chat_id' => $userId,
'text' => 'سلام، کارشناس پشتیبانی در خدمت شماست.',
]);
// Dispatch message via main default bot
Bale::sendMessage([
'chat_id' => $userId,
'text' => 'پیام از ربات اصلی.',
]);
bash
php artisan vendor:publish --tag="bale-config"
bash
php artisan bale:webhook --set --url=https://your-domain.com/bale/webhook
bash
php artisan bale:polling