PHP code example of afaztech / neili

1. Go to this page and download the library: Download afaztech/neili 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/ */

    

afaztech / neili example snippets



Neili\Client;
use Neili\Poller;
use Neili\Settings;

$settings = (new Settings())
    ->setAccessToken('YOUR_BOT_TOKEN');

$client = new Client($settings);
$poller = new Poller($client);

$poller->onMessage(function (array $update) use ($client) {
    $chatId = $update['message']['chat']['id'] ?? null;
    $text   = $update['message']['text'] ?? null;
    if ($chatId && $text) {
        $client->sendMessage($chatId, "Echo: {$text}");
    }
});

$poller->start();

use Neili\Settings;

$settings = (new Settings())
    ->setAccessToken('123456:ABC-DEF...')       //         // transfer timeout, connection timeout
    ->setPollerTimeout(5)
    ->setPollerBackoffBase(1)
    ->setPollerMaxBackoff(32)
    ->setPollerMaxConcurrency(50);

$client = new \Neili\Client($settings);

use Neili\Settings;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\StreamHandler;

$logger = new MonologLogger('bot', [new StreamHandler('/var/log/bot.log')]);

$settings = (new Settings($logger))->setAccessToken('YOUR_BOT_TOKEN');

use Neili\Logger;

$logger = new Logger('/var/log/neili.log', printToConsole: true);

use Amp\Http\Client\HttpClientBuilder;

$http = HttpClientBuilder::buildDefault();

$settings = (new Settings())
    ->setAccessToken('YOUR_BOT_TOKEN')
    ->setHttpClient($http);

$client->setHttpClient($newHttpClient);
$client->reconnect(); // rebuilds the default client from Settings

use Neili\Client;
use Neili\Poller;
use Neili\Settings;

$settings = (new Settings())->setAccessToken('YOUR_BOT_TOKEN');
$client   = new Client($settings);
$poller   = new Poller($client);

// Optional: catch errors raised inside any handler
$poller->onError(function (\Throwable $e, array $update, string $type) {
    error_log("[$type] {$e->getMessage()}");
});

// Global handler (fires for every update)
$poller->onUpdate(function (array $update) {
    // log all updates
});

// Type-specific handlers
$poller->onMessage(function (array $update) use ($client) {
    $chatId = $update['message']['chat']['id'] ?? null;
    $text   = $update['message']['text'] ?? null;
    if ($chatId && $text) {
        $client->sendMessage($chatId, "Echo: {$text}");
    }
});

$poller->onCallbackQuery(function (array $update) use ($client) {
    $client->answerCallbackQuery($update['callback_query']['id'], 'Got it!');
});

// Start polling (default: discard pending updates at startup)
$poller->start(discardOldUpdates: true);

$poller->onMessage(function () use ($poller) {
    $poller->stop();
});

use Neili\Client;
use Neili\Settings;

$settings = (new Settings())->setAccessToken('YOUR_BOT_TOKEN');
$client   = new Client($settings);

$update = $client->handleUpdate('YOUR_SECRET_TOKEN');

if (isset($update['message']['chat']['id'], $update['message']['text'])) {
    $client->sendMessage(
        $update['message']['chat']['id'],
        'Echo: ' . $update['message']['text']
    )->await();
}

$client->setWebhook(
    url: 'https://example.com/webhook.php',
    allowedUpdates: ['message', 'callback_query'],
    secretToken: 'YOUR_SECRET_TOKEN',
    dropPendingUpdates: true,
)->await();

use Neili\Client;
use Neili\Settings;

$settings = (new Settings())
    ->setAccessToken('YOUR_BOT_TOKEN')
    ->setMultiProcess(true)
    ->setPhpBinary('/usr/bin/php');

$client = new Client($settings);

// In webhook.php — returns immediately after forking
$client->handleUpdate('YOUR_SECRET_TOKEN');

use Neili\Exceptions\NeiliException;
use Neili\Exceptions\PermanentException;
use Neili\Exceptions\RateLimitException;
use Neili\Exceptions\TransientException;

try {
    $client->sendMessage(123, 'hi')->await();
} catch (RateLimitException $e) {
    sleep($e->getRetryAfter());
    // retry
} catch (TransientException $e) {
    // backoff and retry
} catch (PermanentException $e) {
    // log; do not retry — bad token, chat not found, etc.
    echo $e->getErrorCode();     // e.g. 400
    print_r($e->getParameters()); // raw "parameters" block
} catch (NeiliException $e) {
    // catch-all
}

// RateLimitException
$e->getRetryAfter(): int     // seconds, min 1
$e->getParameters(): array   // e.g. ['retry_after' => 30]

// PermanentException
$e->getErrorCode(): int
$e->getParameters(): array

// TransientException / NeiliException
// Standard \RuntimeException API

$poller = new Poller($client);

$poller->onMessage(fn (array $u) => /* ... */);
$poller->onCallbackQuery(fn (array $u) => /* ... */);
$poller->onPreCheckoutQuery(fn (array $u) => /* ... */);

$settings->setPollerMaxConcurrency(50);

use Neili\KeyboardBuilder;

// Reply keyboard
$reply = (new KeyboardBuilder())
    ->row('Yes', 'No')
    ->row('Maybe')
    ->resize(true)
    ->oneTime(false)
    ->persistent(true)
    ->inputFieldPlaceholder('Choose…')
    ->build();

// Inline keyboard with callback data
$inline = (new KeyboardBuilder())
    ->inlineRow(['Yes' => 'cb_yes', 'No' => 'cb_no'])
    ->inlineCallbackRow(['More' => 'cb_more'])
    ->build();

// Inline URL buttons
$urls = (new KeyboardBuilder())
    ->inlineUrlRow(['Open' => 'https://example.com'])
    ->build();

// Fully custom inline buttons (web_app, login_url, copy_text, …)
$custom = (new KeyboardBuilder())
    ->inlineButtonRow([
        ['text' => 'Open App', 'web_app' => ['url' => 'https://example.com']],
        ['text' => 'Copy', 'copy_text' => ['text' => 'abc']],
    ])
    ->build();

KeyboardBuilder::forceReplyObject('Reply to me', selective: false);
// → ['force_reply' => true, 'input_field_placeholder' => 'Reply to me', 'selective' => false]

KeyboardBuilder::removeKeyboard(true);
// → ['remove_keyboard' => true, 'selective' => true]

use Neili\Media;

$photo = new Media('/path/to/photo.jpg');
echo $photo->filePath; // realpath

use Neili\Media;

$client->sendPhoto(123, new Media('/path/to/photo.jpg'), caption: 'Hello!')->await();

$client->sendMediaGroup(123, [
    new Media('/path/to/a.jpg'),
    new Media('/path/to/b.jpg'),
    'https://example.com/remote.jpg',
], caption: 'Album')->await();

$client->sendDocument(123, new Media('/path/to/report.pdf'))->await();

$client->sendPaidMedia(
    chatId: 123,
    starCount: 100,
    media: [new Media('/path/to/photo.jpg')],
    caption: 'Premium content',
)->await();

// 1) Get file metadata
$info = $client->getFile('FILE_ID')->await();
$remotePath = $info['result']['file_path'];

// 2) Get a public download URL
$url = $client->getFileUrl($remotePath);
// → https://api.telegram.org/file/bot<TOKEN>/<file_path>

// 3) Stream to disk (64 KiB chunks — safe for large files)
$client->downloadFile('FILE_ID', '/path/to/save.bin')->await();

// Reply markup + parse mode
$client->sendMessage(
    chatId: 123,
    text: '<b>Hello</b>',
    keyboard: (new KeyboardBuilder())->inlineRow(['OK' => 'cb_ok'])->build(),
    parseMode: 'HTML',
)->await();

// Reply to a message using reply_parameters
$client->reply(123, 99, 'pong')->await();

// Rich message edit
$client->editMessageText(
    chatId: 123,
    messageId: 45,
    richMessage: ['html' => '<b>updated</b>'],
)->await();

$client->setChatPhoto($chatId, new Media('/path/to/photo.jpg'))->await();
$client->pinChatMessage($chatId, 42, disableNotification: true)->await();

$client->banChatMember($chatId, $userId, untilDate: time() + 3600)->await();
$client->promoteChatMember($chatId, $userId, ['can_delete_messages' => true])->await();

$client->uploadStickerFile($userId, new Media('/path/to/sticker.webp'), 'static')->await();

$client->createNewStickerSet(
    userId: $userId,
    name: 'my_pack_by_bot',
    title: 'My Pack',
    stickers: [['sticker' => 'attach://file', 'format' => 'static', 'emoji_list' => ['😀']]],
)->await();

$client->createForumTopic($chatId, 'New Topic', iconColor: 0x6FB9F0)->await();

$client->setMyCommands([
    ['command' => 'start', 'description' => 'Start the bot'],
])->await();

$client->setMyProfilePhoto(new Media('/path/to/avatar.jpg'))->await();

$client->sendInvoice(
    chatId: 123,
    title: 'Premium',
    description: 'Premium plan',
    payloadStr: 'order_123',
    providerToken: '',
    currency: 'XTR',
    prices: [['label' => 'Premium', 'amount' => 100]],
    subscriptionPeriod: 2592000,
)->await();

$client->answerInlineQuery(
    inlineQueryId: 'q1',
    results: [[
        'type' => 'article',
        'id' => '1',
        'title' => 'Sample',
        'input_message_content' => ['message_text' => 'Hello!'],
    ]],
    nextOffset: 'page-2',
    button: ['text' => 'Open', 'start_parameter' => 'go'],
)->await();

$client->setWebhook(
    url: 'https://example.com/webhook.php',
    certificate: new Media('/path/to/cert.pem'),
    maxConnections: 40,
    allowedUpdates: ['message', 'callback_query'],
    dropPendingUpdates: false,
    secretToken: 'secret',
    ipAddress: '1.2.3.4',
)->await();

$client->postStory(
    businessConnectionId: 'bc_123',
    content: ['type' => 'photo', 'photo' => 'https://example.com/p.jpg'],
    activePeriod: 86400,
    caption: 'New drop',
)->await();

$client->setBusinessAccountProfilePhoto('bc_123', new Media('/path/to/avatar.mp4'))->await();

$client->sendGift(userId: 42, chatId: null, giftId: 'gift-1', payForUpgrade: true)->await();

$client->verifyUser(42, customDescription: 'Verified merchant')->await();

$client->setManagedBotAccessSettings(
    userId: 42,
    isAccessRestricted: true,
    addedUserIds: [100, 200],
)->await();

$client->approveSuggestedPost($chatId, $messageId, sendDate: time() + 60)->await();
$client->declineSuggestedPost($chatId, $messageId, comment: 'Not suitable')->await();

$client->editEphemeralMessageText(
    chatId: 123,
    receiverUserId: 42,
    ephemeralMessageId: 5,
    text: 'Updated',
)->await();

$client->sendRichMessage(
    chatId: 123,
    richMessage: [
        'html' => '<b>Hello</b>',
        'media' => [
            ['media' => ['type' => 'photo', 'photo' => new Media('/path/to/a.jpg')]],
        ],
    ],
)->await();

$client->setPassportDataErrors($userId, [
    ['source' => 'data', 'type' => 'passport', 'field_name' => 'passport_number', 'message' => 'Invalid'],
])->await();

// Equivalent to $client->request('getMyStarBalance', [])
$client->getMyStarBalance()->await();

// With parameters
$client->getSomeCustomMethod(['foo' => 'bar'])->await();