telegraph icon indicating copy to clipboard operation
telegraph copied to clipboard

Allow deferred bot/chat assignment for composed messages

Open AnatolyAstapov opened this issue 8 months ago • 0 comments

Summary This PR makes Telegraph message composition more flexible by allowing a message to be built before a bot and chat are assigned.

Previously, calling builders like Telegraph::html(...) immediately tried to resolve chat_id, which made it impossible to compose a reusable message in one service and decide the destination bot/chat later in another service.

With this change, message builders can now create a Telegraph payload without an attached chat, and the required chat_id is resolved only when the request is finalized and sent.

Problem A common use case is to build the same message once and send it to multiple recipients:

$message = Telegraph::html(implode(PHP_EOL, $lines))
    ->keyboard(...)
    ->withoutPreview();

$message->bot($botA)->chat($chatA)->send();
$message->bot($botB)->chat($chatB)->send();

Before this PR, this failed at composition time because html() called setMessageText(), which immediately tried to populate chat_id and threw:

No TelegraphChat defined for this request

That made reusable message composition impossible unless the builder already knew the destination chat.

What changed

  • Deferred chat_id resolution for composed text messages.
  • Added centralized chat payload preparation before request execution.
  • Kept validation strict at send time: requests that actually require a chat still fail if no chat is defined when sending.
  • Preserved existing eager behavior for attachments and other APIs that already rely on immediate chat resolution.
  • Preserved existing payload ordering where needed to avoid breaking snapshot tests.
  • Fixed fake/scoped payload behavior so poll, quiz, and editMedia fakes inherit bot/chat state correctly.

Behavior after this PR This now works:

$message = Telegraph::html('Hello')
    ->keyboard(...)
    ->withoutPreview();

$message->bot($channel->bot)->chat($channel->chat_id)->send();

And it still correctly fails if a chat is still missing at send time for endpoints that require it.

Implementation notes

  • Introduced deferred chat synchronization in the request preparation flow.
  • Restricted “chat required” validation to a defined set of endpoints instead of applying it too broadly.
  • Restored eager missingChat behavior for attachments to avoid changing existing API contracts.
  • Updated tests to cover deferred composition and send-time validation.

Result This enables a cleaner separation of responsibilities:

  • one service can build a reusable Telegram message;
  • another service can decide which bot/chat should receive it.

AnatolyAstapov avatar Mar 16 '26 15:03 AnatolyAstapov