Calling Methods & Types
tueen/telegram provides native, strictly typed support for Telegram Bot API methods and types with full IDE autocompletion, enums, computed property hooks, and forward-compatible fallbacks.
🚀 1. Method Invocations
You can invoke API methods either dynamically or via dedicated Method classes:
Dynamic Method Calls (Recommended)
Call any Telegram method directly using camelCase and named arguments:
use Tueen\Telegram\Enums\ParseMode;
$message = $bot->sendMessage(
chatId: 12345678,
text: "Hello from <b>Tueen</b>!",
parseMode: ParseMode::HTML // Direct Enum instance
);Recommended: Use PHP Named Arguments
In tueen/telegram, always invoke API methods using PHP named arguments (paramName: $value).
// ✅ RECOMMENDED: Explicit, readable, and order-independent
$bot->sendMessage(
text: "Welcome to our bot!",
parseMode: ParseMode::HTML
);
// ❌ AVOID: Fragile positional arguments
$bot->sendMessage(123456, "Hello", null, null, null, null, 'HTML');Why Named Arguments Are Recommended:
- Contextual Auto-Injection: Because parameters like
chatId,businessConnectionId, and query IDs are automatically inferred from the active update, named arguments allow you to supply only the parameters you need (e.g.text: "...") without worrying about parameter position. - No Trailing Nulls: Telegram Bot API methods accept dozens of optional parameters. Named arguments eliminate the need for long lists of
nullplaceholders. - Forward-Compatibility: When Telegram adds new parameters to Bot API methods, named arguments prevent positional shift bugs.
- Self-Documenting: Code is clear and easy to read during code review.
Full IDE autocompletion and parameter docblocks are provided via the @mixin \Tueen\Telegram\Contracts\TelegramMethods contract.
Method Objects (For Custom Pipelines & Architecture)
Every Telegram Bot API method has a dedicated class in Tueen\Telegram\Methods:
use Tueen\Telegram\Methods\SendMessage;
$method = new SendMessage(
chatId: 12345678,
text: "Hello from Tueen!"
);
$message = $bot->send($method);Forward-Compatible Unknown / New Parameters
If Telegram introduces a new parameter before the library updates, you can pass it immediately as a named parameter or via variadic $extra:
// If Telegram adds 'new_feature_flag' tomorrow:
$message = $bot->sendMessage(
chatId: 12345678,
text: "Testing new feature",
newFeatureFlag: true // Seamlessly passed to the API
);Passing Complex & Nested Types (Objects or Arrays)
Methods that accept complex structures (such as reply_markup, link_preview_options, or reply_parameters) accept both strongly-typed Type objects and associative arrays:
A. Using Strongly-Typed Type Objects
use Tueen\Telegram\Types\InlineKeyboardMarkup;
use Tueen\Telegram\Types\InlineKeyboardButton;
use Tueen\Telegram\Types\LinkPreviewOptions;
$bot->sendMessage(
chatId: 123456,
text: "Check out Tueen:",
replyMarkup: new InlineKeyboardMarkup(
inlineKeyboard: [
[
new InlineKeyboardButton(text: '🌐 Website', url: 'https://tueen.dev'),
new InlineKeyboardButton(text: '⭐ GitHub', url: 'https://github.com/tueen/telegram'),
]
]
),
linkPreviewOptions: new LinkPreviewOptions(isDisabled: true)
);B. Using Structured Arrays
You can also pass arrays; the library automatically normalizes, converts nested objects/enums, and serializes them:
$bot->sendMessage(
chatId: 123456,
text: "Choose an option:",
replyMarkup: [
'inline_keyboard' => [
[
['text' => 'Option 1', 'callback_data' => 'opt_1'],
['text' => 'Option 2', 'callback_data' => 'opt_2'],
]
]
]
);🏛️ 2. The Universal Base Type Class
All Telegram Bot API response models (over 400 types such as Message, User, Chat, Update) extend the base class Tueen\Telegram\Types\Type.
Core Features of Type:
- Universal
ok(): boolandisOk(): bool: Every response object guarantees a boolean success check. Real response types always returntrue, whileTueen\Telegram\Types\Errorobjects returnfalse. - Dual Property Access: Access properties using camelCase (
$message->messageId) or snake_case ($message->message_id). ArrayAccessSupport: Access properties using bracket syntax ($message['chat']['id']).JsonSerializable& Stringable: Passing any type tojson_encode($type)or(string)$typeproduces clean, unescaped JSON.- Array Transformation: Call
toArray()ortoJson()to recursively convert the type and all nested objects into primitive arrays or JSON strings. - Bulletproof Forward-Compatibility: If Telegram introduces new fields in the future, they are preserved inside
$extraand accessible dynamically. If Telegram returns an entirely new, unmapped object type, Tueen falls back gracefully to the baseTypeclass without crashing.
⚙️ 3. The Base Method Class
Every Telegram Bot API method is represented by a class extending Tueen\Telegram\Methods\Method.
Core Responsibilities of Method:
- Endpoint Resolution: Defines the API method name (e.g.
'sendMessage'). - Payload Serialization: Prepares and filters parameters, converting nested
Typeobjects, Enums, and JSON-encoded fields. - Multipart & File Upload Detection: Inspects parameters for
InputFileinstances. If any file is present,isMultipart()returnstrueand the HTTP client uploads viamultipart/form-data. - Typed Return Resolution: Defines
returnType()so the HTTP client automatically instantiates and deserializes the response into the appropriate concreteType(e.g.Message::class,BooleanResult::class).
🧩 4. Concerns & Computed Helpers
Rather than bloating generated classes, helper methods and computed properties are organized into reusable traits inside Tueen\Telegram\Types\Concerns\:
HasUpdateHelpersTrait on UpdateConcern TraitHasMessageHelpersTrait on MessageConcern TraitHasChatHelpersTrait on ChatConcern TraitHasUserHelpersTrait on UserConcern TraitHasInlineKeyboardHelpersTrait on InlineKeyboardMarkupConcern TraitHasReplyKeyboardHelpersTrait on ReplyKeyboardMarkupConcern TraitFor a complete guide and code examples of these helpers, see Update & Message Helpers.
📦 5. Custom Result Wrapper Types
When Telegram Bot API methods return primitives (such as boolean values, integer counts, or plain strings), Tueen wraps them in dedicated classes inside Tueen\Telegram\Types\Custom\ so you can always check $result->ok():
BooleanResult(e.g. fromsetWebhook,deleteMessage,pinChatMessage): Wraps abool $value.IntegerResult(e.g. fromgetChatMemberCount): Wraps anint $value.StringResult(e.g. fromexportChatInviteLink,createInvoiceLink): Wraps astring $value.ArrayResult<T>(e.g. fromgetUpdates,forwardMessages): An iterable collection wrapping arrays of typed objects.InputFile: Universal multipart file wrapper for uploads (fromPath,fromResource,fromString,fromStream).
🧭 6. Methods & Types API Reference
Below is the comprehensive catalog of core methods and properties across the Base Type, Base Method, Contextual Auto-Injection, and Custom Wrapper types.
🏛️ Base Type Class (Tueen\Telegram\Types\Type)
ok(): boolisOk(): boolpublic array $rawDataarrayProperty Hookprotected(set) array $rawarrayAsymmetric VisibilitytoArray(): arraytoJson(int $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT): stringoffsetGet(mixed $offset): mixedoffsetExists(mixed $offset): booloffsetSet(mixed $offset, mixed $value): voidoffsetUnset(mixed $offset): void⚙️ Base Method Class (Tueen\Telegram\Methods\Method)
endpoint(): stringgetPayload(): arrayhasUploads(): boolisMultipart(): boolreturnType(): string🎯 Contextual Parameter Auto-Injection
chat_idint|stringContextualbusiness_connection_idstringContextualmessage_thread_idintContextualuser_idintContextualmessage_idintContextualinline_message_idstringContextualcallback_query_idstringContextualinline_query_idstringContextualshipping_query_idstringContextualpre_checkout_query_idstringContextual📦 Custom Wrapper Types (Tueen\Telegram\Types\Custom\)
public readonly bool $valueboolBooleanResultpublic readonly int $valueintIntegerResultpublic readonly string $valuestringStringResultInputFile::fromPath(string $path, ?string $filename = null, ?string $contentType = null): selfInputFile::fromResource(resource $resource, string $filename, ?string $contentType = null): selfInputFile::fromString(string $contents, string $filename, ?string $contentType = null): selfInputFile::fromStream(StreamInterface $stream, string $filename, ?string $contentType = null): self