PHPackages                             afaztech/neili - 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. [Queues &amp; Workers](/categories/queues)
4. /
5. afaztech/neili

ActiveLibrary[Queues &amp; Workers](/categories/queues)

afaztech/neili
==============

Neili is an async-first PHP library built on Amp that streamlines creating robust Telegram bots. It provides a non-blocking HTTP client, wrappers for all Telegram Bot API methods, a long-polling Poller with concurrency control, and a flexible webhook handler. Neili is optimized for both constrained hosting environments and long-running worker processes.

2.2.6(3mo ago)4161MITPHPPHP &gt;=8.1

Since Oct 28Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/AfazTech/Neili)[ Packagist](https://packagist.org/packages/afaztech/neili)[ Docs](https://github.com/imafaz/neili)[ RSS](/packages/afaztech-neili/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (3)Versions (10)Used By (0)

Neili — Asynchronous Telegram Bot Library for PHP
=================================================

[](#neili--asynchronous-telegram-bot-library-for-php)

Neili is an async-first PHP library built on Amp that streamlines creating robust Telegram bots. It provides a non-blocking HTTP client, wrappers for all Telegram Bot API methods, a long-polling `Poller` with concurrency control, and a flexible webhook handler. Neili is optimized for both constrained hosting environments and long-running worker processes.

**If this project is helpful to you, you may wish to give it a**🌟 **to support future updates and feature additions!**

---

Donate
------

[](#donate)

[ ![](https://camo.githubusercontent.com/6172dcfba6291a8708f0f4162f69dbd651851f1d047ec49573514d5e59127bed/687474703a2f2f7777772e636f6666656574652e69722f696d616765732f627574746f6e732f6c656d6f6e63686966666f6e2e706e67)](http://www.coffeete.ir/afaz)---

Table of contents
-----------------

[](#table-of-contents)

- [Introduction](#introduction)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Multi-process](#multi-process)
- [Polling vs Webhook](#polling-vs-webhook)
- [Settings](#settings)
- [Keyboard Builder](#keyboard-builder)
- [Client Methods Reference](#client-methods-reference)
- [TODO](#TODO)
- [License](#license)

---

Introduction
------------

[](#introduction)

Neili wraps the Telegram Bot API with Amp-based asynchronous primitives. It offers:

- Safe, non-blocking HTTP requests
- Async message sending, media uploads, and chat management
- Receiving updates via long polling or webhooks
- Lightweight, framework-agnostic architecture suitable for both short-lived webhook endpoints and long-running pollers

---

Features
--------

[](#features)

- Async-first Telegram Bot API wrapper built on Amp HTTP client
- `Poller` implementation with configurable timeout, exponential backoff, and concurrency
- Webhook helper compatible with standard PHP and multi-process setups
- Minimal external dependencies for easy integration
- Multiprocess support for concurrent update handling
- Examples included for polling, webhook, sending messages/media, and keyboards

---

Requirements
------------

[](#requirements)

Neili requires the following environment and extensions:

- **PHP &gt;= 8.1**
- **amphp/file ^3.2** — Async file handling
- **amphp/http-client ^5.3** — Non-blocking HTTP requests
- **PHP extensions:** `fileinfo`, `posix`
- **PHP function `exec()`** — Required only if using multi-process mode in webhook

---

Installation
------------

[](#installation)

Install via Composer:

```
composer require afaztech/neili
```

Or clone repository:

```
git clone https://github.com/afaztech/neili.git
cd neili
composer install
```

Autoloading is PSR-4 (`Neili\` → `src/`).

---

Configuration
-------------

[](#configuration)

Neili uses `Neili\Settings` for configuration.

Example:

```
use Neili\Settings;

$settings = (new Settings())
    ->setAccessToken('TELEGRAM_BOT_TOKEN')
    ->setApiUrl('https://api.telegram.org/bot')
    ->setPollerTimeout(5)
    ->setPollerMaxConcurrency(null);
```

---

Usage
-----

[](#usage)

### Long Polling Example

[](#long-polling-example)

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

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

$poller = new Poller($client);

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

$poller->start();
```

### Webhook Example

[](#webhook-example)

```
use Neili\Client;
use Neili\Settings;

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

$update = $client->handleUpdate('WEBHOOK_SECRET_TOKEN');
if ($update) {
    // Async dispatch example
}
```

---

Multi-process
-------------

[](#multi-process)

Neili supports multi-process update handling in webhook mode using PHP `exec()`.

```
$settings->setUseMultiProcess(true)
         ->setPhpBinary('/usr/bin/php');
```

Incoming webhook updates are automatically forked into separate PHP processes for non-blocking execution.

---

Polling vs Webhook
------------------

[](#polling-vs-webhook)

MethodProsConsStandard WebhookEasy to integrate with HTTP serversSingle-threaded by defaultWebhook with Multi-processNon-blocking, concurrent handling of updatesRequires PHP CLI and `exec()`Long PollingSimple, reliable, no external server config neededContinuous running process---

Settings
--------

[](#settings)

AttributeDescriptionTypeRequiredDefaultapiUrlBase Telegram API URLstringno`https://api.telegram.org/bot`apiVerifySSLEnable TLS verificationboolno`true`timeoutHTTP request timeout (seconds)intno`30`connectionTimeoutHTTP connection timeout (seconds)intno`5`useMultiProcessEnable multi-process modeboolno`false`phpBinaryPath to PHP CLI binary for worker processesstringno`/usr/bin/php`pollerTimeoutLong polling request timeout (seconds)intno`5`pollerBackoffBaseBase seconds for exponential backoffintno`1`pollerMaxBackoffMaximum backoff secondsintno`32`pollerMaxConcurrencyMaximum concurrent async handlersintno`null`accessTokenTelegram bot tokenstringyes`null`loggerPSR-3 compatible logger instanceobjectno`null`---

### Logger

[](#logger)

Neili’s `Settings` constructor **directly accepts a PSR-3 logger**:

- You can pass any PSR-3 compatible logger (e.g., Monolog).
- If you do **not** provide a logger, Neili will use its **default lightweight async logger**.

Example:

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

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

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

This ensures full async logging support in both long-polling and multi-process webhook modes.

---

Keyboard Builder
----------------

[](#keyboard-builder)

`Neili\KeyboardBuilder` provides a fluent interface for building **either** a reply keyboard **or** an inline keyboard. **Important:** You cannot mix inline and regular rows in the same keyboard.

### Methods Table

[](#methods-table)

MethodDescriptionParametersReturnsrowAdd a row of buttons for a reply keyboard`string ...$buttons``self`inlineRowAdd a row of inline buttons with callback data`array $buttons` (`text => callbackData`)`self`inlineConvert the keyboard to inline modenone`self`resizeSet `resize_keyboard` option for reply keyboards`bool $resize = true``self`oneTimeSet `one_time_keyboard` option`bool $oneTime = true``self`clearClear all rows and reset optionsnone`self`buildCompile final array for Telegram APInone`array`### Example: Reply Keyboard

[](#example-reply-keyboard)

```
use Neili\KeyboardBuilder;

$keyboard = (new KeyboardBuilder())
    ->row('Yes', 'No')
    ->row('Maybe')
    ->resize(true)
    ->oneTime(true)
    ->build();
```

### Example: Inline Keyboard

[](#example-inline-keyboard)

```
use Neili\KeyboardBuilder;

$keyboard = (new KeyboardBuilder())
    ->inlineRow(['Button1' => 'callback_1', 'Button2' => 'callback_2'])
    ->inline()
    ->build();
```

---

Client Methods Reference
------------------------

[](#client-methods-reference)

All `Client` methods in Neili are **asynchronous** and return `Amp\Future` objects. A `Future` represents a pending result; you can use `onResolve()` to handle the result or error when it completes.

MethodDescriptionParametersReturnsUsage / NotessendMessageSend a text message`$chatId: int, $text: string, $options: array = []``Future``.onResolve(fn($err, $res) => ...)` gets the result asynchronouslysendPhotoSend a photo to chat`$chatId: int, $media: Media, $options: array = []``Future``Media` object wraps local file path; resolves to API responsesendDocumentSend a document/file`$chatId: int, $media: Media, $options: array = []``Future`Supports local file upload asynchronouslyeditMessageTextEdit the text of a previously sent message`$chatId: int, $messageId: int, $text: string, $options: array = []``Future`Can edit inline or regular messages; async response from Telegram APIdeleteMessageDelete a message`$chatId: int, $messageId: int``Future`Resolves to boolean success/failureforwardMessageForward a message from one chat to another`$fromChatId: int, $toChatId: int, $messageId: int``Future`Returns message object of forwarded messagegetUpdatesFetch updates (long polling)`$params: array = []``Future`Returns array of updates; use in Poller or manual async handlinganswerCallbackQueryRespond to inline button callback`$callbackQueryId: string, $text: string = '', $showAlert: bool = false``Future`Needed to acknowledge inline button pressessendChatActionSend typing / upload action to chat`$chatId: int, $action: string``Future`e.g., `'typing'`, `'upload_photo'`; resolves when action is senthandleUpdateProcess incoming webhook update`$secretToken: string``Future`Resolves to update array if a valid request; integrates with multi-process workflow### How `Future` Works

[](#how-future-works)

`Amp\Future` lets you work asynchronously:

```
$future = $client->sendMessage($chatId, 'Hello async');

$future->onResolve(function($error, $result) {
    if ($error) {
        echo "Error: ".$error->getMessage();
    } else {
        print_r($result); // Telegram API response
    }
});
```

Or `await()` to block until the result is ready (inside an async context):

```
$result = $client->sendMessage($chatId, 'Hello')->await();
print_r($result);
```

**Note:** Every `Client` method returns a `Future`, which means all network requests are **non-blocking** by default, letting you run multiple requests concurrently without waiting.

---

TODO
----

[](#todo)

- Add MTProto support
- Implement login with User Bot

---

License
-------

[](#license)

MIT License — See [LICENSE](LICENSE) file.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance82

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity57

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 ~105 days

Recently: every ~21 days

Total

9

Last Release

93d ago

Major Versions

1.0.0 → 2.0.02025-11-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/69a193cfdda61e7981d7ed0d451533a35edf52421f0d4f8c789d715a6d160a9b?d=identicon)[afaztech](/maintainers/afaztech)

---

Top Contributors

[![AfazTech](https://avatars.githubusercontent.com/u/106348299?v=4)](https://github.com/AfazTech "AfazTech (35 commits)")

---

Tags

asyncamptelegramtelegram bottelegram apineiliafaztechtelegram automation

### Embed Badge

![Health badge](/badges/afaztech-neili/health.svg)

```
[![Health](https://phpackages.com/badges/afaztech-neili/health.svg)](https://phpackages.com/packages/afaztech-neili)
```

###  Alternatives

[danog/madelineproto

Async PHP client API for the telegram MTProto protocol.

3.4k855.0k18](/packages/danog-madelineproto)[amphp/byte-stream

A stream abstraction to make working with non-blocking I/O simple.

393116.2M104](/packages/amphp-byte-stream)[amphp/socket

Non-blocking socket connection / server implementations based on Amp and Revolt.

26539.0M119](/packages/amphp-socket)[amphp/dns

Async DNS resolution for Amp.

19339.2M41](/packages/amphp-dns)[amphp/pipeline

Asynchronous iterators and operators.

7632.7M34](/packages/amphp-pipeline)[amphp/file

Non-blocking access to the filesystem based on Amp and Revolt.

1103.3M94](/packages/amphp-file)

PHPackages © 2026

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