PHP code example of sashalenz / viber-bot-api

1. Go to this page and download the library: Download sashalenz/viber-bot-api 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/ */

    

sashalenz / viber-bot-api example snippets


use Sashalenz\ViberBotApi\ViberBotApi;
use Sashalenz\ViberBotApi\Messages\TextMessage;

ViberBotApi::messages()->send($viberUserId, new TextMessage('Привіт 👋'));

// per-call token override (multi-account: e.g. dev vs prod bot)
ViberBotApi::messages()->token($prodToken)->send($id, new TextMessage('…'));

// broadcast to up to 300 receivers per call
ViberBotApi::messages()->broadcast([$id1, $id2], new TextMessage('…'));

use Sashalenz\ViberBotApi\Messages\{
    TextMessage, PictureMessage, VideoMessage, FileMessage, ContactMessage,
    LocationMessage, UrlMessage, StickerMessage, RichMediaMessage,
};
use Sashalenz\ViberBotApi\Keyboards\Button;

new TextMessage('Hello');                                   // ≤ 7000 chars
new PictureMessage('https://cdn/p.jpg', text: 'caption');   // caption ≤ 768
new VideoMessage('https://cdn/v.mp4', size: 1_200_000);     // ≤ 26 MB
new FileMessage('https://cdn/d.pdf', size: 50_000, fileName: 'invoice.pdf'); // ≤ 50 MB
new ContactMessage('Itamar', '+972511123123');
new LocationMessage(50.4501, 30.5234);
new UrlMessage('https://example.com');
new StickerMessage(40_100);
new RichMediaMessage(buttons: [Button::make()->text('Buy')->actionBody('buy')]);

new TextMessage('Hello', trackingData: 'order-42', minApiVersion: 7);
new StickerMessage(40_100, trackingData: 'sticker-ctx');

use Sashalenz\ViberBotApi\Keyboards\{Keyboard, Button, SharePhoneButton};

$keyboard = Keyboard::make()
    ->button(Button::make()->text('Yes')->actionType('reply')->actionBody('yes'))
    ->button(Button::make()->text('No')->actionType('reply')->actionBody('no'))
    ->toArray();

ViberBotApi::messages()->send($id, new TextMessage('Confirm?', $keyboard));

// the full documented field set is supported on both builders:
Keyboard::make()
    ->customDefaultHeight(50)->heightScale(80)
    ->buttonsGroup(columns: 6, rows: 2)
    ->inputFieldState('hidden')
    ->button(
        Button::make()
            ->text('Open')->actionType('open-url')->actionBody('https://example.com')
            ->openUrl(type: 'internal', mediaType: 'not-media')
            ->textSize('large')->textAlign('center', 'middle')->textOpacity(80)
            ->bgMedia('https://cdn/bg.gif', type: 'gif', scaleType: 'fill', loop: false)
            ->image('https://cdn/i.png', scaleType: 'crop')
            ->frame(borderWidth: 2, borderColor: '#000000', cornerRadius: 10)
    );

// onboarding: ask the user to share their phone (binds a Viber id to a CRM record)
ViberBotApi::messages()->send(
    $id,
    new TextMessage('Share your number', (new SharePhoneButton)->toArray()),
);

$info = ViberBotApi::account()->info();   // read-only — safe on a live bot
$info->webhook;                            // current webhook url
$info->subscribers_count;

ViberBotApi::account()->setWebhook('https://example.com/viber-bot-api/webhook');
ViberBotApi::account()->removeWebhook();   // rollback

$details = ViberBotApi::users()->details($viberUserId); // cache: max 2 calls/12h per user
$details->user;                                          // id, name, avatar, country, …

ViberBotApi::users()->online([$id1, $id2]);             // ≤ 100 ids per call

use Closure;
use Sashalenz\ViberBotApi\Bot\Viber;
use Sashalenz\ViberBotApi\Dto\Events\MessageEvent;
use Sashalenz\ViberBotApi\Dto\Update;
use Sashalenz\ViberBotApi\Messages\TextMessage;

$bot = app(Viber::class);

// middleware runs before/after, in registration order, and can short-circuit
$bot->middleware(fn (Update $update, Closure $next) => $next($update));

$bot->onText('/start', fn (MessageEvent $e, Viber $bot) => $bot->reply(new TextMessage('Hi!')));
$bot->onContact(fn (MessageEvent $e) => logger()->info('phone', [$e->message->contact?->phone_number]));
$bot->onMessage(fn (MessageEvent $e, Viber $bot) => $bot->reply(new TextMessage('echo: '.$e->message->text)));

$bot->onSubscribed(fn ($e) => /* … */ null);
$bot->onDelivered(fn ($e) => /* … */ null);   // also onSeen / onFailed / onUnsubscribed

$bot->onConversationStarted(fn ($e) => new TextMessage('Welcome 👋'));

use Sashalenz\ViberBotApi\RequestData\{SendMessageData, SetWebhookData};
use Sashalenz\ViberBotApi\Messages\TextMessage;

ViberBotApi::messages()->sendData(new SendMessageData(
    receiver: $viberUserId,
    message: new TextMessage('Привіт'),
    trackingData: 'order-42',
));

ViberBotApi::account()->setWebhookData(new SetWebhookData(
    url: 'https://example.com/viber-bot-api/webhook',  // must be HTTPS
    eventTypes: ['message', 'conversation_started'],
));
bash
php artisan vendor:publish --tag="viber-bot-api-config"
bash
php artisan viber:get-account-info            # read-only PA snapshot
php artisan viber:set-webhook {url?} --force  # register webhook (destructive — overwrites)
php artisan viber:delete-webhook --force      # detach webhook (rollback)