PHP code example of bootdesk / chat-sdk-core

1. Go to this page and download the library: Download bootdesk/chat-sdk-core 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/ */

    

bootdesk / chat-sdk-core example snippets


use BootDesk\ChatSDK\Core\Chat;
use BootDesk\ChatSDK\Core\State\MemoryStateAdapter;
use BootDesk\ChatSDK\Core\Concurrency\DefaultConcurrencyHandler;

$chat = new Chat(
    state: new MemoryStateAdapter(),
    userName: 'MyBot',
    config: [],
    concurrencyHandler: new DefaultConcurrencyHandler($state, ['concurrency' => 'drop']),
);

// Register handlers
$chat->onNewMessage('/^hello$/i', function (MessageContext $ctx) {
    $ctx->thread->post('Hey there!');
});

$chat->onDirectMessage(function (MessageContext $ctx) {
    $ctx->thread->post('You DMd me!');
});

$chat->onNewMention(function (MessageContext $ctx) {
    $ctx->thread->post('You mentioned me!');
});

$thread = $chat->thread('slack:C12345');

$thread->post('Hello!');
$thread->edit('msg-id', 'Updated text');
$thread->delete('msg-id');
$thread->subscribe();
$thread->startTyping();

$thread->setState(['step' => 2]);
$state = $thread->getState();

use BootDesk\ChatSDK\Core\Cards\TextStyle;

TextStyle::Plain;  // default
TextStyle::Bold;   // rendered as **bold** or <b> depending on platform
TextStyle::Muted;  // rendered as _italic_ or muted color

use BootDesk\ChatSDK\Core\Cards\Button;
use BootDesk\ChatSDK\Core\Cards\ButtonStyle;
use BootDesk\ChatSDK\Core\Cards\LinkButton;

// Action button — triggers onAction handler when clicked
Button::primary('Confirm', 'order_confirm', ['item' => 'Pizza']);
Button::danger('Cancel', 'order_cancel');
Button::secondary('Maybe', 'order_maybe');

// Link button — opens a URL in the client
LinkButton::primary('Open Dashboard', 'https://dash.example.com');
LinkButton::danger('Report Issue', 'https://github.com/org/repo/issues');

use BootDesk\ChatSDK\Core\Cards\TableAlignment;

$card = Card::make()
    ->table(
        ['Service', 'Status', 'Uptime'],
        [
            ['API', '✅ Healthy', '99.9%'],
            ['Database', '✅ Connected', '99.8%'],
            ['Queue', '✅ Running', '100%'],
        ],
        [TableAlignment::Left, TableAlignment::Center, TableAlignment::Right],
    );

use BootDesk\ChatSDK\Core\Cards\Card;
use BootDesk\ChatSDK\Core\Cards\Button;
use BootDesk\ChatSDK\Core\Cards\ButtonStyle;
use BootDesk\ChatSDK\Core\Cards\TextStyle;
use BootDesk\ChatSDK\Core\Cards\TableAlignment;

$card = Card::make()
    ->header('System Status')
    ->text('All services are operational.', TextStyle::Bold)
    ->divider()
    ->table(
        ['Service', 'Status', 'Uptime'],
        [
            ['API', '✅ Healthy', '99.9%'],
            ['Database', '✅ Connected', '99.8%'],
            ['Queue', '✅ Running', '100%'],
        ],
        [TableAlignment::Left, TableAlignment::Center, TableAlignment::Right],
    )
    ->divider()
    ->link('View details', 'https://status.example.com')
    ->linkButton('Dashboard', 'https://dash.example.com', ButtonStyle::Primary)
    ->actions([Button::primary('Refresh', 'refresh_status')]);

$thread->post($card);

$card = Card::make()
    ->imageUrl('https://picsum.photos/seed/demo/800/200', 'Demo banner')
    ->header('Status')
    ->text('All good!');

$card = Card::make()
    ->header('Deploy Ready')
    ->section(fn ($s) => $s
        ->text('Build passed on main')
        ->fields(['Branch' => 'main', 'Status' => 'passing'])
    )
    ->actions([Button::primary('Deploy', 'deploy')]);

use BootDesk\ChatSDK\Core\Attachment;
use BootDesk\ChatSDK\Core\PostableMessage;

$message = new PostableMessage(
    content: 'Here is a photo:',
    attachments: [
        new Attachment('image', 'https://picsum.photos/seed/foo/800/600', 'Photo', 'image/jpeg'),
    ],
);
$thread->post($message);

use BootDesk\ChatSDK\Core\FileUpload;
use BootDesk\ChatSDK\Core\PostableMessage;

// From file path
$upload = FileUpload::fromFilename('/path/to/document.pdf');

// From string data
$upload = new FileUpload(file_get_contents($url), 'photo.jpg', 'image/jpeg');

$message = new PostableMessage(
    content: 'Here is your file:',
    files: [$upload],
);
$thread->post($message);

use BootDesk\ChatSDK\Core\Contracts\FileUploadConverter;
use BootDesk\ChatSDK\Core\Attachment;
use BootDesk\ChatSDK\Core\FileUpload;

class S3FileUploader implements FileUploadConverter
{
    public function upload(FileUpload $file, Adapter $adapter): Attachment
    {
        $url = $this->s3->upload($file->getData(), $file->filename);
        return new Attachment('file', $url, $file->filename, $file->mimeType);
    }
}

$this->app->bind(FileUploadConverter::class, S3FileUploader::class);

use BootDesk\ChatSDK\Core\Conversations\Conversation;
use BootDesk\ChatSDK\Core\Thread;
use BootDesk\ChatSDK\Core\Message;

class OrderConversation extends Conversation
{
    public function start(Thread $thread, Message $message): void
    {
        $this->ask($thread, 'What would you like to order?', 'handleOrder');
    }

    public function handleOrder(Thread $thread, Message $message): void
    {
        $this->say($thread, "You ordered: {$message->text}");
        $this->end($thread);
    }
}

$chat->conversationManager->start(OrderConversation::class, $thread, $message);

use BootDesk\ChatSDK\Telegram\TelegramAdapter;

class MyTelegramAdapter extends TelegramAdapter
{
    protected function apiCall(string $method, array $params): array
    {
        // Add custom logging, retry logic, etc.
        return parent::apiCall($method, $params);
    }

    protected function buildMessageParams(PostableMessage $message): array
    {
        $params = parent::buildMessageParams($message);

        // Add custom parameters
        $params['disable_web_page_preview'] = true;

        return $params;
    }
}

use BootDesk\ChatSDK\Core\Support\AdapterRegistry;

// Register in a service provider or bootstrap file

// Replace an existing adapter
AdapterRegistry::register('telegram', MyTelegramAdapter::class);

// Or register as a new adapter
AdapterRegistry::register('telegram-custom', MyTelegramAdapter::class);

use BootDesk\ChatSDK\Core\Modals\Modal;
use BootDesk\ChatSDK\Core\Modals\TextInput;
use BootDesk\ChatSDK\Core\Modals\Select;
use BootDesk\ChatSDK\Core\Modals\ExternalSelect;
use BootDesk\ChatSDK\Core\Modals\RadioSelect;
use BootDesk\ChatSDK\Core\Modals\SelectOption;

$modal = new Modal(
    callbackId: 'feedback',
    title: 'Submit Feedback',
    submitLabel: 'Send',
    closeLabel: 'Cancel',
    notifyOnClose: true,
    children: [
        new TextInput(
            id: 'comment',
            label: 'Comment',
            placeholder: 'Enter your feedback...',
            multiline: true,
        ),
        new ExternalSelect(
            id: 'category',
            label: 'Category',
            placeholder: 'Start typing...',
            minQueryLength: 1,
        ),
    ],
);

use BootDesk\ChatSDK\Core\Modals\Modal;
use BootDesk\ChatSDK\Core\Modals\TextInput;

$chat->onAction('feedback', function (ActionEvent $event) {
    $event->openModal(new Modal(
        callbackId: 'feedback',
        title: 'Submit Feedback',
        submitLabel: 'Send',
        children: [
            new TextInput(id: 'comment', label: 'Comment', multiline: true),
        ],
    ));
});

$chat->onOptionsLoad(function (OptionsLoadEvent $event) {
    $prefix = strtolower($event->query);
    $all = [
        ['text' => 'Bug Report', 'value' => 'bug'],
        ['text' => 'Feature Request', 'value' => 'feature'],
    ];

    return $prefix === ''
        ? $all
        : array_values(array_filter($all, fn ($o) => str_starts_with(strtolower($o['text']), $prefix)));
});

$chat->onModalSubmit(function (ModalSubmitEvent $event) {
    $event->relatedThread?->post("Form submitted: " . json_encode($event->values));
});

$chat->onModalClose(function (ModalCloseEvent $event) {
    $event->relatedThread?->post("Form closed without submitting.");
});