Skip to main content

Nutgram 5 is here

ยท 7 min read
Luca Patera
Maintainer

Nutgram 5 is out! This release brings dependency injection to class-based commands, lets you control how often your bot reports file transfer progress, and makes it easier to test what your bot sends to Telegram.

Commands and handlersโ€‹

  • Constructor injection for command classes. onCommand() resolves command classes through the container, so a command can receive services such as a repository through its constructor. The Command interface gives the class a way to declare its description while leaving it free to extend an application class. Command registration PR
  • Command menus by language and scope. A command class can return translated descriptions from description(), with * as the fallback, and implement WithScopes to declare where Telegram should list it. Keeping this metadata with the handler makes it possible to maintain, for example, a separate menu for administrators without duplicating registration code. Command descriptions and scopes PR
  • Backed enums in handler patterns. Methods such as onCommand(), onText(), and onCallbackQueryData() accept a backed enum case directly. A button and its handler can share the same enum, so changing a callback value in one place also updates the handler that matches it. Backed enum PR

File transfersโ€‹

  • One progress API for both directions. The Progress object now exposes currentBytes, totalBytes, percentage(), and a ProgressType. The same callback can drive a progress indicator for uploads and downloads. Progress API PR
  • Configurable progress callbacks. withProgress() accepts EveryByte, EveryPercent, EverySecond, and EveryMillisecond triggers or a custom Trigger. When progress is shown in a Telegram message, a time-based trigger can cut down on message edits and help stay within Telegram's rate limits. Progress triggers PR
  • Uploads from streams, URIs, and strings. InputFile now accepts PSR-7 streams and can open URIs supported by PHP. InputFile::makeFromString() lets a bot send a generated CSV without first writing it to disk. In tests, OutgoingResource exposes the uploaded file as a PSR-7 stream too, so assertions can read its contents through the same interface. File handling PR

For a large upload, EverySecond(2) limits progress reports to one every two seconds.

use SergiX44\Nutgram\Support\Progress\Progress;
use SergiX44\Nutgram\Support\Progress\Triggers\EverySecond;
use SergiX44\Nutgram\Telegram\Types\Internal\InputFile;

$bot
->withProgress(function (Progress $progress): void {
echo $progress->percentage() . "%\n";
}, new EverySecond(2))
->sendVideo(video: InputFile::make('video.mp4'), chat_id: $chatId);

Telegram responses and API hooksโ€‹

  • Full chat details. getChat() returns ChatFullInfo so its result matches the Bot API response. Detailed fields such as permissions, available reactions, and business information belong to that response, while ordinary updates can carry the smaller Chat object. ChatFullInfo PR
  • Deleted or inaccessible messages. Telegram can send a reference to a message whose full contents the bot cannot access. Nutgram resolves these references to InaccessibleMessage where the API uses MaybeInaccessibleMessage, including callback queries, pinned messages, and poll option updates. Call isInaccessible() before relying on full message data. Inaccessible messages PR
  • Endpoint-aware response hooks. afterApiRequest() now receives the Telegram endpoint name alongside the decoded response. A shared hook can log or process responses for particular methods without having to infer the method from the payload. Response hook PR
  • Configured API exception handlers. registerApiException() accepts a class name or an ApiException instance. Passing an instance lets the caller supply constructor arguments and state for the handler, such as settings that control its response to a matching error. API exception PR

Server-side conversationsโ€‹

A scheduled job can call Conversation::begin() with user and chat IDs and an optional threadId. Nutgram builds the conversation context from those IDs, so sendMessage() can infer the destination even when there is no incoming Telegram update. This lets a conversation step use the same code whether it begins from a job or from a user's message. Server-side conversations PR

Testingโ€‹

  • Structured request and response assertions. assertRaw() provides RequestData and ResponseData, with dot notation for nested fields. A test can check request parameters, headers, and files alongside the response payload or API error without decoding JSON or parsing multipart bodies itself. Request and response data PR
  • Assertions without a return value. assertRaw() supports void callbacks as well as boolean callbacks. Test suites can use native Pest or PHPUnit assertions inside the callback and get a failure message for the particular check that failed. Assertion callbacks PR

Telegram type handlingโ€‹

Telegram types share a JSON serializer that uses toArray(), so nested objects and backed enum values are encoded consistently. Many Bot API type families, such as InlineQueryResult and BotCommandScope, now use interfaces with resolvers that map Telegram data to the appropriate concrete class. This keeps the contract for each family independent of its implementation and lets concrete objects share the base serializer. Nutgram exposes the hydrator through getHydrator() so extensions can use the same object mapping as the bot. Serialization PR, Telegram type interfaces PR, Container and hydrator PR

The core uses strict types to limit implicit conversions at internal call sites. PHPStan checks those contracts during development, so more type mismatches can be caught before a bot processes a real update. Strict typing PR, PHPStan PR

Upgrading an existing botโ€‹

  • PHP 8.4 is the new minimum. This gives the framework a single baseline for adopting newer language features. The core already uses PHP 8.4 syntax to call methods directly on newly constructed objects. PHP baseline PR
  • Class commands move to onCommand(). Replace registerCommand() and migrate subclasses of the old Command base class to callable handlers. This brings inline and class-based commands through the same registration path and keeps the command name visible where it is bound to a handler. Command registration PR
  • Construct Telegram objects with new. The old ::make() factories duplicated the constructor signatures. A single construction API keeps argument names and defaults in one place. Telegram constructors PR
  • Read detailed chat fields from getChat() and check message types. Code that reads full chat details from an update should fetch them explicitly because Telegram sends those fields in the getChat() response. Narrow a MaybeInaccessibleMessage to Message before reading properties such as text, since the inaccessible variant carries only identifying information. ChatFullInfo PR, Inaccessible messages PR
  • Start threaded conversations with begin(). The optional $threadId now comes before $data, and beginThread() has been removed. This gives conversations a single entry point for both chats and topics. Use data: if you pass initial data without a thread ID. The conversation-specific ID getters were removed because $bot->chatId() and $bot->userId() can now read the conversation's context. Conversation signature change, Server-side conversations PR
  • Pass the webhook secret first. Webhook now takes the secret token before the optional token resolver, so the common setup can use new Webhook($secretToken). Review existing calls that pass positional arguments. Webhook constructor PR
  • Update typed assertRaw() callbacks. Switch from the raw HTTP request and FormDataParser to RequestData and ResponseData. This gives tests a single interface for normal and multipart requests, plus direct access to the corresponding response. Request and response data PR

Full list of changes on GitHub

Starter kit and integrationsโ€‹

Updated versions are available alongside Nutgram 5.

Read the upgrade guide from Nutgram 4.x to 5.x.