Download the PHP package afaztech/neili without Composer

On this page you can find all versions of the php package afaztech/neili. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package neili

Neili — Asynchronous Telegram Bot Library for PHP

Neili is an async-first PHP library built on Amp that streamlines building robust Telegram bots. It ships a non-blocking HTTP client, wrappers for the Telegram Bot API, a long-polling Poller with exponential backoff, concurrency control and error classification, a multi-process webhook handler, a fluent keyboard builder, and a lightweight PSR-3 logger.

If this project helps you, please consider giving it a ⭐ to support future updates and features.

AI-Assisted Development

For everything you need to know about this project — including AI-assisted ("vibe") coding — hand the neili.txt file to your AI assistant. It contains the full project structure, file contents, conventions and architecture.


Table of Contents


Introduction

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


Features


Requirements


Installation

Install via Composer:

Or clone the repository:

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


Quick Start


Configuration

Neili is configured through a single Neili\Settings instance which is passed to the Client constructor.

Settings Reference

Method Getter Type Default Description
setAccessToken(string) getAccessToken() string (required) Telegram bot access token
setApiUrl(string) getApiUrl() string https://api.telegram.org/bot Base API URL (self-hosted Bot API supported)
setApiVerifySSL(bool) isApiVerifySSL() bool true Enable TLS verification
setTimeout(int, ?int) getTimeout() / getConnectionTimeout() int 10 / 5 Transfer timeout (sec) and connection timeout (sec)
setMultiProcess(bool) isMultiProcess() bool false Fork webhook updates into separate PHP processes. Throws RuntimeException when exec() is disabled
setPhpBinary(string) getPhpBinary() string /usr/bin/php Path to PHP CLI binary for multi-process workers
setPollerTimeout(int) getPollerTimeout() int 3 Telegram long-poll timeout in seconds
setPollerBackoffBase(int) getPollerBackoffBase() int 1 Exponential backoff base (sec)
setPollerMaxBackoff(int) getPollerMaxBackoff() int 32 Maximum backoff delay (sec)
setPollerMaxConcurrency(?int) getPollerMaxConcurrency() ?int null Max concurrent async update handlers (null = unlimited)
setHttpClient(object) getHttpClient() ?object null Inject a pre-built HTTP client (must expose a request() method)
(constructor) getLogger() LoggerInterface Neili\Logger('/neili.log') Any PSR-3 logger

Custom Logger

Settings accepts any PSR-3 logger. If omitted, Neili uses its own lightweight async file logger.

Default async logger — Neili\Logger:

Method Description
__construct(string $filePath, bool $printToConsole = true) Path to log file and whether to mirror to stdout
log($level, $message, array $context = []) PSR-3 method; interpolates {key} placeholders from $context
close(): Future Flushes and closes the file handle asynchronously

Custom HTTP Client

Inject any client exposing a request(Request, ?Cancellation): Response method. The client's timeouts can be overridden per-request by Neili.

You can also swap the transport at runtime:


Usage

Long Polling

To stop from inside a handler:

Webhook

Set the webhook once (from the CLI, or via a setup script):

Multi-Process Webhook

Enables non-blocking handling of incoming updates on plain PHP-FPM / Apache deployments. Each update is forked into a fresh PHP process via exec().

The worker reads the base64-encoded update from $argv[1] and re-enters handleUpdate() in CLI mode.

Polling vs Webhook

Method Pros Cons
Long Polling Simple, no external server config Requires a continuously running process
Standard Webhook Easy to integrate with any HTTP server Single-threaded by default
Multi-Process Webhook Non-blocking, concurrent update handling Requires PHP CLI and exec()

Error Handling

Every Client method returns an Amp\Future. When the underlying HTTP request fails or Telegram returns a non-OK payload, Neili throws one of the following exceptions.

Exception Hierarchy

Exception Thrown When Retry?
NeiliException Base class for all Neili errors —
TransientException HTTP 5xx, invalid JSON, transport errors (DNS, TCP, TLS, timeouts) ✅ Yes
RateLimitException Telegram returns error_code: 429 ✅ After getRetryAfter() seconds
PermanentException Any other non-OK Telegram response (400, 401, 403, 404, …) ❌ No

API surface:

Poller Error Policy

The Poller classifies each exception and reacts accordingly:

Exception Poller Behavior
RateLimitException Sleeps exactly retry_after seconds, then continues (ignores exponential backoff)
TransientException Logs a warning, applies exponential backoff (base × 2^n, capped at pollerMaxBackoff, with up to 1 s of positive jitter) and continues. After 3 consecutive transient failures the underlying HTTP client is rebuilt via Client::reconnect()
PermanentException Logs an error, stops the poller, and rethrows
Any other Throwable Treated as transient — logged and retried with backoff

A successful getUpdates call resets all failure counters.


Poller Reference

Lifecycle

Method Signature Description
start start(bool $discardOldUpdates = true): void Blocks; runs the async polling loop. When $discardOldUpdates is true, a short-poll (timeout=0) fetch is issued first to skip the backlog
stop stop(): void Signals the loop to exit after the current iteration
isRunning isRunning(): bool true while the poll loop is active

Global Handlers

Method Description
onUpdate(callable $cb) Fires for every update, in addition to type-specific handlers
onError(callable $cb) Signature fn(\Throwable $e, array $update, string $type): void. Called in addition to logging; exceptions inside it are swallowed

Type-Specific Handlers

onMessage, onEditedMessage, onMessageReaction, onMessageReactionCount, onChatBoost, onRemovedChatBoost, onChannelPost, onEditedChannelPost, onInlineQuery, onChosenInlineResult, onCallbackQuery, onShippingQuery, onPreCheckoutQuery, onPoll, onPollAnswer, onMyChatMember, onChatMember, onChatJoinRequest, onBusinessMessage, onEditedBusinessMessage, onDeletedBusinessMessage, onBusinessConnection, onGuestMessage, onPurchasedPaidMedia, onManagedBot, onSubscription, onStoppedMessageGeneration.

Each accepts a callable(array $update): void and multiple callbacks can be registered for the same type.

Concurrency

If setPollerMaxConcurrency(n) is configured, handler execution is gated by an Amp\Sync\LocalSemaphore of size n. Each update is dispatched as its own async fiber, so slow handlers do not block the polling loop.


Keyboard Builder

Neili\KeyboardBuilder provides a fluent API for both reply and inline keyboards. Mixing the two types on the same builder throws a RuntimeException.

Methods

Method Signature Description
row row(string ...$buttons): self One row of plain reply-keyboard buttons
replyRow replyRow(array $buttons): self One row of custom KeyboardButton payloads
inlineRow inlineRow(array $textToCallback): self Inline buttons using callback_data
inlineCallbackRow inlineCallbackRow(array $textToCallback): self Alias of inlineRow
inlineUrlRow inlineUrlRow(array $textToUrl): self Inline buttons with url
inlineButtonRow inlineButtonRow(array $buttons): self Full inline row from raw payloads
inlineButton inlineButton(array $button): self Single inline button as its own row
inline inline(): self Forces inline mode without adding rows
resize resize(bool $resize = true): self Reply keyboard resize_keyboard
oneTime oneTime(bool $oneTime = true): self Reply keyboard one_time_keyboard
persistent persistent(bool $state = true): self Reply keyboard is_persistent
inputFieldPlaceholder inputFieldPlaceholder(string): self Reply keyboard placeholder (1–64 chars)
selective selective(bool $selective = true): self Reply + inline selective
forceReply forceReply(bool $state = true): self Adds force_reply to the built markup
clear clear(): self Resets all rows and flags
build build(): array Emits the final array for reply_markup

Static Helpers

Media

Wrap local files in a Media object. The constructor validates existence and resolves the real path.

When any Media is passed to a send* or edit* method, Neili issues a multipart/form-data request and rewrites the payload with attach://<key> references.

Uploading Media

sendMediaGroup() accepts a mix of Media objects, remote URLs, and raw InputMedia arrays. It enforces Telegram's 10-item maximum.

sendPaidMedia() accepts an array of Media objects or InputPaidMedia arrays, and requires star_count:

Methods that transparently recognize Media inside their payload:


File Downloads

downloadFile() streams the response body to disk without buffering the whole file in memory.


Client Methods Reference

All methods return Amp\Future. Use ->await() inside an async context or ->onResolve() / ->map() / ->catch() for callback style.

Messages

Method Description
sendMessage(int\|string $chatId, string $text, ...) Send a text message. Supports parse_mode, entities, reply_parameters, link_preview_options, message_thread_id, direct_messages_topic_id, business_connection_id, suggested_post_parameters, ephemeral_message_parameters, etc.
reply(int\|string $chatId, int $replyToMessageId, string $text, ?array $keyboard = null, ?array $extraParams = null) Shorthand for sendMessage with reply_parameters
editMessageText(...) Edit a text or rich message. Requires either $text or $richMessage
editMessageCaption(...) Edit a caption
editMessageMedia(...) Replace animation/audio/document/photo/video; supports local Media uploads
editMessageLiveLocation(...) Edit an ongoing live location
editMessageReplyMarkup(...) Replace only the keyboard
stopMessageLiveLocation(...) Halt a live location before its live_period expires
deleteMessage(int\|string $chatId, int $messageId) Delete one message
deleteMessages(int\|string $chatId, array $messageIds) Delete many messages in one call
forwardMessage(...) Forward a single message
forwardMessages(...) Forward multiple messages
copyMessage(...) Copy a single message
copyMessages(...) Copy multiple messages
setMessageReaction(...) Set or replace reactions
deleteMessageReaction(...) Remove a specific reaction
deleteAllMessageReactions(...) Remove up to 10,000 recent reactions
sendChatAction(...) typing, upload_photo, record_video, etc.
sendDice(...) Animated dice/emoji throw
sendPoll(...) Regular or quiz poll. Options may be plain strings or InputPollOption arrays (with media)
stopPoll(...) Close a poll
sendVenue(...) Venue location with title + address
sendLocation(...) Static or live location
sendContact(...) Share a phone contact

Examples:

Media

SendsMedia — see Media Uploads.

Method Notes
sendPhoto / sendLivePhoto Supports caption, parse_mode, caption_entities, show_caption_above_media, has_spoiler
sendPaidMedia star_count required; rejects empty/invalid media arrays
sendVideo Supports duration, width, height, thumbnail, cover, start_timestamp, supports_streaming
sendAudio Supports duration, performer, title, thumbnail
sendDocument Supports thumbnail, disable_content_type_detection
sendAnimation Supports duration, width, height, has_spoiler, thumbnail
sendSticker Optional emoji
sendVoice Optional duration
sendVideoNote Optional duration, length, thumbnail
sendMediaGroup Max 10 items; prefer reply_parameters over the legacy reply_to_message_id

Chat Management

ManagesChats — getChat, getChatMemberCount, getChatMembersCount (deprecated alias), pinChatMessage, unpinChatMessage, unpinAllChatMessages, setChatTitle, setChatDescription, setChatPhoto, deleteChatPhoto, leaveChat, setChatPermissions, exportChatInviteLink, createChatInviteLink, editChatInviteLink, createChatSubscriptionInviteLink, editChatSubscriptionInviteLink, revokeChatInviteLink, setChatStickerSet, deleteChatStickerSet, getUserPersonalChatMessages, setChatMenuButton, getChatMenuButton.

Chat Members

ManagesChatMembers — getChatMember, getChatAdministrators, banChatMember, unbanChatMember, restrictChatMember, promoteChatMember, setChatAdministratorCustomTitle, setChatMemberTag, banChatSenderChat, unbanChatSenderChat, approveChatJoinRequest, declineChatJoinRequest, answerChatJoinRequestQuery, sendChatJoinRequestWebApp, getUserChatBoosts, getUserProfilePhotos.

Stickers

ManagesStickers — getStickerSet, uploadStickerFile, createNewStickerSet, addStickerToSet, deleteStickerFromSet, setStickerPositionInSet, replaceStickerInSet, setStickerSetThumbnail, setStickerSetTitle, deleteStickerSet, setCustomEmojiStickerSetThumbnail, setStickerEmojiList, setStickerKeywords, setStickerMaskPosition, getCustomEmojiStickers.

Forum Topics

ManagesForumTopics — createForumTopic, editForumTopic, closeForumTopic, reopenForumTopic, deleteForumTopic, unpinAllForumTopicMessages, unpinAllGeneralForumTopicMessages, getForumTopicIconStickers, editGeneralForumTopic, closeGeneralForumTopic, reopenGeneralForumTopic, hideGeneralForumTopic, unhideGeneralForumTopic.

Bot Profile

ManagesBotProfile — getMe, setMyName, getMyName, setMyDescription, getMyDescription, setMyShortDescription, getMyShortDescription, setMyCommands, deleteMyCommands, getMyCommands, setMyDefaultAdministratorRights, getMyDefaultAdministratorRights, setMyProfilePhoto, removeMyProfilePhoto, setUserEmojiStatus, getUserProfileAudios, logOut, close.

Payments & Stars

HandlesPayments — sendInvoice, createInvoiceLink, answerShippingQuery, answerPreCheckoutQuery, getMyStarBalance, getStarTransactions, refundStarPayment, editUserStarSubscription.

For Telegram Stars, pass currency: 'XTR' and providerToken: ''. For subscriptions use subscriptionPeriod: 2592000 (30 days).

Games

HandlesGames — sendGame, setGameScore, getGameHighScores.

Either provide both chatId and messageId, or inlineMessageId.

Inline Queries

HandlesInlineQueries — answerCallbackQuery, answerInlineQuery, answerWebAppQuery, answerGuestQuery, savePreparedInlineMessage, savePreparedKeyboardButton.

Updates & Webhooks

HandlesUpdates — handleUpdate(?string $secretToken = null): array, getUpdates(?int $offset, ?int $limit, ?int $timeout, ?array $allowedUpdates, ?array $extraParams): Future.

HandlesWebhooks — setWebhook, deleteWebhook, getWebhookInfo.

Stories

HandlesStories — postStory, repostStory, editStory, deleteStory.

Business Accounts

HandlesBusiness — getBusinessConnection, readBusinessMessage, deleteBusinessMessages, setBusinessAccountName, setBusinessAccountUsername, setBusinessAccountBio, setBusinessAccountProfilePhoto, removeBusinessAccountProfilePhoto, setBusinessAccountGiftSettings, getBusinessAccountStarBalance, transferBusinessAccountStars, getBusinessAccountGifts, convertGiftToStars, upgradeGift, transferGift, sendChecklist, editMessageChecklist.

Gifts

HandlesGifts — getAvailableGifts, sendGift, giftPremiumSubscription, getUserGifts, getChatGifts.

sendGift requires exactly one of userId or chatId — otherwise an InvalidArgumentException is thrown.

Verification

HandlesVerification — verifyUser, verifyChat, removeUserVerification, removeChatVerification.

Managed Bots

ManagesManagedBots — getManagedBotToken, replaceManagedBotToken, getManagedBotAccessSettings, setManagedBotAccessSettings.

Suggested Posts

HandlesSuggestedPosts — approveSuggestedPost, declineSuggestedPost.

Ephemeral Messages

HandlesEphemeralMessages — editEphemeralMessageText, editEphemeralMessageMedia, editEphemeralMessageCaption, editEphemeralMessageReplyMarkup, deleteEphemeralMessage.

Rich Messages

HandlesRichMessages — sendRichMessage, sendRichMessageDraft, sendMessageDraft.

sendRichMessage supports embedded Media objects — they are uploaded via multipart and rewritten to attach:// references automatically.

Telegram Passport

HandlesPassport — setPassportDataErrors.

Dynamic Method Calls

Client::__call() maps any unknown method to a Telegram API call with the first argument as the payload:


TODO


License

MIT License — see the LICENSE file.


All versions of neili with dependencies

PHP Build Version
Package Version
Requires php Version >=8.1
amphp/file Version ^3.2
amphp/http-client Version ^5.3
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package afaztech/neili contains the following files

Loading the files please wait ...