Download the PHP package irwinlopez1023/magma4telegram without Composer
On this page you can find all versions of the php package irwinlopez1023/magma4telegram. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package magma4telegram
Magma4Telegram
Magma4Telegram is a clean, modular, and intuitive routing framework for Telegram bots based on webhooks. Built for PHP developers who want an elegant way to structure their Telegram bot commands, handle callback queries, abstract away repetitive API calls, seamlessly manage multi-step conversations, and easily dispatch background jobs.
Features
- Command Routing: Magma parses incoming webhook requests and routes them to a specific handler class.
- Magic Arguments Extraction: Define commands like
/info {name}and Magma magically passes the argument to the handler. - Command Aliases: Define multiple trigger words for the same command (e.g.,
/ping,ping,pongall trigger the same handler). - Conversations: Easily build stateful, multi-step conversation flows that automatically capture and persist user input across different webhook requests.
- Interactive Callbacks: Map inline keyboard button clicks to specific methods inside your class seamlessly.
- Builder Pattern for Keyboards: Create inline keyboards easily via the
Keyboardbuilder. - Dynamic Progress Bars: Easily create and update visual progress bars within messages to keep users informed about long-running tasks.
- Asynchronous Jobs: Dispatch heavy tasks to run completely in the background without blocking the user or the webhook response.
- Modular & Clean Architecture: Keep your code clean by isolating commands, conversations, and jobs in their own respective classes.
- Auto-Discovery: Magma can automatically scan a directory and register all your command, conversation, and job classes dynamically without manual requires.
Installation
Quick Start
Initialize Magma by providing your Telegram Bot Token. You can let Magma discover your classes automatically.
Creating a Basic Command
To create a command, make a new class that extends MagmaCommand and uses the MagmaSend trait (which provides helpers like $this->sendTelegramMessage()).
Define the command structure via the protected string $command property. Arguments inside {} are automatically extracted and accessible via $this->argument('name').
Command Aliases
You can define aliases for a command so it responds to multiple trigger words without duplicating code. For example, /ping can also be triggered by ping or pong.
This command responds to:
/ping(the main command)ping(alias)pong(alias)
Conversations (Multi-step flows)
If you need to collect multiple pieces of information from a user sequentially (e.g., asking for a name, then age, then confirming), you can use Magma's Conversation system.
1. Create a Conversation Class
Create a class extending MagmaConversation. Every step must point to the next() method that will handle the user's next message.
2. Trigger the Conversation from a Command
In any command, instantiate the conversation, passing the Magma instance and the Chat ID, and call start().
Multi-Level Menus
For complex menus with submenus and navigation, extend MagmaMenu instead of MagmaConversation.
Key features:
- Define menus as methods returning button arrays
- Navigate between menus with "back" button
- Automatic message editing (no spam)
- Previous menus are automatically deleted when starting a new one
- Stack-based navigation history
How it works:
$this->showMenu('main')displays the menu defined inmenu_main()- Button clicks are routed to
handleMenuResponse() <<backcallback navigates to the previous menu- Other callbacks trigger
onMenuOptionSelected() - When a new command is executed, the previous menu message is automatically deleted
Menu array format:
['text' => 'Button Label', 'callback' => 'unique_id']— inline button'<<back'— special callback for back navigation
Navigation methods:
$this->showMenu('menu_name')— display a menu$this->goBack()— go to previous menu in stack$this->closeMenu()— close menu and end conversation
Menu command example:
Note: Magma automatically handles menu cleanup. When a user executes any command while a menu is active, Magma deletes the previous menu message before processing the new command.
Background Jobs (Asynchronous Processing)
When a command needs to process heavy tasks (like downloading files, querying an external API, or processing database records), doing it synchronously will block the webhook and slow down the bot.
Magma provides an elegant Background Jobs system using the MagmaJob abstract class and $this->dispatchAsync().
1. Create a Job Class
Create a class that extends MagmaJob. This class will be executed entirely in the background.
2. Dispatch the Job from a Command
Inside your command, call $this->dispatchAsync(Job::class, $payload). The command will immediately finish and respond to Telegram, while the Job will keep running in the background.
Note: Logging is disabled by default. To enable it, add
protected static bool $magmaRunnerLogging = true;to your Job class. Logs are written torunner_log.txt.
Creating Interactive Commands (Inline Buttons)
If your command involves interactive inline keyboards, use the MagmaSend trait. This trait includes answerCallback() to respond to button clicks and map specific callback data to methods in your class.
Define the protected array $callbacks to map a callback_data string to a method name.
The Fluent Keyboard Builder
The Keyboard class provides a fluent Builder Pattern to construct inline keyboards intuitively.
Structure and Rows
You structure your keyboard by defining rows. Calling ->row() creates a new line in the keyboard. Any ->button(...) calls following a ->row() will place those buttons side-by-side on that same line.
Magic URL Detection
Magma's Keyboard class is smart. When adding a button via ->button('Text', 'Data'), Magma inspects the second parameter. If the data is a valid URL, it automatically creates a Telegram URL button. If it's a standard string, it creates a callback_data button that triggers your class methods.
Progress Bars
Magma makes it incredibly easy to provide visual feedback for long-running operations using dynamic progress bars.
To use this feature, your class just needs to use the MagmaSend trait. You can create a progress bar instance using $this->createProgressBar() and then seamlessly update it with new percentages and text via $bar->update().
Advanced: Framework Integration
Magma is fully compatible with popular frameworks like Laravel and Symfony.
Because Magma handles Async Jobs by booting a background PHP process, if you use Magma within Laravel, you should point setBootstrapPath() to a custom bridge file that boots the Laravel Kernel, rather than public/index.php.
Check out the full SKILL.md guidelines internally to see exactly how to write this bridge file and handle artisan properly inside your jobs.
Advanced: Standalone Usage (MagmaSend Trait)
The MagmaSend trait is completely decoupled from the main routing logic. This means you can use it in any external class, background worker, or script outside the primary Magma lifecycle to send messages or documents.
CRITICAL WARNING:
Because Magma automatically injects the bot token when routing requests, using the trait standalone means the token is not automatically set. You MUST manually initialize the bot token by calling $this->MagmaSetBotToken('YOUR_TOKEN'); before attempting to send any requests.
Available Helpers
Through the MagmaSend trait, your command classes inherit various tools to interact with Telegram:
$this->sendTelegramMessage(string $chatId, string $message, string $parseMode = 'html', $replyMarkup = null)$this->sendTelegramPhoto(string $chatId, string $photo, ?string $caption = null, string $parseMode = 'html')$this->sendTelegramVideo(string $chatId, string $video, ?string $caption = null, string $parseMode = 'html')$this->sendTelegramDocument(string $chatId, string $document, ?string $caption = null, string $parseMode = 'html')$this->editTelegramMessage(string $chatId, string $messageId, string $newMessage, string $parseMode = 'html')$this->deleteTelegramMessage(string $chatId, string $messageId)$this->createProgressBar(string $chatId, string $text = "Loading...", int $size = 10): ProgressBar
The MagmaSend trait also provides:
$this->answerCallback(string $text, $buttons = null, string $parseMode = 'html')(Automatically uses the class's$this->chatIdand$this->incomingMessageIdto edit the interaction message).
Proxy Support (Debugging)
For debugging network requests through a proxy (e.g., Charles Proxy, Mitmproxy), configure it in your webhook.php:
To disable the proxy, simply don't call setProxy() or pass null.